下面的代码实际上是不言自明的 .
为什么我可以说CreateLion()的结果,一个实现Cat接口的结构的指针,是Cat接口的一个实例,但我不能说CreateLion()的类型为“返回Cat的函数”接口 . ”
实现这种行为的标准Golang方法是什么?
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{}
}