小编zia*_*ian的帖子

Golang函数返回一个接口

下面的代码实际上是不言自明的.

为什么我可以说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{}
}
Run Code Online (Sandbox Code Playgroud)

go

10
推荐指数
3
解决办法
2万
查看次数

标签 统计

go ×1