1

How can I get the underlying value of a field having the fields name as a string?

I understand I need to use reflection but if I do will I have to continue using it throughout my code? Is there any way to assert?

I would just like to get the value of the field, the underlying struct, in this case a []Dice.

http://play.golang.org/p/KYOH8C7TAl

type Dice struct {
    In int
}

type SliceNDice struct {
    Unknown []Dice
}

func main() {
    structure := SliceNDice{make([]Dice, 10)}

    refValue := reflect.ValueOf(&structure).Elem().FieldByName(string("Unknown"))
    slice := refValue.Slice(0, refValue.Len())

    // cannot range over slice (type reflect.Value)
    //for i,v := range slice {
    //    fmt.Printf("%v %v\n", i, v.In)
    //}

    for i := 0; i < slice.Len(); i++ {
        v := slice.Index(i)
        // v.In undefined (type reflect.Value has no field or method In)
        fmt.Printf("%v %v\n", i, v.In)
    }

}

1 Answer 1

1

If you know that the "Unknown" field is of type []Dice, you can use Value.Interface to get the underlying value and convert it with a type assertion:

slice := refValue.Interface().([]Dice)

for i,v := range slice {
     fmt.Printf("%v %v\n", i, v.In)
}

http://play.golang.org/p/2lV106b6dH

Sign up to request clarification or add additional context in comments.

1 Comment

Silly detail: s/reflect.Interface/Value.Interface/; the former exists, but is something else.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.