英文:
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(&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
得分: 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("%v %v\n", i, v.In)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论