I think the best way to explain this is by example, so here it is:
package main
import (
"fmt"
)
// Greeter greets with a Greeting.
type Greeter interface {
Greet() Greeting
}
// A Greeting has a string representation.
type Greeting interface {
String() string
}
type Hello struct {}
// Hello greets by returning itself...
func (h *Hello) Greet() *Hello {
return h
}
// ...because Hello also has a string representation.
func (h *Hello) String() string {
return "Hello"
}
// But Go says Hello doesn't implement Greeter.
func main() {
var g interface{} = &Hello{}
g, ok := g.(Greeter)
fmt.Println(ok)
}
This prints false
. You can run and play with it: https://play.golang.org/p/A_2k_ku_Q2
In my real case the struct Hello
and the interfaces for Greeter
and Greeting
are in different packages that do not import each other and I wanted to keep it that way. I'm perhaps missing some understanding of interfaces in Go but after reading so much about it I still can't put my finger on it. Would you guys have any pointers for me? Maybe another approach for the problem? Thanks!