-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 ?

1
  • 3
    It's possible with reflection, but a very unusual requirement. If you tell us why you think you need this we can maybe show you a more appropriate solution. Commented Apr 9, 2021 at 10:01

1 Answer 1

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())
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.