Recently I have been working with Golang interface.
There are lots of confusions on how to use interface in Golang, particularly how to implement the methods in interface. Should I implement pointer receiver, or value receiver? How to mutate a struct that implements an interface? Can I implement both?
Here is a sample code to clear the confusion (http://play.golang.org/p/6u6g2HM33X):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package main import "fmt" type User interface { SetIndex(int) } type UserMutable struct { Index int } // UserMutable DOES NOT implement User, *UserMutable implements User func (u *UserMutable) SetIndex(index int) { u.Index = index } type UserImmutable struct { Index int } // UserImmutable implements User func (u UserImmutable) SetIndex(index int) { u.Index = index } func main() { //userMutable is type *UserMutable userMutable := &UserMutable{} var user User user = userMutable user.SetIndex(9) //userImmutable is type UserImmutable userImmutable := UserImmutable{} // or userImmutable := &UserImmutable{} var user2 User user2 = userImmutable user2.SetIndex(9) fmt.Println("userMutable", userMutable.Index) // "userMutable 9" fmt.Println("userImmutable", userImmutable.Index) // "userImmutable 0" } |
As you can see, a method in an interface can be implemented by either pointer receiver and value receiver.
In the case of pointer receiver, the pointer to the struct (*UserMutable in the example above) implements the interface.
In the case of value receiver, the the struct itself (UserImmutable in the example above) implements the interface.
Hope this clears confusions for people new to Golang.