为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕少森 2021-07-02 14:59:33
在 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;它似乎不一致。我相信这是有充分理由的;任何人都可以启发我吗?我问的原因主要是因为我想以这种方式缩短一些相当长的函数类型,但我想确保这样做是预期和可接受的:)
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 174 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信