需要帮助理解为什么会这样。可以使用指针或值调用 PrintFoo。为什么不是 NumField?
http://play.golang.org/p/Kw16ReujRx
type A struct {
foo string
}
func (a *A) PrintFoo(){
fmt.Println("Foo value is " + a.foo)
}
func main() {
a := &A{foo: "afoo"}
(*a).PrintFoo() //Works - no problem
a.PrintFoo() //Works - no problem
reflect.TypeOf(*a).NumField() //Works - no problem - Type = main.A
reflect.TypeOf(a).NumField() //BREAKS! - Type = *main.A
}
最佳答案
来自documentation :
// NumField returns the number of fields in the struct v.
// It panics if v's Kind is not Struct.
func (v Value) NumField() int
你在一个指针上调用它,你必须在一个结构上调用它,因为 example :
fmt.Println(reflect.Indirect(reflect.ValueOf(a)).NumField())
fmt.Println(reflect.Indirect(reflect.ValueOf(*a)).NumField())
当您不确定您的值是否为指针时,请使用 reflect.Indirect :
Indirect returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.
//编辑:
NumField
在 Value
上被调用,而不是你的实际对象,例如你这样做:
func main() {
a := &A{foo: "afoo"}
fmt.Printf("%#v\n", reflect.TypeOf(*a))
fmt.Printf("%#v\n", reflect.TypeOf(a))
}
你会得到:
//*a
&reflect.rtype{size:0x8, ...... ptrToThis:(*reflect.rtype)(0xec320)}
//a
&reflect.rtype{size:0x4, ...... ptrToThis:(*reflect.rtype)(nil)}
如您所知,这是一个完全不同的野兽。
- 第一个包含有关指针的信息,因此
ptrToThis
指向实际结构。 - 第二个保存有关结构本身的信息。
关于golang - 指针特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336537/