[英]Necessity of calling Elem() method on pointer-receiver for struct reflection
I have struct我有结构
type ChartOpts struct {
Name mypakage.MyType
Repo mypakage.MyType
}
on which I want to set a receiver for reflection.我想在其上设置一个反射接收器。
func (chartOpts *ChartOpts) BindFlags() {
fields := reflect.TypeOf(chartOpts)
values := reflect.ValueOf(chartOpts)
num := fields.NumField()
fmt.Println(fields, values, num)
}
The above code panics上面的代码恐慌
panic: reflect: NumField of non-struct type *app.ChartOpts
Why do I need to call the Elem()
method to fix this?为什么我需要调用
Elem()
方法来解决这个问题?
func (chartOpts *ChartOpts) BindFlags() {
fields := reflect.TypeOf(chartOpts)
values := reflect.ValueOf(chartOpts)
num := fields.Elem().NumField()
fmt.Println(fields, values, num)
}
Because type of chartOpts
is *ChartOpts
, a pointer to ChartOpts
type.因为
chartOpts
的类型是*ChartOpts
,一个指向ChartOpts
类型的指针。 Pointers have no fields, only structs.指针没有字段,只有结构。 Calling
Elem()
on its type descriptor will return a type descriptor that represents / describes ChartOpts
, a struct type which does have fields.在其类型描述符上调用
Elem()
将返回一个表示 / 描述ChartOpts
的类型描述符,这是一种具有字段的结构类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.