For Entity
to fulfill your interface it must comply strictly with the interface definition:
Trying to print an entity using
func msg(m Message) {
fmt.Println(m.Get())
}
shows:
func main() {
fmt.Println("Hello, playground")
e := &Entity{}
e2 := e.New()
msg(e2)
}
prog.go:28:5: cannot use e2 (type *Entity) as type Message in argument to msg:
*Entity does not implement Message (wrong type for New method)
have New() *Entity
want New() *Message
Updating Entity.New()
to return a pointer to a Message
interface now shows:
type Message interface {
New() *Message
Get() string
}
type Entity struct {}
func (e *Entity) New() *Message {
return e
prog.go:14:3: cannot use e (type *Entity) as type *Message in return argument:
*Message is pointer to interface, not interface
prog.go:28:5: cannot use e2 (type *Message) as type Message in argument to msg:
*Message is pointer to interface, not interface
More about this can be read:
"<type> is pointer to interface, not interface" confusion
Now updating your methods to return an interface instead of a pointer to an interface yields:
type Message interface {
New() Message
Get() string
}
type Entity struct {}
func (e *Entity) New() Message {
return e
}
func (e Entity) Get() string {
return "hi"
}
func msg(m Message) {
fmt.Println(m.Get())
}
func main() {
fmt.Println("Hello, playground")
e := &Entity{}
e2 := e.New()
msg(e2)
}
Hello, playground
hi