反映值接口和指针接收器 [英] reflect value Interface and pointer receiver
问题描述
在用于golang的mongodb驱动程序中,包含以下代码:
In the mongodb driver for golang there is the following piece of code:
case reflect.Struct:
if z, ok := v.Interface().(Zeroer); ok {
return z.IsZero()
}
return false
接口清零器的定义如下:
Interface Zeroer is defined like this:
type Zeroer interface {
IsZero() bool
}
当我使用
func (id SomeStruct) IsZero() bool {
return id.ID == ""
}
有效.但是,当我使用指针接收器实现IsZero方法时:
it works. But when I implement the IsZero method with a pointer receiver:
func (id *SomeStruct) IsZero() bool {
return id.ID == ""
}
类型声明失败,并且IsZero无法执行.
the type assertion fails and IsZero does not get executed.
有人可以向我解释吗?
推荐答案
大概是case reflect.Struct
上方的某个位置,在reflect.ValueOf(...).Kind()
Presumably somewhere above the case reflect.Struct
there is a switch on reflect.ValueOf(...).Kind()
如果您查看反射包中的Kind
,请在此处文档
If you look at the Kind
s in the reflect package, docs here
Struct
是其中的一种,而Ptr
是另一种.在switch语句中,它不匹配,因为IsZero()
方法的接收者中定义的类型*SomeStruct
是Ptr
而不是Struct
.
Struct
is one of the kinds and Ptr
is another. In the switch statement it is not matching because the kind *SomeStruct
as defined in the receiver of the IsZero()
method is Ptr
and not Struct
.
您需要执行v.Elem().Interface().(Zeroer)
才能获取基础元素
You'd need to do v.Elem().Interface().(Zeroer)
to get the underlying element
此处为可运行示例 https://play.golang.org/p/tx1zgD7Ri0E
这篇关于反映值接口和指针接收器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!