golang - 指针特性

标签 go

需要帮助理解为什么会这样。可以使用指针或值调用 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.

//编辑:

NumFieldValue 上被调用,而不是你的实际对象,例如你这样做:

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/

相关文章:

mongodb - 使用结构为 Controller 进行模型子类化

go - 从使用 Go 制作的生产服务器中获取 panic

google-app-engine - 应用程序.yaml : wildcard in URL with static_dir?

api - Go - 中间件阻止每个请求的 MIME 类型

http - 如何使用 Go http 包提供共享结构?

go - 如何使用 `godoc -http=:6060` 显示内置类型?

Golang 在测试中使用 Null*s

go - exec.Command 错误,没有输出到 stdout 或 stderr

go - 获取 slice 中值的指针

go - 哪种扫描用于从字符串中读取 float ?