doudeng1870 2015-05-21 07:56
浏览 212
已采纳

为什么在golang中连续声明“ var _ I = T {}”和“ var _ I =&T {}”?

When I read a copy of the docker/distribution source code, I find there are variables declared which make me quite confused. The code is:

var _ FileInfo = FileInfoInternal{}
var _ FileInfo = &FileInfoInternal{}

I don't know what the declare mean, and hope to get some help.

  • 写回答

2条回答 默认 最新

  • dqpdb82600 2015-05-21 08:04
    关注

    From the FAQ:

    You can ask the compiler to check that the type T implements the interface I by attempting an assignment:

    type T struct{} 
    var _ I = T{}   // Verify that T implements I.
    

    In this case the blank identifier _ stands for the variable name which is not needed here (and thus prevents a "declared but not used" error).

    And more general from the spec:

    The blank identifier provides a way to ignore right-hand side values in an assignment:

    _ = x       // evaluate x but ignore it 
    x, _ = f()  // evaluate f() but ignore second result value
    

    By testing both FileInfoInternal{} and &FileInfoInternal{} you check if the interface is implemented with a value receiver. A value receiver will accept both a value and a pointer whereas the pointer receiver will only work with a pointer and the first assignment by value will fail.

    The second test with &FileInfoInternal{} is not actually needed (as confirmed by the author in the comments) since the first test will pass with a value receiver and fail with a pointer received. Thus the second test is redundant.

    This is an excellent article that explains the difference between value and pointer receivers and how they are used very well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题