Last active
September 25, 2020 19:52
-
-
Save danfarino/b30c62129c7dfdbd00f2417a4445cb25 to your computer and use it in GitHub Desktop.
Golang interface vs. pointer semantics in interfaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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