Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
golang函数类型继承?_Go - Fatal编程技术网

golang函数类型继承?

golang函数类型继承?,go,Go,以Go语言为例: type I interface { get() string } type S struct {} func (s *S) get() string { return "here!" } var sSupplier = func() *S { return &S{} } func foo(supplier func () I) { i := supplier() println(i) } func ma

以Go语言为例:

type I interface {
    get() string
}

type S struct {}
func (s *S) get() string {
    return "here!"
}
var sSupplier = func() *S {
    return &S{}
}

func foo(supplier func () I) {
    i := supplier()
    println(i)
}

func main() {
    foo(sSupplier) // compile error, type mismatch
}
键入
S
继承接口
I
。但是显然type
func()*S
并没有继承
func()I
,所以我不能用
sSupplier
来调用
foo
,而不是
supplier
函数。有没有一种方法可以在不强制
sSupplier
返回类型
I
的情况下修复它


在java中,您可以使用泛型执行类似于
voidfoo(Supplier){…}
的操作,然后调用
foo(sSupplier)与供应商供应商供应商类型一起使用。我不确定类似的方法在go中是否可行?

如果您想一想泛型为您做了什么,它们实际上是一种要求编译器当场编译匿名包装函数或lambda或从某个具体类型映射所需的任何东西的方法。也就是说,给出了一些(我将使用C++语法而不是java,因为我对C++更熟悉):

请参阅上更完整的示例。我用
fmt.Printf(“%#v\n”,I)
重新播放您的
println(I)
,以稍微有用的形式打印接口对象的值

template<T>
void f(T obj) {
    // do stuff with the object
}
foo(func() I { return sSupplier() })