为了账号安全,请及时绑定邮箱和手机立即绑定

指针的类型别名什么时候等同于 Go 中的其他类型?

指针的类型别名什么时候等同于 Go 中的其他类型?

Go
哔哔one 2023-08-14 15:03:31
我一直试图找出为什么一个特定的行可以编译,而另一行则不能。这是一个精炼版本:type A *stringtype B *stringfunc TakeStringPointer(a *string) {    fmt.Println("something: %s\n", *a)}func TakeA(a A) {    fmt.Println("something else: %s\n", *a)}func Sample() {    aa := "asdf"    var pA A    var pB B    var pString *string    pA = &aa    pB = &aa    pString = &aa    TakeStringPointer(pString)    TakeStringPointer(pA)    TakeStringPointer(pB)    TakeA(pA)    TakeA(pB) // Does not compile    TakeA(pString) // Does compile }据我了解,TakeA(pB)要么TakeA(pString)两者都起作用,要么两者都不起作用......A value x is assignable to a variable of type T if:x’s type is identical to T.x’s type V and T have identical underlying types…是在 go 规范中。对我来说,我希望两者都能编译,因为两者A都有B相同的底层类型。(或者,两者都不会,因为 *string 与 A 不同,因为我们有类型声明)。这里发生了什么?
查看完整描述

1 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

x 的类型 V 和 T 具有相同的基础类型……

您引用了规范并省略了重要部分。规范的这一部分全文如下:

x 的类型 V 和 T 具有相同的基础类型,并且 V 或 T 中至少有一个不是已定义的类型。

您拥有的不是类型别名,而是已定义的类型。(类型别名的形式为。)因此,采用已定义类型的type A = B函数不能采用已定义类型;它可以采用,也可以采用 的基础类型。 BABB


查看完整回答
反对 回复 2023-08-14
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信