Type declarations

July 18, 2023

We’ve already talked about the different types availabe in Go, but now we’ll see how to declare them… just in case it wasn’t already obvious.

Type declarations

A type declaration binds an identifier, the type name, to a type. Type declarations come in two forms: alias declarations and type definitions.

TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
TypeSpec = AliasDecl | TypeDef .

We’ll talk about these two different forms in the coming days. But for now, let me point out that a type alias is a very specific concept in Go, distinct from a standard type declaration. This is something that confuses many newcomers, who often think of any type delcaration as an “alias”.

To spell it out:

type MyInt int

In this example, MyInt is not an alias for int. It is a distinct type. Now, it does have the same underlying type… but it is not an alias. That is to say that int and MyInt are distinct types. They may have distinct method sets. They cannot be converted to one another without, well, conversion.

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

Share this