为什么我可以键入别名函数并在不强制转换的情况下使用它们?

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


type MyInt int

然后您不能将 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

}

美好的。但是为什么这同样不适用于函数呢?例如:


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

}

现在,我不是在抱怨,因为它使我不必像在第一个示例中那样显式地强制转换newfunc为 type MyFunc;它似乎不一致。我相信这是有充分理由的;任何人都可以启发我吗?


我问的原因主要是因为我想以这种方式缩短一些相当长的函数类型,但我想确保这样做是预期和可接受的:)


慕少森
浏览 181回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go