Alias declarations

July 19, 2023

Alias declarations

An alias declaration binds an identifier to the given type.

AliasDecl = identifier "=" Type .

Within the scope of the identifier, it serves as an alias for the type.

type (
	nodeList = []*Node  // nodeList and []*Node are identical types
	Polar    = polar    // Polar and polar denote identical types
)

Aliases are a feature you likely won’t use frequently. You may never use it, in fact.

The original purpose for aliases was to allow for a more graceful transition when renaming or moving packages. Although they do have other uses as well.

The most common use I see of aliases, is for use as a simple convenience, when extending or wrapping an existing package. Let’s imagine you’re building a custom logging library for use at your company, and it’s based on the standard library’s log library (NOTE: I don’t actually recommend this!), but you want a simplified API that doesn’t expose the global logger. So you’d rather your apps import example.com/log instead of log. You could accomplish this with a package something like:

package log

import "log"

type Logger = log.Logger // An alias!

// New just wraps log.New. Note that it returns *Logger, not *log.Logger, thanks
// to the alias above.
func New(out io.Writer, prefix string, flag int) *Logger {
  return log.New(out, prefix, flag)
}

Now those who import your custom log package will only have access to the Logger and New, rather than all of the functions that reference the global/default logger. Of course, there’s nothing here preventing someone who wants to from importing log directly.

Of course, this is a bit of a contrived example, but I hope it illustrates the use of aliases.

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this