我一直试图弄清楚为什么某一行会编译,而另一行则无法编译。这是一个简化的版本:
type A *string
type B *string
func 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…
符合规范。对我来说,我希望两者都能编译,因为
A
和B
具有相同的基础类型。 (或者,因为* string与A也不一样,因为我们有类型声明)。这里发生了什么?
最佳答案
x的V型和T型具有相同的基础类型...
您引用了规范并省略了重要部分。整个that part of the spec读取:
x的类型V和T具有相同的基础类型,并且V或T中的至少一个不是定义的类型。
您拥有的不是类型别名,而是定义的类型。 (Type aliases的格式为type A = B
。)因此,采用已定义类型B
的函数不能采用已定义类型A
;它可以采用B
,也可以采用B
的基础类型。
关于go - 什么时候指针的类型别名等同于go中的其他类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59328730/