相关疑难解决方法(0)

为什么我可以键入别名函数并使用它们而不进行转换?

在Go中,如果您定义一个新类型,例如:

type MyInt int
Run Code Online (Sandbox Code Playgroud)

然后,您无法将a传递MyInt给期望int的函数,反之亦然:

func test(i MyInt) {
    //do something with i
}

func main() {
    anInt := 0
    test(anInt) //doesn't work, int is not of type MyInt
}
Run Code Online (Sandbox Code Playgroud)

精细.但是为什么同样不适用于功能呢?例如:

type MyFunc func(i int)
func (m MyFunc) Run(i int) {
    m(i)
}

func run(f MyFunc, i int) {
    f.Run(i)
}

func main() {
    var newfunc func(int) //explicit declaration
    newfunc = func(i int) {
        fmt.Println(i)
    }
    run(newfunc, 10) //works just fine, even though types seem to differ
} …
Run Code Online (Sandbox Code Playgroud)

types casting go

86
推荐指数
2
解决办法
4万
查看次数

标签 统计

casting ×1

go ×1

types ×1