Golang: Get underlying struct having the fields name as a string

huangapple go评论74阅读模式
英文:

Golang: Get underlying struct having the fields name as a string

问题

如何通过字段名的字符串形式获取字段的底层值?

我了解我需要使用反射,但如果我这样做,我是否需要在整个代码中继续使用它?有没有什么方法可以断言?

我只想获取字段的值,即底层结构,在这种情况下是一个[]Dice。

type Dice struct {
    In int
}

type SliceNDice struct {
    Unknown []Dice
}

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

    refValue := reflect.ValueOf(&structure).Elem().FieldByName("Unknown")
    slice := refValue.Slice(0, refValue.Len())
    
    // 无法对切片进行迭代(类型为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未定义(类型reflect.Value没有字段或方法In)
        fmt.Printf("%v %v\n", i, v.In)
    }
}

希望对你有所帮助!

英文:

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(&amp;structure).Elem().FieldByName(string(&quot;Unknown&quot;))
    slice := refValue.Slice(0, refValue.Len())
    
    // cannot range over slice (type reflect.Value)
    //for i,v := range slice {
    //    fmt.Printf(&quot;%v %v\n&quot;, i, v.In)
    //}

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

}

答案1

得分: 1

如果你知道"Unknown"字段的类型是[]Dice,你可以使用Value.Interface来获取底层值,并通过类型断言进行转换:

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

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

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

英文:

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(&quot;%v %v\n&quot;, i, v.In)
}

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

huangapple
  • 本文由 发表于 2013年8月28日 01:35:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/18472019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定