1

I have a go struct and I need to work with one of the fields. However I am starting with a string. How do I case it to get the field itself.

package main
import "fmt"

func main() {

    type Point struct{
  x int
  y int
}

    pt := Point{x:2, y:3}
    a  := "x"
    fmt.Printf("%s", pt.a)
} 

Since a = "x" I am expecting pt.x = 2. Here's the error message it prints out. I am definitely starting with a string so I can't just remove the quotation marks.

$ go run point.go
# command-line-arguments
./point.go:14: pt.a undefined (type Point has no field or method a)
12
  • Is this Point struct your actual use case? Are you able to explain a little more about where you are trying to do this? Commented Oct 25, 2015 at 14:31
  • What do you expect this code to do? Commented Oct 25, 2015 at 14:32
  • The field names of Point are x and y, not a. Commented Oct 25, 2015 at 14:33
  • why doesn't it give pt.x = 2 ? Commented Oct 25, 2015 at 14:33
  • 1
    string "x" has nothing to do with field pt.x Commented Oct 25, 2015 at 14:42

1 Answer 1

3

If you need to access a field whose name is given as a string, you have no choice but to use reflection. Go ain't Python. :-)

This blog has a nice explanation.

Here is the reflect package documentation.

But note that reflection should usually be used as a last resort only. It removes the static type safety and is detrimental for performance.

What are you really looking for? There may be a way to address your requirements without using reflection. For example, if you don't need methods attached to your struct, you could use map[string]int.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.