英文:
golang StructField's name returning a pointer?
问题
我想迭代结构体的字段并获取每个字段的名称。所以我在play.golang.org上尝试了这个:http://play.golang.org/p/C2cWzEVRBl
为了方便起见,我引用了以下代码:
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func main() {
p := Person{"allan", 10}
v := reflect.ValueOf(p)
num := v.NumField()
for i := 0; i < num; i++ {
fv := v.Field(i)
t := reflect.TypeOf(fv)
fmt.Println("struct name:", t.Name())
}
}
在我的运行中,它的输出如下:
struct name: 0x203a0
struct name: 0x203a0
然而,我本来期望它显示为:
struct name: Name
struct name: Age
你能解释为什么它显示为一个地址,并且如何正确地获取结构体字段的名称吗?
英文:
I want to iterate over the fields of a struct and get each fields name. So I try this on play.golang.org : http://play.golang.org/p/C2cWzEVRBl
for convenience, I quote the
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func main() {
p := Person{"allan", 10}
v := reflect.ValueOf(p)
num := v.NumField()
for i := 0; i < num; i++ {
fv := v.Field(i)
t := reflect.TypeOf(fv)
fmt.Println("struct name:",t.Name)
}
}
in my run, it output as follow:
struct name: 0x203a0
struct name: 0x203a0
However, I had been expecting it to be
struct name: Name
struct name: Age
Can you explain why it's displayed as a address and how can I correctly get a struct field's name ?
答案1
得分: 2
最后找到了问题的原因...
不应该在字段Value
上使用TypeOf()
,而是应该在原始结构上使用TypeOf()
,然后使用Field()
来检索StructField
。
以下是修正后的代码:
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func main() {
p := Person{"allan", 10}
v := reflect.ValueOf(p)
num := v.NumField()
for i := 0; i < num; i++ {
//fv := v.Field(i)
//t := reflect.TypeOf(fv)
// 不应该在字段 Value 上使用 TypeOf()!
// 应该在原始结构上使用 TypeOf(),然后使用 Field() 来检索 StructField
sf := reflect.TypeOf(p).Field(i)
fmt.Println("字段名:", sf.Name)
}
}
希望对你有帮助!
英文:
Finally figure out the problem...
SHOULD NOT USE TypeOf() on a field Value
, Use TypeOf on original struct, and use Field() to retrieve StructField
working code as below:
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func main() {
p := Person{"allan", 10}
v := reflect.ValueOf(p)
num := v.NumField()
for i := 0; i < num; i++ {
//fv := v.Field(i)
//t := reflect.TypeOf(fv)
// SHOULD NOT USE TypeOf() on a field Value!
// Use TypeOf on original struct, and use Field() to retrieve StructField
sf := reflect.TypeOf(p).Field(i)
fmt.Println("Field name:",sf.Name)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论