【问题标题】:How to pass func with any return type as parameter into another function?如何将具有任何返回类型的 func 作为参数传递给另一个函数?
【发布时间】:2021-12-27 10:01:38
【问题描述】:
func F(f func()interface{})interface{} {
    return f()
}

func one() int {
    return 1
}
type A struct {}
func two() A {
  return A{}
}
func main() {

    a := F(one)
    b := F(two)
}

上面的代码会出错

cannot use one (type func() int) as type func() interface {} in argument to F
cannot use two (type func() A) as type func() interface {} in argument to F

我的问题是如何将具有任何可能输出的函数作为参数传递?

【问题讨论】:

  • 您需要键入其他函数才能返回一个空接口。这东西总是让我进入 Go,我仍然不明白为什么它是这样设计的。我理解你的思路,int 应该被空接口覆盖,因此作为返回类型是有效的,但事实并非如此。

标签: go generics func


【解决方案1】:

int 类型的值可以分配给interface{} 变量; func() int 类型的值不能分配给 func() interface{} 类型的值。任何版本的 Go 都是如此。

想一想,您尝试做的事情可以通过 Go 1.18 实现,您可以在其中轻松地使用 T any 对函数进行类型参数化(顺便说一句,anyinterface{} 的别名):

func callf[T any](f func() T) T {
    return f()
}

func one() int {
    return 1
}

type A struct {}
func two() A {
  return A{}
}

func main() {
    a := callf(one)
    b := callf(two)

    fmt.Println(a) // 1
    fmt.Println(b) // {}
}

https://gotipplay.golang.org/p/zCB5VUhQpXE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2011-09-21
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2011-03-31
    相关资源
    最近更新 更多