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

标签 go types

我一直试图弄清楚为什么某一行会编译,而另一行则无法编译。这是一个简化的版本:

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…

符合规范。对我来说,我希望两者都能编译,因为AB具有相同的基础类型。 (或者,因为* 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/

相关文章:

go - slice 的长度在已经使用 WaitGroup 时有所不同

postgresql - 如何在 Go 中表示 PostgreSQL 区间

go - 为什么 created_at,update_at 与我本地时间 gorm golang 不一样?

reflection - 为什么reflect包里没有 "byte"kind?

c++ - 通过引用传递基本数据类型的速度优势 C++

json - 去 Json 的 ASCII

go - 如何决定并发操作的数量?

sql - 将数据类型更改为 float 并四舍五入为 2 位小数

java - 为什么Java中必须指定方法的返回类型?

javascript - 谷歌关闭 : trouble type checking parameters that should be functions