我有这个示例代码
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 无法正常工作,因为其接收器不是指针类型。
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实际实例的值?
struct
这是一个可入侵的代码段:https : //play.golang.org/p/ghW0mk0IuU
您指向结构的指针应实现该接口。这样,您可以修改其字段。
查看我如何修改您的代码,以使其按预期工作:
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()) }