问题描述
下面的代码是不言自明的.
The code below is really self-explanatory.
我怎么能说CreateLion()的结果(指向实现Cat接口的结构的指针)是Cat接口的实例,但是我不能说CreateLion()的类型是返回Cat接口."
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."
达到这种行为的标准Golang方法是什么?
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{}
}
推荐答案
尝试一下:
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()
}
在大多数情况下,您可以将任何类型分配给基本类型 interface {}
.但是,如果函数参数的类型是 map [T] interface {}
, [] interface {}
或 func()interface {}
.在这种情况下,类型必须相同.
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.
这篇关于返回接口的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!