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.

Paradigms: imperative, OOP & functional

How each language supports the main programming styles: step-by-step imperative code, objects with encapsulation, polymorphism and composition, and functional programming with pure functions, immutability, higher-order functions and algebraic data types. Most real programs mix them; each entry names when a style fits.

Imperative & procedural programming: statements, loops, mutation, procedures

Go

Go is a deliberately imperative, procedural language: functions, for loops (the only loop keyword), assignment and explicit error returns, with no classes and few functional helpers. A map lookup of a missing key yields the zero value, which makes accumulator loops short.

Complete program

Complete program.

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

import (
    "fmt"
    "maps"
    "slices"
)

type Order struct {
    Category string
    Cents    int
}

// totalsByCategory is a procedure: a loop that updates local state.
func totalsByCategory(orders []Order) map[string]int {
    totals := make(map[string]int)
    for _, o := range orders {
        totals[o.Category] += o.Cents // a missing key reads as 0
    }
    return totals
}

func main() {
    orders := []Order{
        {"books", 1200}, {"games", 5999}, {"books", 850}, {"music", 999}, {"games", 2000},
    }
    totals := totalsByCategory(orders)
    grand := 0
    // Map order is random on each run; sort the keys for stable output.
    for _, category := range slices.Sorted(maps.Keys(totals)) {
        cents := totals[category]
        fmt.Printf("%-6s $%d.%02d\n", category, cents/100, cents%100)
        grand += cents
    }
    fmt.Printf("total  $%d.%02d\n", grand/100, grand%100)
}

In practice: write the plain loop; it is idiomatic Go, not a lack of style. Return new values from functions rather than updating package-level variables. Sort map keys before printing, because map iteration order is randomised.

Ranging over a map visits keys in a different order on each run; slices.Sorted(maps.Keys(m)) gives a stable order.

A map is a reference to shared storage: a function that writes into a map it received changes the caller's map too.

Objects & encapsulation: classes, struct methods, impl blocks, class invariants

Go

Go has no classes: a struct holds the data and methods are declared on it with a receiver. Visibility is per package, not per type: a lowercase field or function is unexported (hidden from other packages) but fully visible to every file in its own package. A NewX function that validates and returns (*X, error) plays the constructor role by convention.

Complete program

Complete program.

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

import (
    "errors"
    "fmt"
)

// Account keeps one invariant: the balance never goes below zero.
// Lowercase fields are unexported: hidden from other packages, not from this one.
type Account struct {
    owner string
    cents int
}

var ErrInsufficient = errors.New("insufficient funds")

// NewAccount is the constructor by convention; it validates before building.
func NewAccount(owner string, opening int) (*Account, error) {
    if opening < 0 {
        return nil, fmt.Errorf("opening balance %d: must not be negative", opening)
    }
    return &Account{owner: owner, cents: opening}, nil
}

func (a *Account) Balance() int { return a.cents } // getter, no Get prefix

func (a *Account) Withdraw(cents int) error {
    if cents <= 0 || cents > a.cents {
        return ErrInsufficient
    }
    a.cents -= cents
    return nil
}

func main() {
    acct, err := NewAccount("Ada", 7500)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(acct.Withdraw(10000), acct.Withdraw(3000), acct.Balance()) // insufficient funds <nil> 4500

    _, err = NewAccount("Bob", -1)
    fmt.Println(err)
}

In practice: put a type with invariants in its own package so callers must go through NewX and the methods; use pointer receivers for methods that mutate; return errors for invalid input rather than panicking.

This one-file program is package main, so main itself could write acct.cents directly; the hiding only takes effect across a package boundary (for example package bank imported by main).

Account{} is always constructible, even from other packages, with every field at its zero value; design so that zero value is valid, or document that NewAccount is required.

Go getters drop the Get prefix: Balance(), not GetBalance().

Polymorphism: structural interfaces, Go interfaces, dyn Trait, virtual functions

Go

Go interfaces are sets of methods satisfied implicitly: a type implements an interface simply by having the methods, with no declaration. That lets the consumer define the small interface it needs, after the fact, over types it does not own. Calls through an interface value are dynamic; a type assertion or type switch recovers the concrete type.

Complete program

Complete program.

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

import (
    "fmt"
    "math"
)

type Shape interface { // small, and defined where it is used
    Area() float64
    Name() string
}

type Circle struct{ Radius float64 }
type Rect struct{ W, H float64 }

// No "implements": having the methods is enough.
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (c Circle) Name() string  { return "circle" }
func (r Rect) Area() float64   { return r.W * r.H }
func (r Rect) Name() string    { return "rect" }

var _ Shape = Rect{} // compile-time check that Rect satisfies Shape

// Accept interfaces: totalArea works with any Shape.
func totalArea(shapes []Shape) float64 {
    sum := 0.0
    for _, s := range shapes {
        sum += s.Area() // dynamic call through the interface
    }
    return sum
}

// Return structs: the constructor returns the concrete type.
func NewSquare(side float64) Rect { return Rect{side, side} }

func main() {
    shapes := []Shape{Circle{1}, Rect{2, 3}, NewSquare(2)}
    for _, s := range shapes {
        fmt.Printf("%-6s %.2f\n", s.Name(), s.Area())
    }
    fmt.Printf("total  %.2f\n", totalArea(shapes))
    if c, ok := shapes[0].(Circle); ok { // type assertion recovers the concrete type
        fmt.Println("first radius:", c.Radius)
    }
}

In practice: accept interfaces, return structs: functions take the narrowest interface they use and constructors return concrete types; keep interfaces to one to three methods and define them in the consuming package; add var _ Shape = Rect{} when you want a compile-time check.

An interface holding a nil *T is not a nil interface: if err != nil is true for a typed nil pointer. Return a literal nil for "no value".

Methods with pointer receivers are only in *T's method set, so a T value does not satisfy an interface that needs them; store &T{} instead.

Inheritance vs composition: extends, struct embedding, supertraits, object slicing

Go

Go has no inheritance. Embedding a type in a struct promotes the embedded type's fields and methods, so s.Log() works, but it is composition with automatic forwarding, not subtyping: a Service is not a Logger and cannot be passed where a Logger is required. There is no virtual dispatch either: a method of the embedded type always calls the embedded type's methods, even if the outer struct declares one with the same name.

Complete program

Complete program.

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

import "fmt"

type Logger struct{}

func (Logger) Prefix() string   { return "[log]" }
func (l Logger) Log(msg string) { fmt.Println(l.Prefix(), msg) } // always Logger.Prefix

// Service embeds Logger: Logger's methods are promoted to Service.
type Service struct {
    Logger // embedded field: its name is the type name
    name   string
}

// This shadows Logger.Prefix for callers of Service, but Logger.Log never sees it.
func (Service) Prefix() string { return "[svc]" }

type LogWriter interface{ Log(string) }

func useLogger(l Logger) { l.Log("got a Logger") }

func main() {
    s := Service{name: "orders"}
    s.Log("starting " + s.name) // promoted: same as s.Logger.Log(...)
    fmt.Println(s.Prefix())     // [svc]: the outer method wins for direct calls

    // useLogger(s) // compile error: Service is not a Logger; embedding is not subtyping
    useLogger(s.Logger) // pass the embedded value explicitly

    var w LogWriter = s // Service's method set includes Log, so it satisfies interfaces
    w.Log("via interface")
}

In practice: embed to reuse behaviour and satisfy interfaces; use interfaces, not embedding, wherever code must accept several types; do not embed types whose exported methods you do not want in your own API.

Embedding exports the embedded type's methods as part of your type's API; embedding sync.Mutex in an exported struct, for example, lets callers lock it.

Two embedded types with the same method name make the promoted call ambiguous, a compile error only when you call it.

Design principles: SOLID and dependency inversion with an injected interface

Go

SOLID is phrased for classes, but every principle applies to Go: single responsibility per package and type, small interfaces (io.Reader is the model for interface segregation), and dependency inversion through implicit interfaces. The consumer declares the interface it needs, any type with that method satisfies it, and the constructor takes it as a parameter. Open/closed follows: a new notifier is a new type, with no edit to OrderService.

Complete program

Complete program.

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

import "fmt"

// Notifier is declared by its consumer, with only the method it calls.
type Notifier interface {
    Send(to, message string)
}

// OrderService depends on the abstraction; the detail is injected.
type OrderService struct {
    notifier Notifier
    nextID   int
}

func NewOrderService(n Notifier) *OrderService {
    return &OrderService{notifier: n, nextID: 1}
}

func (s *OrderService) Place(customer string, cents int) int {
    id := s.nextID
    s.nextID++
    s.notifier.Send(customer, fmt.Sprintf("order %d confirmed: %d cents", id, cents))
    return id
}

type ConsoleNotifier struct{}

func (ConsoleNotifier) Send(to, message string) { fmt.Printf("to %s: %s\n", to, message) }

// FakeNotifier records messages; tests inspect Sent instead of a real inbox.
type FakeNotifier struct{ Sent []string }

func (f *FakeNotifier) Send(to, message string) { f.Sent = append(f.Sent, to+" | "+message) }

func main() {
    fake := &FakeNotifier{}
    svc := NewOrderService(fake)
    svc.Place("ada@example.com", 4200)
    svc.Place("ada@example.com", 999)
    fmt.Printf("%q\n", fake.Sent)

    NewOrderService(ConsoleNotifier{}).Place("bob@example.com", 1500) // same policy, real detail
}

In practice: define the interface in the consuming package, not next to the implementation; pass dependencies to NewX and keep them in unexported fields; wire concrete types together in main.

A fake with a pointer receiver must be passed as &FakeNotifier{}; passing the value does not compile because Send is not in its method set.

Declaring a large interface up front "for testing" works against interface segregation; add an interface when a second implementation or a test needs it.

Functional programming: pure functions, functions as values, functional core

Go

Go has first-class functions and closures, but it is deliberately an imperative language: there are no map/filter/reduce built-ins, no immutable data structures, and statements (loops, if, switch) rather than expressions do most of the work. Pure functions are still the easiest Go code to test, and table-driven tests exist for exactly this shape: inputs in, expected output out.

Complete program

Complete program.

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

import "fmt"

type Order struct {
    SubtotalCents int
    LoyaltyYears  int
}

// discountPercent is pure: the same years always give the same percent.
func discountPercent(years int) int {
    switch {
    case years >= 5:
        return 15
    case years >= 2:
        return 5
    default:
        return 0
    }
}

func totalCents(o Order) int {
    return o.SubtotalCents * (100 - discountPercent(o.LoyaltyYears)) / 100
}

func formatCents(c int) string { return fmt.Sprintf("%d.%02d", c/100, c%100) }

func main() {
    // A pure function's test is a table of inputs and expected outputs.
    for _, tc := range []struct{ years, want int }{{6, 15}, {3, 5}, {0, 0}} {
        if got := discountPercent(tc.years); got != tc.want {
            panic(fmt.Sprintf("discountPercent(%d) = %d, want %d", tc.years, got, tc.want))
        }
    }

    // Imperative shell: the printing happens out here, around the pure core.
    orders := []Order{{12000, 1}, {8000, 3}, {20000, 6}}
    for i, o := range orders {
        fmt.Printf("order %d: %s\n", i+1, formatCents(totalCents(o)))
    }
}

In practice: write the decision logic as plain functions over values with no package-level state, and keep I/O in main or in a thin handler. Pass dependencies such as a clock or a writer in as parameters instead of reaching for globals. Do not force FP idioms on Go; a clear loop is the normal style.

Slices and maps passed to a function share their backing storage, so a function that writes to one has a side effect visible to the caller.

In real code the table lives in a _test.go file and runs with go test; it is inlined here only to keep the program self-contained.

Immutability: readonly and spread, value copies, let vs let mut, const

Go

Go has no immutable variables or read-only types; const only names compile-time numbers, strings and booleans. What it has is value semantics: assigning or passing a struct copies its fields. Slices, maps, pointers and channels inside the struct are copied as headers that still point at the same data, which is the common aliasing trap.

Complete program

Complete program.

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

import (
    "fmt"
    "maps"
    "slices"
)

type Account struct {
    ID      string
    Balance int
    Tags    []string
}

// withCredit receives a copy of the struct, but the copied Tags header
// still points at the caller's backing array, so clone before changing it.
func withCredit(a Account, amount int) Account {
    a.Balance += amount
    a.Tags = append(slices.Clone(a.Tags), "active")
    return a
}

func main() {
    original := Account{ID: "a1", Balance: 100, Tags: []string{"new"}}
    credited := withCredit(original, 25)
    fmt.Println(original.Balance, original.Tags)
    fmt.Println(credited.Balance, credited.Tags)

    // The aliasing trap: a struct copy shares its slice elements.
    alias := original
    alias.Balance = 0         // independent: ints are copied
    alias.Tags[0] = "changed" // shared: same backing array
    fmt.Println(original.Balance, original.Tags[0])

    // Maps are shared the same way; maps.Clone makes a shallow, independent copy.
    limits := map[string]int{"daily": 500}
    snapshot := maps.Clone(limits)
    limits["daily"] = 900
    fmt.Println(snapshot["daily"], limits["daily"])

    const maxRetries = 3 // const is limited to numbers, strings and booleans
    fmt.Println(maxRetries)
}

In practice: pass small structs by value when the callee should not change the caller's copy. Clone slices and maps (slices.Clone, maps.Clone) before modifying data you did not create. Keep fields unexported and expose methods when a type must not be changed from outside.

append may write into the caller's backing array when the slice has spare capacity, so even appending to a received slice can change data the caller sees.

slices.Clone and maps.Clone are shallow: a slice of pointers or a map of slices still shares the pointed-to data.

Higher-order functions: map/filter/reduce, currying, composition, returning closures

Go

Functions can be passed and returned like any value, and generics (since 1.18) make Map and Filter helpers easy to write. The standard library still does not ship them for slices, and most Go code uses a plain for loop: the Go authors favor one obvious way that shows the cost of each step. Higher-order functions are common elsewhere, for example sort comparators, http.HandlerFunc middleware and functional options.

Complete program

Complete program.

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

import (
    "fmt"
    "slices"
)

// Generic Map and Filter: not in the standard library, but short to write.
func Map[T, U any](xs []T, f func(T) U) []U {
    out := make([]U, 0, len(xs))
    for _, x := range xs {
        out = append(out, f(x))
    }
    return out
}

func Filter[T any](xs []T, keep func(T) bool) []T {
    return slices.DeleteFunc(slices.Clone(xs), func(x T) bool { return !keep(x) })
}

func multiplyBy(factor int) func(int) int {
    return func(n int) int { return n * factor } // returns a closure over factor
}

// compose(f, g) runs f, then g.
func compose[A, B, C any](f func(A) B, g func(B) C) func(A) C {
    return func(a A) C { return g(f(a)) }
}

func main() {
    prices := []int{12, 40, 7, 25}
    fmt.Println(Map(Filter(prices, func(p int) bool { return p >= 10 }), multiplyBy(3)))

    label := compose(multiplyBy(10), func(n int) string { return fmt.Sprintf("%d pts", n) })
    fmt.Println(label(4))

    // What most Go code writes instead: one loop, no intermediate slices.
    total := 0
    for _, p := range prices {
        if p >= 10 {
            total += p * 3
        }
    }
    fmt.Println(total)
}

In practice: write loops for data transformations. Use function parameters for callbacks, comparators and strategies, and closures returned from constructors for middleware or configuration. Add a generic helper only when the same shape repeats.

Each helper call allocates a new slice; chaining Filter then Map makes two passes and an intermediate slice that a single loop avoids.

Go 1.23 iterators (iter.Seq) plus slices.Collect and slices.Sorted cover some pipeline cases lazily, but there is still no standard Map or Filter over them.

Algebraic data types: discriminated unions, type switches, enum + match, std::variant

Go

Go has no sum types. The usual stand-in is an interface implemented by one struct per variant, inspected with a type switch. An unexported marker method seals the interface so only the defining package can add variants, but the compiler does not check that a type switch handles all of them; a missed case falls through to default at run time.

Complete program

Complete program.

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

import "fmt"

// A sealed interface: the unexported method means only this package can add
// variants. Go still does not check that a type switch covers all of them.
type PaymentEvent interface{ isPaymentEvent() }

type Authorized struct{ AmountCents int }
type Captured struct{ AmountCents int }
type Refunded struct {
    AmountCents int
    Reason      string
}
type Failed struct{ Code string }

func (Authorized) isPaymentEvent() {}
func (Captured) isPaymentEvent()   {}
func (Refunded) isPaymentEvent()   {}
func (Failed) isPaymentEvent()     {}

func describe(e PaymentEvent) string {
    switch e := e.(type) { // inside each case, e has that concrete type
    case Authorized:
        return fmt.Sprintf("hold %d", e.AmountCents)
    case Captured:
        return fmt.Sprintf("charge %d", e.AmountCents)
    case Refunded:
        return fmt.Sprintf("refund %d (%s)", e.AmountCents, e.Reason)
    case Failed:
        return "failed: " + e.Code
    default: // a forgotten variant only shows up here, at run time
        panic(fmt.Sprintf("unhandled event %T", e))
    }
}

func main() {
    events := []PaymentEvent{
        Authorized{5000}, Captured{5000}, Refunded{1200, "damaged"}, Failed{"card_declined"},
    }
    for _, e := range events {
        fmt.Println(describe(e))
    }
}

In practice: give every type switch a default that panics or returns an error, so a forgotten variant fails loudly. Seal the interface with an unexported method. Prefer a regular method on the interface when each variant can simply answer the question itself.

A nil interface value matches no case; it lands in default (or in an explicit case nil), so handle it.

Third-party linters (for example the exhaustive analyzer) can check type switches over sealed interfaces; the compiler and go vet do not.

A pointer receiver changes which types satisfy the interface: with func (*Refunded) isPaymentEvent(), only *Refunded matches, not Refunded.

Declarative vs imperative: loops vs pipelines, recursion vs iteration

Go

Go is imperative by design: the idiomatic way to filter, sort and take is a for loop plus the slices package, and the language has no lazy pipeline syntax. Whole-slice functions such as slices.DeleteFunc, slices.SortFunc and slices.Contains are as declarative as the standard library gets. Goroutine stacks grow on demand, so recursion goes deeper than in most languages, but there is no tail-call elimination and very deep recursion still uses memory and can hit the stack limit.

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"
)

type User struct {
    Name   string
    Active bool
    Score  int
}

func byScoreDesc(a, b User) int { return cmp.Compare(b.Score, a.Score) }

// sumTo recurses; Go stacks grow, but there is no tail-call elimination.
func sumTo(n int) int {
    if n == 0 {
        return 0
    }
    return n + sumTo(n-1)
}

func main() {
    users := []User{{"ana", true, 82}, {"ben", false, 97}, {"cy", true, 91}, {"dee", true, 64}, {"eli", true, 88}}

    // Imperative, and idiomatic Go: a loop that builds the result.
    var active []User
    for _, u := range users {
        if u.Active {
            active = append(active, u)
        }
    }
    slices.SortFunc(active, byScoreDesc)
    fmt.Println(active[:min(3, len(active))])

    // As declarative as the standard library gets: whole-slice operations.
    ranked := slices.DeleteFunc(slices.Clone(users), func(u User) bool { return !u.Active })
    slices.SortFunc(ranked, byScoreDesc)
    fmt.Println(ranked[:min(3, len(ranked))])

    fmt.Println(sumTo(1000))
}

In practice: write the loop; Go readers expect it, and it makes allocation and early exit obvious. Use slices helpers for sorting, searching and removal. Use recursion for naturally recursive data such as trees, and iteration for long linear chains.

slices.DeleteFunc and slices.SortFunc modify the slice they are given; clone first when the input belongs to someone else.

The default maximum goroutine stack is 1 GB on 64-bit systems; exceeding it is a fatal error, not a recoverable panic.