Fundamentals

Defined Types and Type Aliases

Give values domain meaning with defined types, build enum-like constants with iota, and learn how an alias differs.

What you will learn

A number can mean many things: a user ID, a price, a temperature. If they all share the type int, the compiler cannot warn you when you mix them up. This lesson shows how to create new types on top of existing ones so the compiler can tell them apart, how to attach methods to them, how to build enum-like sets of constants with iota, and how a type alias differs from a defined type.

The problem: same representation, different meaning

Consider this function:

func transfer(fromAccount int64, toAccount int64, amount int64) { ... }

Every parameter is an int64, so this call compiles even though the arguments are in the wrong order:

transfer(amount, fromAccount, toAccount) // compiles, wrong, and expensive

Go lets you give each concept its own type, so a mix-up becomes a compile error instead of a production bug.

Defining a type

type UserID int64
type ProductID int64

UserID is a new type whose underlying type is int64. It has the same memory layout and supports the same operators, but the compiler treats it as a distinct type:

func loadUser(id UserID) {
    fmt.Println("loading user", id)
}

func main() {
    var userID UserID = 42
    var productID ProductID = 42

    loadUser(userID)    // fine
    loadUser(productID) // compile error
}
cannot use productID (variable of type ProductID) as UserID value in argument to loadUser

The exact wording of the message varies a little between Go versions, but the point is the same: the two types are not interchangeable even though both are numbers underneath.

Conversions are explicit

Moving between a defined type and its underlying type requires a conversion:

var raw int64 = 42
var id UserID = raw // compile error: different types

id = UserID(raw)    // fine, explicit
back := int64(id)   // fine, explicit

A conversion does not change the number, only the type the compiler sees. Writing it deliberately forces you to pause at the places where meaning crosses a boundary, such as reading an ID from a database or a URL.

Constants adapt

An untyped constant, like a literal 42, can be used wherever its value fits:

var id UserID = 42 // fine: the constant 42 becomes a UserID

Once a value sits in a typed variable, though, the strict rules apply.

Adding methods

You can attach methods to a defined type declared in your own package:

type Celsius float64

func (c Celsius) Fahrenheit() float64 {
    return float64(c)*9/5 + 32
}

func main() {
    boiling := Celsius(100)
    fmt.Println(boiling.Fahrenheit()) // 212
}

This keeps behaviour next to the concept it belongs to. You cannot add methods to built-in types like int directly, which is one more reason to define a type.

Enum-like constants with iota

Go has no enum keyword. The idiom is a defined type plus a block of constants:

type Weekday int

const (
    Sunday Weekday = iota // 0
    Monday                // 1
    Tuesday               // 2
    Wednesday             // 3
)

iota is a counter that starts at 0 in each const block and increases by one for every line. Lines that omit the expression repeat the previous one, so Monday is Weekday = iota with iota now equal to 1.

Add a String method and the values print nicely:

func (d Weekday) String() string {
    switch d {
    case Sunday:
        return "Sunday"
    case Monday:
        return "Monday"
    case Tuesday:
        return "Tuesday"
    case Wednesday:
        return "Wednesday"
    }
    return "Unknown"
}

func main() {
    day := Tuesday
    fmt.Println(day)        // Tuesday
    fmt.Printf("%d\n", day) // 2
}

Because Weekday is its own type, a function that takes a Weekday will not accept an arbitrary int variable, which is exactly the protection you want from an enum.

Types do not validate by themselves

A defined type does not restrict its values. This compiles:

type Percentage int

var p Percentage = 500 // valid to the compiler

When values must follow a rule, enforce it in a constructor or parsing function:

func NewPercentage(value int) (Percentage, error) {
    if value < 0 || value > 100 {
        return 0, fmt.Errorf("percentage %d is outside 0..100", value)
    }
    return Percentage(value), nil
}

To make the constructor impossible to bypass, define the type as a struct with an unexported field, in its own package, so outside code can only create values through your function.

Type aliases

An alias gives an existing type a second name. It uses =:

type Byte = uint8

Byte and uint8 are the very same type, so no conversion is needed between them. Compare the two forms side by side:

type UserID int64        // defined type: new, distinct type
type Identifier = int64  // alias: just another name for int64

An alias creates no new meaning, so it cannot protect you from mix-ups, and it cannot have its own methods. Aliases exist mainly to help with gradual refactoring, for example when moving a type to another package, and to give shorter names to long type expressions. If you want new meaning or behaviour, use a defined type.

Common mistakes

  • Expecting automatic validation. A defined type accepts every value its underlying type does.
  • Converting just to make the error go away. First ask whether the mismatch points to a real bug.
  • Defining a type for every local variable. Types pay off at meaningful boundaries, like IDs, units, and states.
  • Using an alias when you wanted a new type. An alias gives you no extra safety.
  • Comparing against raw numbers all over the code when named constants exist.

Practice

Create distinct AccountID and TransactionID types based on string. Give each a Valid method that rejects an empty value. Write a function that accepts an AccountID, and demonstrate that passing a TransactionID to it does not compile.

Summary

A defined type, written type UserID int64, is a new and distinct type with the same underlying representation, so the compiler stops you from mixing it with other types by accident. Converting to and from the underlying type is always explicit. Defined types can have methods and can model enums with constants and iota. A type does not validate its values by itself, so use a constructor for rules, and remember that an alias gives a second name to the same type without creating anything new.

Official reference: Type declarations in the specification and A Tour of Go: Methods.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026