普通网友 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.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么