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

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

报告相同问题?

悬赏问题

  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员