Skip to content

Instantly share code, notes, and snippets.

@danfarino
Last active September 25, 2020 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danfarino/b30c62129c7dfdbd00f2417a4445cb25 to your computer and use it in GitHub Desktop.
Save danfarino/b30c62129c7dfdbd00f2417a4445cb25 to your computer and use it in GitHub Desktop.
Golang interface vs. pointer semantics in interfaces
package main
import "fmt"
type Thinger interface {
DoStuff()
DoThings()
}
type thing1 struct {}
func (t thing1) DoStuff() {
fmt.Println("thing1.DoStuff")
}
func (t thing1) DoThings(){
fmt.Println("thing1.DoThings")
}
type thing2 struct {}
func (t *thing2) DoStuff() {
fmt.Println("thing2.DoStuff")
}
func (t *thing2) DoThings(){
fmt.Println("thing2.DoThings")
}
type thing3 struct {}
func (t *thing3) DoStuff() {
fmt.Println("thing3.DoStuff")
}
func (t thing3) DoThings(){
fmt.Println("thing3.DoThings")
}
func main() {
var ti Thinger
ti = thing1{}
// ti = &thing1{} // ALSO WORKS
ti.DoStuff()
ti.DoThings()
ti = &thing2{}
// ti = thing2{} // DOES NOT COMPILE: "thing2 does not implement Thinger (DoStuff method has pointer receiver)"
ti.DoStuff()
ti.DoThings()
ti = &thing3{}
// ti = thing3{} // DOES NOT COMPILE: "thing3 does not implement Thinger (DoStuff method has pointer receiver)"
ti.DoStuff()
ti.DoThings()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment