douyan6958 2019-03-29 02:06
浏览 23

为什么在Go中调用嵌入式字段的方法时,Type Alias和Type的行为会有所不同?

go version go1.11.2 linux/amd64

https://play.golang.org/p/kTvcsWkJeaZ

package main

type T1 struct {
}

func (T1) Hello(T1) {
}

type T2 struct {
    T1
}

func (T2) Hello(T2) {
}

type T3 T2
type T4 = T2

func main() {
    var v_T3 T3
    v_T3.Hello(v_T3)
    var v_T4 T4
    v_T4.Hello(v_T4)
}

prog.go:21:12: cannot use v_T3 (type T3) as type T1 in argument to v_T3.T1.Hello

row 21:I expect call v_T3.Hello but the actual call v_T3.T1.Hello

row 23:it's ok

  • 写回答

1条回答 默认 最新

  • doulu1325 2019-03-29 06:16
    关注
    type T4 = T2
    

    This gives an additional name T4 to the existing type T2. It does not introduce a new type. In other words, T2 and T4 are always interchangeable. That should explain why the v_T4.Hello(v_T4) call works. All of the following calls are all synonymous in terms of types (but ignoring that v_T2 and v_T4 are different values):

    var v_T2 T2
    var v_T4 T4
    
    v_T2.Hello(v_T2)
    v_T2.Hello(v_T4)
    v_T4.Hello(v_T2)
    v_T4.Hello(v_T4)
    

    type T3 T2
    

    This defines a new type T3 that is distinct from all other types. According to the type rules, T3 doesn't inherit T2's methods. But because they have the same underlying type, T3's and T2's fields are the same, including the embedded T1. This in turn promotes T1's methods to T3.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集