-3

I'm trying to access to a struct properties with a variable who contains the property key.

For example, i got this struct :

type person struct {
    name string
    age  int
}

I have a variable "property" who contain a string value "age".

I would like to access to the age with something like person.property ?

Do you think it is possile in golang ?

emma_lanome
  • 45
  • 1
  • 8
  • 3
    It's possible with [reflection](https://golang.org/pkg/reflect/), but a very unusual requirement. If you tell us *why* you think you need this we can maybe show you a more appropriate solution. – Peter Apr 09 '21 at 10:01

1 Answers1

3

If you're looking for something like person[property] like you do in Python or JavaScript, the answer is NO, Golang does not support dynamic field/method selection at runtime.

But you can do it with reflect:

import (
    "fmt"
    "reflect"
)

func main() {
    type person struct {
        name string
        age  int
    }

    v := reflect.ValueOf(person{"Golang", 10})
    property := "age"
    f := v.FieldByName(property)
    fmt.Printf("Person Age: %d\n", f.Int())
}
shizhz
  • 11,715
  • 3
  • 39
  • 49