Go语言中的接口(interface)可以被认为是一个指针的意义在于什么?

huangapple go评论86阅读模式
英文:

In what sense can Go's interface be considered a pointer?

问题

在这篇博文中,作者提到:

结构体可以实现接口,所以通常你会将它们视为相同的东西。但是当你处理结构体时,你可能会通过引用传递,此时类型是 *myStruct,或者你可能会通过值传递,此时类型只是 myStruct。然而,如果你处理的是“仅仅”一个接口,你永远不会有一个指向它的指针 -- 接口在某种意义上是一个指针。当你看到代码中传递的东西没有 * 时,可能会感到困惑,要记住如果它是一个接口而不是结构体,它实际上可能是“一个指针”。

在什么意义上可以认为 Go 的接口是一个指针?请提供一些例子。

英文:

In this blog post the author states that:

> Structs can implement interfaces, of course, so in general you tend to
> treat these as the same thing. But when you're dealing with a struct,
> you might be passing by reference, in which the type is *myStruct, or
> you might be passing by value, in which the type is just myStruct. If,
> on the other hand, the thing you're dealing with is "just" an
> interface, you never have a pointer to it -- an interface is a pointer
> in some sense. It can get confusing when you're looking at code that
> is passing things around without the * to remember that it might
> actually "be a pointer" if it's an interface rather than a struct.

In what sense can Go's interface be considered a pointer? Please provide some examples.

答案1

得分: 3

这句话很奇怪。我认为他想表达的意思是:指针接收器上的方法清楚地表明该方法可能会修改接收器,因为该方法是在原始结构上调用的,而不是在副本上调用的。一旦你将一个结构体包装在接口值中,这种明确的指示“你在这里使用指针,这可能会修改原始值!”就会丢失:你可以传递接口值的副本,但所有这些副本都包装着同一个结构体。

英文:

This quote is strange. I think he wants to say something in the line of this: Methods on pointer receivers are a clear indication that the method may modify the receiver as the method is invoked on the original struct and not on a copy. This clear indication of "You work on pointers here, this might modify the original!" is lost once you wrap a struct in an interface value: You may pass around copies of the interface value but all these copies wrap the same struct.

huangapple
  • 本文由 发表于 2015年1月8日 03:50:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/27827500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定