英文:
What is the difference between ways to declare function type?
问题
这两种声明函数类型的方式有什么区别?为什么会选择其中一种而不是另一种?
英文:
I can declare a function type in two ways :
type opener = func() error
type opener func() error
What is the difference between those declarations ? Why would you use one over the other ?
答案1
得分: 4
根据语言规范,两者都是类型声明。
type opener func() error 是一个类型定义。它引入了一个名为 opener 的新类型,其底层类型是 func() error。
opener和func() error是不同的类型,它们不能互换使用。- 然而,正如 Hymns For Disco 指出的,因为它们具有相同的底层类型(
func() error),所以类型为opener的表达式可以被赋值给类型为func() error的变量,反之亦然。 - 你可以在
opener上声明方法。
相比之下,type opener = func() error 是一个别名声明:opener 被声明为 func() error 类型的别名。
- 这两个类型是“同义词”,完全可以互换使用。
- 在这里,你不能在
opener上声明方法,因为func() error不是一个定义的类型。在更一般的情况下,只有当别名类型是与别名在同一个包中定义的类型时,你才能在类型别名上声明方法。
类型别名被添加到语言中的主要动机(在Go 1.9中)是逐步修复代码,即将类型从一个包移动到另一个包。还有一些其他特定用例可以使用类型别名,但你很可能更希望使用类型定义而不是别名声明。
英文:
Per the language spec, both are type declarations.
type opener func() error is a type definition. It introduces a new type named opener whose underlying type is func() error.
openerandfunc() errorare distinct types. They are not interchangeable.- However, as Hymns For Disco points out, because they have the same underlying type (
func() error), an expression of typeopenercan be assigned to a variable of typefunc() error, and vice versa. - You can declare methods on
opener.
In contrast, type opener = func() error is an alias declaration: opener is declared as an alias for the func() error type.
- The two types are "synonyms" and perfectly interchangeable.
- You cannot declare methods on
openerhere becausefunc() erroris not a defined type. In the more general case, you can declare methods on a type alias only if the aliased type is a type defined in the same package as the alias.
The primary motivation for the addition of type aliases to the language (in Go 1.9) was gradual code repair, i.e. moving types from one package to another. There are a few other niche use cases for type aliases, but you most likely want to use a type definition rather than an alias declaration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论