reflect value Interface and pointer receiver

假装没事ソ 提交于 2020-05-15 08:54:06

问题


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
}

When I implement my struct with

func (id SomeStruct) IsZero() bool {
    return id.ID == ""
}

it works. But when I implement the IsZero method with a pointer receiver:

func (id *SomeStruct) IsZero() bool {
        return id.ID == ""
 }

the type assertion fails and IsZero does not get executed.

Can someone explain this to me?


回答1:


Presumably somewhere above the case reflect.Struct there is a switch on reflect.ValueOf(...).Kind()

If you look at the Kinds in the reflect package, docs here

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.

You'd need to do v.Elem().Interface().(Zeroer) to get the underlying element

Runnable example here https://play.golang.org/p/tx1zgD7Ri0E



来源:https://stackoverflow.com/questions/50163955/reflect-value-interface-and-pointer-receiver

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!