This question already has an answer here:
- Access struct property by name 2 answers
Please see the code sample below (playground). I think my question is explained by the code itself. For some reason, I want to use a string variable to determine the struct field name, not explicitly mention the field. I know this is possible, but I don't know how to start :(.
package main
import "fmt"
type Usage struct {
Primary *Rendition
Additional *Rendition
}
type Rendition struct {
ID int
SomeField string
}
func main() {
r1 := Rendition{
ID: 1,
SomeField: "somevalue",
}
var myName = "Primary"
u1 := Usage{
// now instead of explicit mention "primary", I want to use the value of
// the above myName var (which is "Primary") in order to fill the struct.
Primary: &r1,
}
fmt.Print(u1.Primary)
}
Aucun commentaire:
Enregistrer un commentaire