Ado Ren
Ado Ren

Reputation: 4394

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 ?

Upvotes: 4

Views: 219

Answers (1)

jub0bs
jub0bs

Reputation: 66244

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.

Upvotes: 4

Related Questions