我一直在试图弄清楚为什么一个特定的行会编译,而另一行不会。这是一个提炼的版本:
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…
在 go 规范中。对我来说,我希望两者都能编译,因为两者都A具有B相同的基础类型。(或者,两者都不会,因为 *string 与 A 不同,因为我们有一个类型声明)。
这里发生了什么?
白衣染霜花
相关分类