Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Type design: unions, newtypes & generics

Using the type system to rule out bugs: models in which invalid states cannot be built, newtypes for IDs and units, checks that every case is handled, states encoded as types, constrained generics, variance and higher-kinded types. It goes deeper than the Types & syntax entries, which show how to read generics and tagged variants, and the Paradigms entries, which introduce algebraic data types.

Make illegal states unrepresentable: unions over flags, parse don't validate, smart constructors

Go

Name alternatives and tagged variants (Types & syntax) shows how to write a union; this entry uses unions and validated constructors to design a model in which nonsense combinations cannot be built. Go has no unions and no private constructors, but it has unexported fields: a struct such as Email{addr string} can only be built outside its package through ParseEmail, which validates. Groups of flags and optional fields become a sealed interface with one struct per valid shape (ByEmail, ByPhone, ByBoth). ParseReach turns the loose input into a Reach or an error once, at the boundary.

Complete program

Complete program.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "errors"
    "fmt"
    "net/mail"
    "strings"
)

// Smart constructor: the field is unexported, so other packages can only get an
// Email from ParseEmail. (main is one package, so here it is a convention.)
type Email struct{ addr string }

func ParseEmail(raw string) (Email, error) {
    a, err := mail.ParseAddress(strings.TrimSpace(raw))
    if err != nil {
        return Email{}, fmt.Errorf("bad email %q: %w", raw, err)
    }
    return Email{addr: strings.ToLower(a.Address)}, nil
}

// Before: Email, Phone string, where both empty is invalid but representable.
// After: a sealed interface stands in for a union of the three valid shapes.
type Reach interface{ isReach() }
type ByEmail struct{ Email Email }
type ByPhone struct{ Phone string }
type ByBoth struct {
    Email Email
    Phone string
}

func (ByEmail) isReach() {}
func (ByPhone) isReach() {}
func (ByBoth) isReach()  {}

// Parse once at the boundary; everything after works with a valid Reach.
func ParseReach(email, phone string) (Reach, error) {
    if email == "" && phone == "" {
        return nil, errors.New("need an email or a phone")
    }
    if email == "" {
        return ByPhone{phone}, nil
    }
    e, err := ParseEmail(email)
    if err != nil {
        return nil, err
    }
    if phone == "" {
        return ByEmail{e}, nil
    }
    return ByBoth{e, phone}, nil
}

func SendTo(r Reach) string {
    switch r := r.(type) {
    case ByEmail:
        return "mail " + r.Email.addr
    case ByBoth:
        return "mail " + r.Email.addr
    case ByPhone:
        return "text " + r.Phone
    default: // a nil Reach (a zero value) gets past every constructor
        panic(fmt.Sprintf("unhandled reach %T", r))
    }
}

func main() {
    for _, in := range [][2]string{{" Ana@Example.com ", ""}, {"", "+15550100"}, {"", ""}, {"nope", ""}} {
        r, err := ParseReach(in[0], in[1])
        if err != nil {
            fmt.Println("rejected:", err)
            continue
        }
        fmt.Println(SendTo(r))
    }
}

In practice: put validated types in their own package so the unexported field actually protects them, return (T, error) from constructors, and add a panicking default to type switches over the sealed interfaces. Remember that zero values bypass every constructor: Email{} and a nil Reach can always be created.

mail.ParseAddress follows RFC 5322 and accepts forms like "Ana <ana@example.com>"; it does not check that the domain exists.

Make the zero value safe where you can (an IsZero method, or treating it as invalid) because Go cannot forbid it.

Wrap a primitive in a distinct type: brands, defined types, tuple structs, strong typedefs

Go

Where Name alternatives and tagged variants (Types & syntax) names a set of values, a newtype gives one kind of value its own type, so two values with the same representation (two string IDs, meters and feet) cannot be swapped. Go is nominal for defined types: `type UserID string` creates a new type with string as its underlying type, and a UserID variable cannot be passed where an OrderID or a string variable is expected without an explicit conversion. Defined types can have methods, which is how time.Duration (a defined int64) prints as 3s. An alias, `type Label = string`, is not a new type at all.

Complete program

Complete program.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "fmt"
    "time"
)

// Defined types: each is a new, distinct type with the same underlying type.
type UserID string
type OrderID string
type Cents int64

// An alias (with =) is NOT a new type: Label and string are interchangeable.
type Label = string

func CancelOrder(user UserID, order OrderID) string {
    return fmt.Sprintf("%s cancelled %s", user, order)
}

// Defined types can carry methods; the underlying type's methods are not inherited.
func (c Cents) String() string { return fmt.Sprintf("$%d.%02d", c/100, c%100) }

func main() {
    u := UserID("u_42") // explicit conversion from string
    o := OrderID("o_9001")
    fmt.Println(CancelOrder(u, o))
    // CancelOrder(o, u)
    //   error: cannot use o (variable of string type OrderID) as UserID value in argument to CancelOrder

    raw := "u_7"
    // CancelOrder(raw, o)  // error: a string variable needs an explicit UserID(raw)
    fmt.Println(CancelOrder(UserID(raw), o))

    // Pitfall: untyped constants convert implicitly, so a literal slips through.
    fmt.Println(CancelOrder("o_mistake", o))

    // Conversion between defined types with the same underlying type is allowed
    // and unchecked, so the type only helps if conversions stay at the edges.
    sneaky := UserID(o)
    fmt.Println(sneaky)

    var price Cents = 250
    tax := Cents(20)
    fmt.Println(price+tax, int64(price)) // arithmetic keeps the type; int64() unwraps

    var l Label = "plain"
    var s string = l // no conversion needed for an alias
    fmt.Println(s)

    // The standard library uses the same pattern: time.Duration is a defined int64.
    timeout := 3 * time.Second
    fmt.Println(timeout, int64(timeout))
}

In practice: define types for IDs, money and units, and convert at the edges (parsing, database rows). Know the two gaps: untyped constants such as "o_mistake" convert implicitly, and any two types with the same underlying type convert freely with T(x). The type stops accidents, not deliberate conversions.

A defined type does not inherit the methods of its underlying type (it does keep the fields of an underlying struct, and the methods of embedded fields).

Arithmetic keeps the type (Cents + Cents is Cents), but mixing Cents and int64 variables needs a conversion.

To force validation, use a struct with an unexported field and a constructor function instead; a defined string can be converted from any string.

Make the compiler check every case: assertNever, exhaustive linters, match, std::visit

Go

Algebraic data types (in Paradigms) shows the sealed-interface stand-in for a sum type; this entry covers how to get a missing case reported, since the Go compiler never does. A switch over iota constants and a type switch over a sealed interface both compile with cases missing, and a defined integer type can hold values outside its constants, such as Channel(7). Two linters fill the gap: exhaustive checks switches over enum-like constants, and gochecksumtype checks type switches over interfaces marked //sumtype:decl. The one compiler-checked option is to make the behavior an interface method, so a variant without it fails to compile where it is used as that interface.

Complete program

Complete program.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

// Enum-like constants: the compiler never checks that a switch lists them all.
// Removing "case Push" below makes the exhaustive linter report
// "missing cases in expression switch: Push".
type Channel int

const (
    Email Channel = iota
    SMS
    Push
)

func (c Channel) String() string {
    switch c {
    case Email:
        return "email"
    case SMS:
        return "sms"
    case Push:
        return "push"
    default:
        return fmt.Sprintf("Channel(%d)", int(c)) // Channel(7) is a legal value
    }
}

// A sealed interface: only this package can implement the unexported method.
// The marker comment below tells go-check-sumtype to check type switches over it.
//
//sumtype:decl
type Notice interface{ isNotice() }

type EmailNotice struct{ Address string }
type SMSNotice struct{ Phone string }
type PushNotice struct{ DeviceID string }

func (EmailNotice) isNotice() {}
func (SMSNotice) isNotice()   {}
func (PushNotice) isNotice()  {}

// A type switch compiles even if a case is missing. Removing "case PushNotice" makes
// go-check-sumtype report "exhaustiveness check failed for sum type "Notice" (...):
// missing cases for PushNotice".
func target(n Notice) string {
    switch n := n.(type) {
    case EmailNotice:
        return n.Address
    case SMSNotice:
        return n.Phone
    case PushNotice:
        return n.DeviceID
    default:
        panic(fmt.Sprintf("unhandled notice %T", n))
    }
}

// The compile-time alternative: make the behavior an interface method.
// Adding a method here forces every variant to implement it, or the
// assignments in main fail with "does not implement Coster (missing method CostCents)".
type Coster interface {
    Notice
    CostCents() int
}

func (EmailNotice) CostCents() int { return 0 }
func (SMSNotice) CostCents() int   { return 4 }
func (PushNotice) CostCents() int  { return 0 }

func main() {
    notices := []Coster{EmailNotice{"ana@example.com"}, SMSNotice{"+15550100"}, PushNotice{"dev-7"}}
    total := 0
    for _, n := range notices {
        fmt.Println(target(n))
        total += n.CostCents()
    }
    fmt.Println("total cost", total)
    fmt.Println(Email, SMS, Push, Channel(7))
}

In practice: run both linters in CI (golangci-lint bundles them), and still give every switch a default that panics or returns an error for values the linters cannot see, such as nil or Channel(7). Prefer an interface method when each variant can answer the question itself.

Neither the compiler nor go vet checks exhaustiveness. The exhaustive analyzer (github.com/nishanths/exhaustive v0.17.1) checks switches and map literals over enum-like constants. go-check-sumtype (github.com/alecthomas/go-check-sumtype v0.5.0, gochecksumtype in golangci-lint) checks type switches over interfaces marked with a //sumtype:decl comment, as in the example. The older BurntSushi/go-sumtype uses a different marker, //go-sumtype:decl.

exhaustive reports a missing constant even when the switch has a default. go-check-sumtype treats a default that does not panic as covering every case (-default-signifies-exhaustive, on by default), so keep the default panicking, as here, or turn the flag off.

A nil interface value matches no type case and lands in default.

The String method needs its own default because any int converts to Channel.

Allow a call only in the right state (typestate): state types, consuming self, PhantomData, tag templates

Go

Name alternatives and tagged variants (Types & syntax) puts every state in one union; typestate gives each state its own type, so a call that is wrong for the current state does not compile. A Go generic type cannot have methods for only some type arguments (no Conn[Connected]-only send), so typestate in Go means separate struct types per state: Draft has Submit, InReview has Approve and Reject, and only Published has URL. Unexported fields stop other packages from building a Published value directly, so the transitions are the only way in. Value receivers return a new value and leave the old one unchanged.

Complete program

Complete program.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "errors"
    "fmt"
    "strings"
)

// One struct type per state. Unexported fields stop other packages from
// building a Published directly; they must go through the transitions.
type Draft struct{ title, body string }
type InReview struct {
    title, body string
    reviewer    string
}
type Published struct {
    title, body string
}

func NewDraft(title string) Draft { return Draft{title: title} }

// Value receivers return a new value, so the old state is left unchanged.
func (d Draft) Edit(body string) Draft { d.body = body; return d }

func (d Draft) Submit(reviewer string) (InReview, error) {
    if d.body == "" {
        return InReview{}, errors.New("empty post")
    }
    return InReview{title: d.title, body: d.body, reviewer: reviewer}, nil
}

func (r InReview) Reject() Draft      { return Draft{title: r.title, body: r.body} }
func (r InReview) Approve() Published { return Published{title: r.title, body: r.body} }

// Only Published has URL; calling it on another state does not compile.
func (p Published) URL() string {
    return "/posts/" + strings.ReplaceAll(strings.ToLower(p.title), " ", "-")
}

func main() {
    d := NewDraft("Type State").Edit("States as types.")
    r, err := d.Submit("lee")
    if err != nil {
        panic(err)
    }
    // r.URL()
    //   error: r.URL undefined (type InReview has no field or method URL)
    d = r.Reject().Edit("States as types, revised.")
    r, err = d.Submit("lee")
    if err != nil {
        panic(err)
    }
    p := r.Approve()
    fmt.Println(r.reviewer, "approved", p.URL())

    // Go cannot stop reuse of an old value: d is still a Draft and can be submitted again.
    // Within one package, Published{} also compiles; the guarantee holds across packages only.
    if _, err := NewDraft("Empty").Submit("lee"); err != nil {
        fmt.Println("rejected:", err)
    }
}

In practice: split a type when some methods are valid only after a step (a connection after Connect, a request after Build), and return errors from transitions that can fail. Accept that Go cannot stop reuse of an old value, and that code inside the same package can construct any state.

The zero value of every state type is always constructible (InReview{}); give it a safe meaning or check it in the methods.

With pointer receivers, the old variable and the new state may share data; value receivers on small structs avoid that.

Constrain a generic type: extends + keyof, type sets, trait bounds, concepts

Go

Read a type parameter (Types & syntax) shows how to read [T any] in a signature; this entry covers writing the constraint that says what T must support. A Go constraint is an interface. Besides methods, a constraint interface may list a type set: `~int | ~int64 | ~float64`, where ~int64 means any type whose underlying type is int64, so a defined Cents type fits. The operators allowed in the body are those every type in the set supports. comparable permits == and != (needed for map keys), and cmp.Ordered (Go 1.21+) permits < and friends. A constraint can mix a type set with methods.

Complete program

Complete program.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "cmp"
    "fmt"
    "slices"
    "strings"
)

// A constraint is an interface. A union of types (a type set) can only be used
// as a constraint, never as the type of a variable.
// ~int64 means "any type whose underlying type is int64", so defined types fit.
type Number interface {
    ~int | ~int64 | ~float64
}

type Cents int64

func Sum[T Number](xs []T) T {
    var total T
    for _, x := range xs {
        total += x // + is allowed because every type in the set supports it
    }
    return total
}

// cmp.Ordered (Go 1.21+) is every type that supports < <= > >=.
func MaxOf[T cmp.Ordered](xs []T) T {
    best := xs[0]
    for _, x := range xs[1:] {
        best = max(best, x)
    }
    return best
}

// comparable allows == and !=, which map keys and Index need.
func Index[T comparable](xs []T, want T) int {
    for i, x := range xs {
        if x == want {
            return i
        }
    }
    return -1
}

// A constraint can mix a type set with required methods.
type Code interface {
    ~string
    Valid() bool
}

type SKU string

func (s SKU) Valid() bool { return strings.HasPrefix(string(s), "SKU-") }

func Normalize[T Code](codes []T) []T {
    out := make([]T, 0, len(codes))
    for _, c := range codes {
        if c.Valid() {
            out = append(out, T(strings.ToUpper(string(c)))) // conversion works via ~string
        }
    }
    return out
}

func main() {
    fmt.Println(Sum([]Cents{250, 199}), Sum([]float64{0.5, 0.25}))
    fmt.Println(MaxOf([]string{"pear", "apple", "zucchini"}), MaxOf([]int{3, 9, 4}))
    fmt.Println(Index([]string{"a", "b"}, "b"))
    fmt.Println(Normalize([]SKU{"SKU-ab1", "x-2", "SKU-cd3"}))
    // Sum([]string{"a"})
    //   error: string does not satisfy Number (string missing in ~int | ~int64 | ~float64)
    // var n Number
    //   error: cannot use type Number outside a type constraint: interface contains type constraints

    // slices and maps in the standard library are written the same way.
    fmt.Println(slices.Max([]Cents{5, 2, 8}))
}

In practice: start with any, comparable or cmp.Ordered, and write a union only when you need arithmetic. Use ~ in unions so defined types are accepted. Interfaces with type sets work only as constraints: they cannot be the type of a variable or field.

Without ~, `int64` in a union matches only int64 itself, not type Cents int64.

Since Go 1.20, comparable is satisfied by interface types too, so == on such a T can panic at run time if the dynamic values are not comparable.

golang.org/x/exp/constraints is superseded by cmp.Ordered for ordering; define small unions like Number yourself.

Know when subtypes substitute (variance): covariant arrays, invariant slices, lifetime subtyping, covariant returns

Go

Read a type parameter (Types & syntax) treats each instantiation on its own; variance is the rule for when a container of Dog can be used where a container of Animal is expected. Go has no variance. A []Dog is not a []Animal even when Dog implements Animal, because a []Animal holds interface values (a type word and a data word per element) and has a different memory layout. The same holds for maps, channels and function types: a func(Animal) is not a func(Dog). Interface satisfaction needs exact method signatures, so there are no covariant return types either.

Complete program

Complete program.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

type Animal interface{ Name() string }

type Dog struct{ name string }

func (d Dog) Name() string { return d.name }
func (d Dog) Bark() string { return "woof" }

func Names(animals []Animal) []string {
    out := make([]string, len(animals))
    for i, a := range animals {
        out[i] = a.Name()
    }
    return out
}

// A generic helper does the copy for any element type that implements I.
func Upcast[T Animal](xs []T) []Animal {
    out := make([]Animal, len(xs))
    for i, x := range xs {
        out[i] = x // each element is wrapped in an interface value
    }
    return out
}

// Often better: make the consumer generic, so no copy is needed.
func NamesOf[T Animal](xs []T) []string {
    out := make([]string, len(xs))
    for i, x := range xs {
        out[i] = x.Name()
    }
    return out
}

func main() {
    dogs := []Dog{{"Rex"}, {"Fido"}}
    // Names(dogs)
    //   error: cannot use dogs (variable of type []Dog) as []Animal value in argument to Names
    // A []Animal holds interface values (type + pointer per element) and has a different
    // memory layout from []Dog, so Go has no slice variance at all.
    fmt.Println(Names(Upcast(dogs)), NamesOf(dogs))

    // Function types are invariant too: a func(Animal) is not a func(Dog).
    greet := func(a Animal) string { return "hi " + a.Name() }
    var forDogs func(Dog) string = func(d Dog) string { return greet(d) } // wrap it
    fmt.Println(forDogs(dogs[0]))

    // Method signatures must match exactly: no covariant return types.
    // type Cloner interface{ Clone() Animal }
    // A method Clone() Dog does not satisfy Cloner; it must return Animal.
}

In practice: copy into a new slice (a generic Upcast[T Animal] helper does it once), wrap functions in a closure of the right type, or make the consumer generic (NamesOf[T Animal]) so it takes []Dog directly with no copy.

The copy is O(n) and allocates, so for hot paths the generic-consumer form is better.

A single Dog value converts to Animal implicitly; only composite types (slices, maps, funcs, channels) are invariant.

Abstract over containers (higher-kinded types): HKT encodings, GATs, template template parameters

Go

Read a type parameter (Types & syntax) covers parameters that stand for a type such as int; this entry covers parameters that would stand for a type constructor, so one function could work over any container. A type constructor such as Option (a generic type before it is instantiated) takes a type and produces one; an HKT would let code take the constructor itself as a parameter. Go generics accept only types, so `func Map[F[_] any, A, B any]` cannot be written. Each container gets its own generic function, or (Go 1.27+) a generic method with its own type parameter: `func (o Option[T]) Map[B any](f func(T) B) Option[B]`. Interface methods still cannot declare type parameters, so no interface can describe "any container with Map".

Complete program

Complete program.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "fmt"
    "strconv"
)

// Go generics take types, not type constructors. This parses, but the type checker
// rejects it with "F is not a generic type", because F stands for a type:
//   func Map[F any, A, B any](fa F[A], f func(A) B) F[B]
// So each container gets its own generic function or method.

type Option[T any] struct {
    value T
    ok    bool
}

func Some[T any](v T) Option[T] { return Option[T]{value: v, ok: true} }
func None[T any]() Option[T]    { return Option[T]{} }

// Go 1.27+: a method may declare its own type parameters (B here).
func (o Option[T]) Map[B any](f func(T) B) Option[B] {
    if !o.ok {
        return None[B]()
    }
    return Some(f(o.value))
}

// Before Go 1.27, and for built-in containers, a top-level function does the job.
func MapSlice[A, B any](xs []A, f func(A) B) []B {
    out := make([]B, 0, len(xs))
    for _, x := range xs {
        out = append(out, f(x))
    }
    return out
}

// What still cannot be written is the abstraction over both:
//   type Functor[T any] interface { Map[B any](func(T) B) Functor[B] }
//   error: interface method must have no type parameters

func main() {
    double := func(n int) int { return n * 2 }
    fmt.Println(MapSlice([]int{1, 2, 3}, double))
    fmt.Println(MapSlice([]int{1, 2}, strconv.Itoa))
    fmt.Println(Some(21).Map(double), None[int]().Map(strconv.Itoa))
}

In practice: write MapSlice, MapOption and similar per container, or use the slices and maps packages and plain loops. This is the expected Go style, and the duplication is usually a few lines.

Generic methods need Go 1.27 or later; on older versions, Map must be a top-level function.

A generic method cannot implement an interface method, so it gives call-site convenience, not abstraction.