dqx13503925528 2018-05-03 21:15
浏览 41
已采纳

反映值接口和指针接收器

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条回答 默认 最新

  • 普通网友 2018-05-04 10:36
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?