golang的StructField的name返回一个指针吗?

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

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 (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{&quot;allan&quot;, 10}

	v := reflect.ValueOf(p)
	num := v.NumField()
	for i := 0; i &lt; num; i++ {
		fv := v.Field(i)
		t := reflect.TypeOf(fv)
		fmt.Println(&quot;struct name:&quot;,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 (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{&quot;allan&quot;, 10}

	v := reflect.ValueOf(p)
	num := v.NumField()
	for i := 0; i &lt; 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(&quot;Field name:&quot;,sf.Name)
		
	}
}

huangapple
  • 本文由 发表于 2013年12月27日 19:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/20800113.html
匿名

发表评论

匿名网友

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

确定