gotype-aliastype-declaration

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 ?


Solution

  • 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.

    In contrast, type opener = func() error is an alias declaration: opener is declared as an alias for the func() error type.


    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.