在Go中使用空接口返回类型接受参数中的函数

Sam*_*ann 8 go

我是Go的新手,我想了解为什么下面的代码片段无法编译.接受函数作为可能具有任何返回类型的函数参数的Go方式是什么?

package main

func main() {
    test(a) // Error: cannot use a (type func() string) as type func() interface {} in argument to test
    test(b) // Error: cannot use b (type func() int) as type func() interface {} in argument to test
}

func a() string {
    return "hello"
}

func b() int {
    return 1
}

func test(x func() interface{}) {

    // some code...
    v := x()
    // some more code....
}
Run Code Online (Sandbox Code Playgroud)

播放:https://play.golang.org/p/CqbuEZGy12

我的解决方案基于Volker的答案:

package main

import (
    "fmt"
)

func main() {

    // Wrap function a and b with an anonymous function
    // that has an empty interface return type. With this
    // anonymous function, the call signature of test
    // can be satisfied without needing to modify the return
    // type of function a and b.

    test(func() interface{} {
        return a()
    })

    test(func() interface{} {
        return b()
    })
}

func a() string {
     return "hello"
}

func b() int {
    return 1
}

func test(x func() interface{}) {
    v := x()
    fmt.Println(v)  
}
Run Code Online (Sandbox Code Playgroud)

播放:https://play.golang.org/p/waOGBZZwN7

Vol*_*ker 12

你绊倒了围棋新人一个非常普遍的误解:空接口interface{}不能意味着"任何类型".真的,它没有.Go是静态类型的.空接口interface {}是实际的(强类型类型),例如eg stringstruct{Foo int}or interface{Explode() bool}.

这意味着如果某些东西具有该类型的interface{}类型而不是"任何类型".

你的功能

func test(x func() interface{})
Run Code Online (Sandbox Code Playgroud)

取一个参数.此参数是(无参数函数),它返回特定类型,即类型interface{}.您可以传递test与此签名匹配的任何函数:"无参数并返回interface{}".您的所有功能都ab匹配此签名.

如上所述:interface {}不是"无论"的神奇缩写,它是一种独特的静态类型.

你必须改变例如:

func a() interface{} {
    return "hello"
}
Run Code Online (Sandbox Code Playgroud)

现在,当你返回一个string不属于类型的东西时,这可能看起来很奇怪interface{}.这是有效的,因为任何类型都可以赋值给类型的变量interface{}(因为每个类型至少没有方法:-).

  • 这就像按任意键和按“任意”键之间的区别。 (2认同)