dongyuandou2521 2018-07-14 01:57
浏览 15
已采纳

Golang中值类型/指针类型的差异

type T struct {
    Name string
}
func (t T) M1 () {
    t.Name = "name1"
}
func (t *T) M2 () {
    t.Name = "name2"
}
type intf interface {
    M1()
    M2()
}
func main() {
    var t1 T = T{"t1"}
    t1.M1()
    t1.M2()
    var t2 intf = t1
    t2.M1()
    t2.M2()
}

Why when I usevar tf intf = &t1, It's correct But when I usevar tf intf = &t1, It's not correct Is there any difference in the two representations?

  • 写回答

1条回答 默认 最新

  • doupike2351 2018-07-14 02:57
    关注

    when I usevar tf intf = &t1, It's correct But when I usevar tf intf = &t1, it's not

    Since in your example you are using tf intf = t1 (and it does not compile), I think you probably meant:

    when I usevar tf intf = &t1, It's correct But when I usevar tf intf = t1, it's not

    So the question here is why &T{"t1"} (pointer) fulfils the interface intf while T{"t1"} (value) does not.

    In your example, the interface has two methods M1 and M2.

    Type T implements both methods BUT:

    • M1 has T value as the receiver
    • M2 has T pointer as the receiver

    So why does the compiler consider a T pointer to have both methods implemented but considers that a T value does not?

    Answer can be found here in the spec:

    https://golang.org/ref/spec#Method_sets

    The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).

    The spec says that a T pointer has all methods defined with receivers T and *T (so both M1 and M2 in this case).

    But a value of T only has the methods defined with receiver T (so only M1 in this case).

    Since the interface has both methods, only the pointer can fulfil it.

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

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程