I am trying to understand Golang (1.12) interfaces. I found out that interface pointers must be explicitly dereferenced, unlike structs:
import "fmt"
// A simple interface with one function
type myinter interface {
hello()
}
// Implement myinter
type mystruct struct {}
func (mystruct) hello() {
fmt.Println("I am T!")
}
// Some function that calls the hello function as defined by myinter
func callHello(i *myinter) {
i.hello() // <- cannot resolve reference 'hello'
}
func main() {
newMystruct := &mystruct{}
callHello(newMystruct)
}
Here, my callHello function cannot resolve the reference to my hello function as defined in the interface. Of course, dereferencing the interface works:
func callHello(i *myinter) {
(*i).hello() // <- works!
}
But in structs, we can call the function directly, none of this cumbersome dereference notation is necessary:
func callHello(s *mystruct) {
s.hello() // <- also works!
}
Why is this the case? Is there a reason why we must explicitly dereference interface pointers? Is Go trying to discourage me from passing interface pointers into functions?
*myintertomyinter. This fixes the error atcallHello(newMystruct)and ati.hello().