Golang:获取具有字段名称作为字符串的基础结构

问题描述:

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
", 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
", i, v.In)
    }

}

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
", i, v.In)
}

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