声明函数类型的方式有哪些区别?

huangapple go评论85阅读模式
英文:

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

  • openerfunc() 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.

  • opener and func() error are 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 type opener can be assigned to a variable of type func() 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 opener here because func() error is 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.

huangapple
  • 本文由 发表于 2021年7月10日 14:14:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/68325216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定