英文:
About interfaces in Go
问题
你好!根据你提供的代码,我可以解释一下为什么在调用函数时(obj.Method())Go语言会自动解引用,但在将接口变量赋值时(var i IA = SA{})却不能自动解引用。
在Go语言中,当你调用一个方法时,编译器会自动解引用指针接收器。这意味着如果一个方法的接收器是一个指针类型,你可以直接调用该方法,而不需要显式地解引用指针。因此,当你调用obj.Method()时,编译器会自动解引用obj,并调用Method()方法。
然而,在将一个结构体赋值给接口变量时,Go语言不会自动解引用。这是因为接口变量可以持有任意类型的值,包括指针类型和非指针类型。为了保持一致性,Go语言要求你显式地解引用指针,以确保将指针类型的值赋给接口变量时,不会发生隐式的解引用。
因此,在赋值给接口变量i时,你需要使用&SA{}来显式地创建一个指向SA类型的指针,并将其赋给接口变量i。这样做可以确保类型匹配,并将指针类型的值赋给接口变量。
希望这个解释对你有帮助!如果你还有其他问题,请随时提问。
英文:
type IA interface {
Method()
}
type SA struct {
}
func (this *SA) Method() {
}
func main() {
var i IA = SA{} //error
var i IA = &SA{} //ok
var obj = SA{}
obj.Method()//ok
}
Could you explain why does GO automatically dereference in the case of calling function (obj.Method()) but in assignment to interface variable (var i IA = SA{}) it can't?
答案1
得分: 2
func (this *SA) Method() 表示只有指向类型 SA 的指针 (*SA) 才具有 Method() 方法,因此 var i IA = &SA{} 符合 IA 接口。
如果将其改为 func (this SA) Method(),那么 var i IA = SA{} 就符合接口,而不是 var i IA = &SA{}。
*SA 和 SA 不是相同的类型。
Go 为处理解引用方法值提供了一些快捷方式(这可能是混淆的原因)。
如果你查看规范中的方法值部分,你会看到:
>使用指针引用具有值接收器的非接口方法将自动解引用该指针
和
>使用可寻址值引用具有指针接收器的非接口方法将自动获取该值的地址
这就是为什么 obj.Method() 在 obj 是 *SA 或 SA 时都可以工作的原因。
希望对你有所帮助。
英文:
func (this *SA) Method() means that only a pointer to type SA (*SA) has the Method() method, therefore var i IA = &SA{} fulfils the IA interface.
If you change it to read func (this SA) Method() then var i IA = SA{} fulfils the interface, and not var i IA = &SA{}.
*SA is not the same type as SA.
Go provides some shortcuts for dealing with dereferencing method values (which is probably where the confusion is coming from)
If you have a look at the Method Values section of the spec you will see that:
>a reference to a non-interface method with a value receiver using a pointer will automatically dereference that pointer
and
>a reference to a non-interface method with a pointer receiver using an addressable value will automatically take the address of that value
This is why obj.Method() works whether obj is an *SA or an SA.
Hope that helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论