drqwbh2150 2015-11-26 10:23
浏览 48
已采纳

带有指针接收器的Golang方法

I have this example code

package main

import (
    "fmt"
)

type IFace interface {
    SetSomeField(newValue string)
    GetSomeField() string
}

type Implementation struct {
    someField string
}

func (i Implementation) GetSomeField() string {
    return i.someField
}

func (i Implementation) SetSomeField(newValue string) {
    i.someField = newValue
}

func Create() IFace {
    obj := Implementation{someField: "Hello"}
    return obj // <= Offending line
}

func main() {
    a := Create()
    a.SetSomeField("World")
    fmt.Println(a.GetSomeField())
}

SetSomeField does not work as expected because its receiver is not of pointer type.

If I change the method to a pointer receiver, what I would expect to work, it looks like this:

func (i *Implementation) SetSomeField(newValue string) { ...

Compiling this leads to the following error:

prog.go:26: cannot use obj (type Implementation) as type IFace in return argument:
Implementation does not implement IFace (GetSomeField method has pointer receiver)

How can I have the struct implement the interface and the method SetSomeField change the value of the actual instance without creating a copy?

Here's a hackable snippet: https://play.golang.org/p/ghW0mk0IuU

I've already seen this question In go (golang), how can you cast an interface pointer into a struct pointer?, but I cannot see how it is related to this example.

  • 写回答

2条回答 默认 最新

  • du7999 2015-11-26 11:16
    关注

    Your pointer to the struct should implement the Interface. In that way you can modify its fields.

    Look at how I modified your code, to make it working as you expect:

    package main
    
    import (
        "fmt"
    )
    
    type IFace interface {
        SetSomeField(newValue string)
        GetSomeField() string
    }
    
    type Implementation struct {
        someField string
    }    
    
    func (i *Implementation) GetSomeField() string {
        return i.someField
    }
    
    func (i *Implementation) SetSomeField(newValue string) {
        i.someField = newValue
    }
    
    func Create() *Implementation {
        return &Implementation{someField: "Hello"}
    }
    
    func main() {
        var a IFace
        a = Create()
        a.SetSomeField("World")
        fmt.Println(a.GetSomeField())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败