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 ?
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.func() error
), an expression of type opener
can be assigned to a variable of type func() error
, and vice versa.opener
.In contrast, type opener = func() error
is an alias declaration: opener
is declared as an alias for the func() error
type.
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.