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)
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
.