I am new to golang and migrating from php to golang.
I am trying to do something like below stuff, where I want field name age
to get assigned from variable test. Is this possible in golang?
In php, we have provision like $$test, looking something similar in golang as well.
package main
import "fmt"
// This `person` struct type has `name` and `age` fields.
type person struct {
name string
age int
}
func main() {
var test = "age"
fmt.Println(person{name: "Alice",test: 30})
}
This is just sample code replicating my use case.
You have three options, in rough order of preference:
1) An if/switch statement:
var p = &person{}
if key == "age" {
p.age = value
}
2) Use a map instead of a struct:
var p = map[string]interface{}
p[key] = value
3) Use reflection. See this question for details, but generally you should avoid reflection. It's slow, and non-idiomatic, and it only works with exported fields (your example uses un-exported fields, so as written, is not a candidate for reflection anyway).