【发布时间】:2016-02-29 09:33:41
【问题描述】:
我有这个示例代码
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 无法按预期工作,因为它的接收者不是指针类型。
如果我将方法更改为指针接收器,我希望它可以工作,它看起来像这样:
func (i *Implementation) SetSomeField(newValue string) { ...
编译它会导致以下错误:
prog.go:26: cannot use obj (type Implementation) as type IFace in return argument:
Implementation does not implement IFace (GetSomeField method has pointer receiver)
如何让struct 实现接口和方法SetSomeField 更改实际实例的值而不创建副本?
这是一个可破解的 sn-p: https://play.golang.org/p/ghW0mk0IuU
我已经看过这个问题In go (golang), how can you cast an interface pointer into a struct pointer?,但我看不出它与这个例子有什么关系。
【问题讨论】:
标签: go