普通网友 2019-02-22 04:02
浏览 49
已采纳

为什么Go允许将接口变量分配给未实现值接收者的值?

Sorry for the confusing question title, but here's something I don't understand. In the following code, an error is reached when we attempt to assign x to p, because x requires p to implement M(), and it doesn't, as M() has a pointer receiver.

type Person struct {
    Name string
    Age int
}

func (p *Person) M() {
}

type I interface {
    M()
}

func main() {
    var x I
    var p := Person{}
    x = p              // Error, M() has pointer receiver
}

That makes relative sense to me. The thing I don't understand is how it's perfectly happy assigning x to &p in the following example. In this example, M() has a value receiver, not a pointer receiver, but it still works just fine.

type Person struct {
    Name string
    Age int
}

func (p Person) M() {
}

type I interface {
    M()
}

func main() {
    var x I
    var p := Person{}
    x = &p             // No error
}

This makes no sense to me. A method either implements a value receiver or a pointer receiver, so if it doesn't allow you to assign an interface variable to a value of a type that only implements a pointer receiver, why would it allow you to assign it to a pointer, when the method is only defined as a value receiver?

Lastly, this is further confused by the fact that you can do the following without issue in Go:

func (p *Person) rename(string newName) {
    p.Name = newName
}

func main() {
    p := Person{Name: "Old name"}
    fmt.Println(p.Name)
    p.rename("New name")
    fmt.Println(p.Name) // Name has changed, despite p not being pointer
}

In the Go tour, it says calls like this are explicitly cast, (eg p.rename("New name") implicitly becomes (&p).rename("New name") and pointers become values if needed).

This seems really inconsistent. Am I wrong here?

  • 写回答

1条回答 默认 最新

  • dsxml2169 2019-02-24 00:41
    关注

    I figured it out. In short, I was messing up two concepts. There was a lot to my confusion, so let's break it down, starting with my last point about the automatic pointer dereferencing.

    The main issue I was having was that it seemed like the compiler was happy to apply the & operator for you. The thing is, there are times when that makes sense and times when it doesn't (see below).

    p := Person{"Old"}
    var iface I = p
    p.rename("New") // Can safely be rewritten to (&p).rename("New")
    iface.rename("New") // Cannot rewrite (&iface != &p)
    

    This is why it makes sense to disallow assigning a value to an interface, if only a pointer to that value satisfies the interface. You can't just yank the address of the original variable once it's been assigned to the interface, but you can when it's a variable of the actual type. Now, that still left me confused about this:

    p := Person{"Name"}
    var iface I = &p    // No error
    

    What I got from this mostly is that...Go just works that way. This post describes method sets. I was getting tripped up by the word "addressable". To explain my confusion, I was under the impression that the compiler was doing the following insertion when a pointer was stored but a value was needed, (which wouldn't make sense):

    p := &Person{"Name"}
    var iface I = p
    p.rename()  /* becomes */ (*p).rename()
    iface.rename() /* becomes */ (*iface).rename()
    

    Performing a method call is a multi step process from the compiler's perspective; simply putting the * before the variable name might seem like it gets you far, but there's still more variables to copy from memory and push on the stack, etc. In reality, dereferencing the variable yourself doesn't "do" anything for the compiler. In both cases, it needs to then go to that location and copy what's there. Physically writing the * is, from Go's perspective, just telling the compiler to do what it's already going to do, because a value receiver method expects a value, so the compiler needs to produce one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行