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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了