Go 语言中,类型对应的结构体成员一样时,它们的底层类型就是一样的吗?

比如存在下面两个类型 AB

type A struct {
    x, y int
}

type B struct {
    x, y int
}

此时,类型 A 和类型 B 对应的结构体成员是一样的,那么,A 和 B 拥有的是不是 同一个 底层类型呢?

就像这样:

A      B
 \    /
  \  /
   \/
struct {
  x, y int
}
阅读 2.1k
2 个回答

如果 A B 在同一个包里,是的。

如果他们不在同一个包里,那么由于 struct 里有没有被导出的 field ,他们的 underlying type 是不同的。

Type Identity

Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags.Non-exported field names from different packages are always different.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题