How come I can say that the result of CreateLion(), a pointer to a struct that implements the Cat interface, is an instance of the Cat interface, and yet I cannot say that CreateLion() is of type "function that returns the Cat interface."
What is the standard Golang approach to achieving this type of behavior?
package main
import "fmt"
func main() {
var lion Cat := CreateLion()
lion.Meow()
// this line breaks. Why?
var cf CatFactory = CreateLion
}
type Cat interface {
Meow()
}
type Lion struct {}
func (l Lion) Meow() {
fmt.Println("Roar")
}
// define a functor that returns a Cat interface
type CatFactory func() Cat
// define a function that returns a pointer to a Lion struct
func CreateLion() *Lion {
return &Lion{}
}
Pedantically, but crucially, it does not return an interface. It returns an object reference.
If an interface is defined to be the return type of a method then instances of classes derived from that interface can be returned. The benefit of doing that is no different from returning objects of classes derived from a class.
Yes, you can return an interface.
Try this:
package main
import "fmt"
type Cat interface {
Meow()
}
type Lion struct{}
func (l Lion) Meow() {
fmt.Println("Roar")
}
type CatFactory func() Cat
func CreateLion() Cat {
return Lion{}
}
func main() {
lion := CreateLion()
lion.Meow()
var cf CatFactory = CreateLion
fLion := cf()
fLion.Meow()
}
In most cases, you can assign any type to base type interface{}
. But situation changes if type of function parameter is a map[T]interface{}
, []interface{}
or func() interface{}
.
In this case the type must be the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With