Edit: For everyone suggesting using a pointer receiver in the function: By changing the method to have a pointer receiver, the structure no longer implements the interface. I have a image at the bottom of my question showing that.
I am trying to make a setter that will mutate the pointer of a variable in a struct with a method implemented from an interface.
package main
import "fmt"
func main() {
i := 1
b := BlahImpl {id:&i}
fmt.Println(b.ID())
j := 2
b.SetID(&j)
fmt.Println(b.ID())
}
type BlahInterface interface {
SetID(*int)
ID() int
}
type BlahImpl struct {
id *int
}
func (b BlahImpl) SetID(i *int) {
b.id = i
}
func (b BlahImpl) ID() int {
return *b.id
}
The current output is:
1
1
But I would like:
1
2
When I use pointer receiver I get this error because the struct is no longer implementing the interface.
Well, to be honest I do not quite get why it works this way, but this works as you want it to:
package main
import "fmt"
func main() {
i := 1
b := BlahImpl{id: &i}
fmt.Println(b.ID())
j := 2
b.SetID(&j)
fmt.Println(b.ID())
}
type BlahInterface interface {
SetID(*int)
ID() int
}
type BlahImpl struct {
id *int
}
func (b *BlahImpl) SetID(i *int) {
b.id = i
}
func (b *BlahImpl) ID() int {
return *b.id
}
The difference is how the structure's methods are defined. I've added *
before the name so reference on the structure is passed into the method. It looks like without *
the method gets copy of the struct so the modification does not work.