声明函数类型的方式有什么区别?

What is the difference between ways to declare function type?

我可以用两种方式声明函数类型:

type opener = func() error

type opener func() error 

这些声明有什么区别?你为什么要用一个而不是另一个?

根据语言规范,两者都是 type declarations

type opener func() error 是一个 type definition。它引入了一个名为 opener 的新类型,其基础类型为 func() error.

  • openerfunc() error 是不同的类型。它们不可互换。
  • 然而,作为 , because they have the same underlying type (func() error), an expression of type opener can be assigned 类型的变量 func() error,反之亦然。
  • 您可以在 opener 上声明方法。

相比之下,type opener = func() error 是一个 alias declarationopener 被声明为 func() error 类型的别名。

  • 这两种类型是“同义词”,完全可以互换。
  • 您不能在此处声明 opener 上的方法,因为 func() error 不是已定义的类型。在更一般的情况下,仅当别名类型是在与别名相同的包中定义的类型时,才可以在类型别名上声明方法。

primary motivation for the addition of type aliases to the language (in Go 1.9) 是渐进的代码修复,即将类型从一个包移动到另一个包。类型别名还有其他一些小众用例,但您很可能想使用 类型定义 而不是 别名声明 .