Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 147 ยท Variables and Types

Defined Types and Type Aliases

Learn Go defined types and aliases - type X int versus type X = int, underlying types, methods, generic type aliases (Go 1.24) and enum-like types.

Go's basic types are general-purpose: an int can be a count of apples, a user ID or a number of seconds. The compiler can't tell them apart, so nothing stops you from adding seconds to apples. Go lets you create your own named types that give those numbers a meaning, make accidental mixing a compile error, and let you attach behavior in the form of methods.

There are two related declarations, and they do very different things. type Celsius float64 creates a defined type: a brand-new type. type Temp = float64 creates an alias: just a second name for an existing type. This lesson explains both, the idea of an underlying type, how to give your types methods, how generic type aliases work (new in Go 1.24), and how defined types and iota build enum-like types. It builds on type conversion; methods are explored fully in the methods lesson later.

Defined types

A defined type declaration has the form type Name UnderlyingType:

Go Defined types keep meanings apart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Celsius has the same underlying type as float64, so it supports the same operators and the same memory layout. But it is a different type, and the compiler enforces that. Passing a Fahrenheit to describe is an error, and so is comparing a UserID with an OrderID. That is exactly what you want: a function that deletes an order must not accept a user ID by mistake.

The mismatch looks like this:

Go Mixing defined types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler rejects it before anything runs:

TEXT
./main.go:14:9: cannot use u (variable of int type UserID) as OrderID value in argument to cancel

Untyped constants still work with defined types, because they adapt: cancel(12) compiles. This is why 5 * time.Second works while n * time.Second with an int variable doesn't (see type conversion).

Underlying types

Every type has an underlying type. For predeclared types like int it's the type itself; for a defined type it's the underlying type of the type it was declared from. The underlying type decides what operations and conversions are available:

Go Underlying types and conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You can base a defined type on a struct, slice, map, function, channel or even an interface, not only on numbers. The operations of the underlying type (indexing, append, len, range, calling) all still work.

One thing does not carry over: the methods of the original type. A new defined type starts with no methods, other than what you declare for it.

Methods on defined types

A method is a function with a receiver: an extra parameter placed before the function name. You can attach methods to any type you define in the same package, which is a good reason to define types:

Go Giving a defined type methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

fmt looks for a String() string method (the fmt.Stringer interface), so Println(temp) prints 36.6ยฐC instead of a bare number. You can't add methods to int or string directly, because they belong to another package, but you can define type Meters int and add them to that. The next chapters cover methods, value versus pointer receivers and interfaces in full.

Type aliases

An alias declaration uses an equals sign: type NewName = ExistingType. The new name is identical to the old one in every way. There's no new type, no conversion needed, and the methods are shared:

Go An alias is the same type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

%T prints main.Celsius and float64: the alias name never appears at run time. You use aliases for three main reasons:

  1. Gradual refactoring. If you move a type from package old to package new, leave type Thing = new.Thing behind so existing code keeps compiling.
  2. Shorter or clearer names for a long type, like type Row = map[string]any.
  3. Built-in aliases. byte is an alias for uint8, rune for int32, and any for interface{}.

Defined type versus alias in one line: type A B creates a new, distinct type that needs conversions; type A = B creates another name for the very same type. If you want the compiler to keep two meanings apart, you want the defined type.

Generic type aliases (Go 1.24)

Since Go 1.24, an alias can have its own type parameters. This lets you give a short, readable name to a generic type or to a particular instantiation of one. Generics are covered in their own chapter, so treat this as a preview:

Go A generic type alias

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Entry[V] fixes the key to string and leaves only the value type open. Aliases don't create new types, so a Setting and a Pair[string, int] compare equal and are interchangeable. Generic aliases are a niche tool; most code uses plain defined types.

Enum-like types

Go has no enum keyword, but a defined type plus constants gives you the same thing, with iota supplying the numbers (see constants). A String method makes the values print nicely:

Go An enum built from a defined type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice what the compiler does not give you: Color(9) is allowed, because any integer converts to a Color. Go enums are not closed sets, so validate values that come from outside (input, files, the network) with a method like Valid. A string-based type works the same way and is often nicer for JSON and logs:

Go
type Role string

const (
	Admin  Role = "admin"
	Editor Role = "editor"
	Viewer Role = "viewer"
)

Defined types for validation and units

Because the type is checked at compile time, small defined types are a cheap way to make wrong code unrepresentable. A common pattern is to give a unit its own type, such as the standard library's time.Duration (an int64 counting nanoseconds with many helpful methods):

Go time.Duration is a defined type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

time.Duration prints as 1h30m0s because it has a String method, yet underneath it is an int64 (%d shows 5400000000000 nanoseconds). That's the whole idea of this lesson in one standard-library type.

When to define a type

Create a defined type when:

  • the value has a meaning that deserves protection from mix-ups (IDs, units, states);
  • you want to attach methods or implement an interface;
  • you need a set of named constants (an enum);
  • a long type such as map[string][]string has a clear role and deserves a name.

Don't create one just to rename something: it adds conversions without adding clarity. Use an alias only for migration or for a real shorthand.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given type Celsius float64 and var c Celsius = 20, which line fails to compile?

    Celsius is a distinct defined type, so assigning it to a float64 variable needs an explicit conversion. Adding an untyped constant like 1.5 is fine.
  2. 2. What is the difference between type A B and type A = B?

    A defined type (no equals sign) is a new type with B as its underlying type. An alias (with =) is the same type as B under another name.
  3. 3. What does fmt.Printf("%T", x) print for type Degrees = float64; var x Degrees?

    An alias is the same type, so the run-time type name is float64. Only defined types print with their own name.
  4. 4. Which statement about type Color int with const Red Color = iota + 1 is true?

    Any integer converts to a defined integer type. Go does not restrict the values, so write a Valid method and a String method yourself.
  5. 5. Which of these can you do for type Meters int but not for plain int?

    Methods can only be declared on types defined in your own package. int is declared in the language itself, but Meters is yours.

Summary

  • type Name Underlying creates a defined type: a new type that shares the underlying type's representation and operators but not its methods, and needs explicit conversions to other types.
  • Defined types keep meanings apart (UserID versus OrderID), carry methods (such as String), and form the basis of enums with iota.
  • type Name = Existing creates an alias: the identical type under another name. It's meant for refactoring, shorthand and the built-in aliases byte, rune and any.
  • Generic type aliases, such as type Entry[V any] = Pair[string, V], arrived in Go 1.24.
  • Go enums are not closed sets: any number converts to the enum type, so validate untrusted values.
  • Define a type when it adds meaning, behavior or safety; skip it when it only renames something.

Next: Operators