How to create golang with pointer receiver in Go ?


Lets go!!

Published · Feb 6

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?

Write your answer...

Never miss a post from Gopher , when you sign up for Ednsquare.