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.

Errors & cleanup

Recognize results and ignored values

Go

Many APIs return (value, error); nil means no error. _ discards a result; it does not check it. panic interrupts normal execution. EOF may accompany usable read data.

Fragment

Import plus fragments; return assumes no result.

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

n, err := strconv.Atoi("24")
if err != nil {
  return
}

_ = n

Return or propagate a failure

Go

A returned error is an ordinary result that callers must handle. nil conventionally means success. fmt.Errorf with %w wraps an error so errors.Is/As can inspect its chain; ignoring a returned error does not propagate it.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

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

func requirePositive(n int) (int, error) {
  if n <= 0 {
    return 0, errors.New("positive value required")
  }
  return n, nil
}

Recognize resource cleanup

Go

defer schedules a call for when the surrounding function returns, including normal panic unwinding. Arguments are evaluated when the defer is registered. Deferred calls run in reverse registration order; defer is not a block-exit mechanism.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
func observe() {
  defer func() {
    // Cleanup before observe returns.
  }()

  // Work.
}

Choose an error-handling strategy: exceptions, error values, Result, error codes, optional, panics

Go

Go's idiomatic strategy is errors as values: a function that can fail returns error as its last result, nil means success, and the caller checks if err != nil right away. The failure is visible in every signature, there is no hidden control flow, and the cost is the explicit check at each call. Go has no exceptions. panic and recover exist, but they are reserved for bugs and impossible states, not for expected failures; absence is reported with the comma-ok form (v, ok := m[k]) or a nil pointer, not with an error. Error codes in the C sense appear only at the system boundary (syscall.Errno), wrapped inside ordinary error values.

Complete program

Complete program.

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

import (
    "errors"
    "fmt"
    "regexp"
    "strconv"
)

var errOutOfRange = errors.New("port out of range")

// 1. Errors as values (idiomatic): the last result is an error, nil on success.
func parsePort(text string) (int, error) {
    port, err := strconv.Atoi(text)
    if err != nil {
        return 0, fmt.Errorf("parse port %q: %w", text, err)
    }
    if port < 1 || port > 65535 {
        return 0, fmt.Errorf("parse port %q: %w", text, errOutOfRange)
    }
    return port, nil
}

// 2. Absence is not an error: the comma-ok form reports "missing" as a bool.
var wellKnown = map[string]int{"http": 80, "https": 443}

// 3. Panics are for bugs and impossible states. The Must* convention panics on
// input that is fixed in the source, such as a regexp literal checked at startup.
var hostPattern = regexp.MustCompile(`^[a-z0-9.-]+$`)

func main() {
    for _, text := range []string{"8080", "99999", "eighty"} {
        port, err := parsePort(text)
        if err != nil {
            // Callers branch on the kind of failure with errors.Is or errors.As.
            fmt.Println("error:", err, "| out of range:", errors.Is(err, errOutOfRange))
            continue
        }
        fmt.Println("parsed:", port)
    }

    if port, ok := wellKnown["ssh"]; ok {
        fmt.Println("ssh port:", port)
    } else {
        fmt.Println("ssh port: unknown")
    }

    fmt.Println("valid host:", hostPattern.MatchString("api.example.com"))
}

In practice: return error for anything the caller might reasonably handle, add context with fmt.Errorf and %w, and branch with errors.Is (sentinel values) or errors.As (typed errors). Use comma-ok for "not found" when it is not a failure. Panic only when continuing would be wrong, and use the Must* convention only for inputs fixed in the source code.

Assigning the error to _ (v, _ := f()) is an explicit opt-out that no default tool reports; errcheck finds errors dropped entirely (a bare f() call) and reports _ only with -blank.

A function that returns (T, error) should return a meaningful zero T with a non-nil error; callers must not use T when err != nil unless the documentation says otherwise (io.Reader.Read is the classic exception).

Define a custom error type: Error subclasses, error structs, error enums, exception hierarchies

Go

Any type with an Error() string method satisfies the error interface. Two kinds of custom errors are common. Sentinel errors are package-level values made with errors.New (io.EOF, fs.ErrNotExist); callers compare with errors.Is. Error types are structs that carry data (a field name, a status); callers extract them with errors.As, or since Go 1.26 with the generic errors.AsType[*T](err). Both functions walk wrapped chains, so they keep working after fmt.Errorf("...: %w", err).

Complete program

Complete program.

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

import (
    "errors"
    "fmt"
)

// Sentinel errors: fixed values that callers compare with errors.Is.
var (
    ErrNotFound     = errors.New("not found")
    ErrUnauthorized = errors.New("unauthorized")
)

// A custom error type carries data. Callers extract it with errors.As.
type ValidationError struct {
    Field  string
    Reason string
}

// A pointer receiver is the usual choice, so the error compares and unwraps as *ValidationError.
func (e *ValidationError) Error() string {
    return fmt.Sprintf("invalid %s: %s", e.Field, e.Reason)
}

func findUser(id string) (string, error) {
    if id != "u1" {
        return "", fmt.Errorf("find user %s: %w", id, ErrNotFound)
    }
    return "Ada", nil
}

func setQuantity(n int) error {
    if n < 1 || n > 1000 {
        return &ValidationError{Field: "quantity", Reason: fmt.Sprintf("%d is outside 1..1000", n)}
    }
    return nil
}

func describe(err error) string {
    // errors.As finds the first error in the chain that has the target's type.
    var ve *ValidationError
    switch {
    case err == nil:
        return "ok"
    case errors.Is(err, ErrNotFound):
        return "404: " + err.Error()
    case errors.As(err, &ve):
        return fmt.Sprintf("422: field=%s reason=%s", ve.Field, ve.Reason)
    default:
        return "500: " + err.Error()
    }
}

func main() {
    _, err := findUser("u9")
    fmt.Println(describe(err))
    fmt.Println(describe(setQuantity(5000)))
    fmt.Println(describe(setQuantity(7)))
    fmt.Println(describe(fmt.Errorf("token check: %w", ErrUnauthorized)))

    // Go 1.26 added the generic errors.AsType, which avoids declaring the target variable.
    if ve, ok := errors.AsType[*ValidationError](fmt.Errorf("save: %w", setQuantity(0))); ok {
        fmt.Println("AsType found field:", ve.Field)
    }
}

In practice: export a sentinel when callers only need to know which condition happened, and a struct type when they need details. Use a pointer receiver for Error() and return &MyError{...}, so errors.As targets *MyError. Never compare err.Error() strings.

A nil *MyError stored in an error interface is not == nil. Return a literal nil, not a typed nil pointer variable, on success.

errors.AsType needs Go 1.26 or later; on older versions declare var target *MyError and call errors.As(err, &target).

Sentinels are part of your API: renaming or rewrapping one breaks callers that test for it with errors.Is.

Add context to an error: cause, %w, source chains, nested exceptions

Go

fmt.Errorf with the %w verb returns a new error whose message includes the cause and whose Unwrap method returns it. errors.Is and errors.As then search the whole chain, so callers can still detect fs.ErrNotExist or a *fs.PathError three layers up. errors.Unwrap peels one layer. %v formats the cause into the text but does not wrap it, which deliberately cuts the chain. Since Go 1.20 one Errorf call may contain several %w verbs, and the result unwraps to all of them.

Complete program

Complete program.

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

import (
    "errors"
    "fmt"
    "io/fs"
    "os"
)

func readSettings(path string) ([]byte, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        // %w wraps: the message gains context and the cause stays inspectable.
        return nil, fmt.Errorf("read settings: %w", err)
    }
    return data, nil
}

func loadConfig() error {
    if _, err := readSettings("/no/such/dir/settings.json"); err != nil {
        return fmt.Errorf("load config: %w", err)
    }
    return nil
}

func main() {
    err := loadConfig()
    fmt.Println(err)

    // errors.Is and errors.As search the whole chain, not just the outer error.
    fmt.Println("not exist:", errors.Is(err, fs.ErrNotExist))
    var pathErr *fs.PathError
    if errors.As(err, &pathErr) {
        fmt.Printf("op=%s path=%s\n", pathErr.Op, pathErr.Path)
    }

    // errors.Unwrap peels one layer at a time.
    for e := err; e != nil; e = errors.Unwrap(e) {
        fmt.Printf("  %T\n", e)
    }

    // %v formats the cause into the text but does not wrap it: the chain is cut.
    flat := fmt.Errorf("load config: %v", err)
    fmt.Println("flattened still not exist:", errors.Is(flat, fs.ErrNotExist))
}

In practice: wrap with a short "doing X: %w" prefix at each layer that adds information, giving messages like "load config: read settings: open ...: no such file or directory". Use %v instead of %w when you do not want callers to depend on an implementation detail (a driver error, say). Custom error types can join a chain by implementing Unwrap() error.

Wrapping makes the cause part of your API: once callers use errors.Is on it, switching libraries breaks them. Wrap deliberately.

Avoid prefixes like "failed to" or "error:" in each layer; the chain already reads as a sequence of failures.

errors.Unwrap returns nil for an error made with several %w verbs or errors.Join; those implement Unwrap() []error instead, which errors.Is and errors.As understand.

Return typed errors: Result, (T, error), Result<T, E>, std::expected

Go

Go has no sum types (the FAQ explains the decision: they interact badly with interfaces), so there is no Result. The idiom (T, error) plays the same role: two results, and the convention that T is only meaningful when err is nil. To give callers a closed set of failures, export sentinel errors and error struct types and document them; callers branch with errors.Is, errors.As/AsType or a type switch. The compiler does not check that every kind is handled, so a default case is mandatory.

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

// Go has no sum types. The closest shape is (T, error) plus a closed set of
// error types; the compiler does not check that callers handle every one.
var ErrEmpty = errors.New("username is empty")

type TooLongError struct{ Max, Actual int }

func (e *TooLongError) Error() string {
    return fmt.Sprintf("use at most %d characters (got %d)", e.Max, e.Actual)
}

type BadCharError struct{ Char rune }

func (e *BadCharError) Error() string { return fmt.Sprintf("%q is not allowed", e.Char) }

func parseUsername(input string) (string, error) {
    name := strings.ToLower(strings.TrimSpace(input))
    if name == "" {
        return "", ErrEmpty
    }
    if n := len([]rune(name)); n > 16 {
        return "", &TooLongError{Max: 16, Actual: n}
    }
    for _, c := range name {
        if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_') {
            return "", &BadCharError{Char: c}
        }
    }
    return name, nil
}

// classify plays the role of a match: a type switch over the error's dynamic type.
// The default case is required, because nothing stops a new error type appearing.
func classify(err error) string {
    switch e := err.(type) {
    case nil:
        return "ok"
    case *TooLongError:
        return fmt.Sprintf("too long by %d", e.Actual-e.Max)
    case *BadCharError:
        return fmt.Sprintf("bad char %q", e.Char)
    default:
        if errors.Is(err, ErrEmpty) {
            return "empty"
        }
        return "unexpected: " + err.Error()
    }
}

func main() {
    for _, input := range []string{"  Ada_L ", "", "grace hopper", strings.Repeat("x", 20)} {
        name, err := parseUsername(input)
        if err != nil {
            fmt.Printf("%q -> error: %v [%s]\n", input, err, classify(err))
            continue
        }
        fmt.Printf("%q -> ok %s\n", input, name)
    }

    // A type switch matches the outer type only. After wrapping, use errors.As(Type).
    wrapped := fmt.Errorf("signup: %w", &BadCharError{Char: '!'})
    fmt.Println("switch sees:", classify(wrapped))
    if e, ok := errors.AsType[*BadCharError](wrapped); ok {
        fmt.Printf("AsType sees: bad char %q\n", e.Char)
    }
}

In practice: document which errors a function can return, wrap them with %w so errors.As still finds them, and prefer errors.As over a raw type switch, since a type switch only sees the outermost type. A sealed interface (an interface with an unexported method) is the closest Go gets to a closed union, but linters, not the compiler, check exhaustiveness.

A type switch on a wrapped error matches only the wrapper (here *fmt.wrapError); this is the most common reason a typed-error switch "stops working".

The exhaustive linter (in golangci-lint) checks switches over enum-like constants, and gochecksumtype checks sealed interfaces; neither is part of go vet.

Crash on a bug (panic): uncaught exceptions, panic/recover, panic!, std::terminate

Go

panic stops normal execution, runs deferred calls up the goroutine's stack and, if nothing recovers, crashes the whole program with a stack trace and exit status 2. recover, called directly inside a deferred function, stops the panic and returns its value. Runtime faults (nil map writes, out-of-range indexes, nil pointer dereferences) panic with a runtime.Error. A panic is never caught by another goroutine: if a goroutine panics without recovering, the entire process dies.

Complete program

Complete program.

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

import (
    "errors"
    "fmt"
    "runtime"
    "sync"
)

// runJob is a goroutine boundary: the one place that turns a panic into an error.
// A panic that escapes any goroutine crashes the whole program, not just that goroutine.
func runJob(id int, job func() int) (result int, err error) {
    defer func() {
        switch r := recover().(type) {
        case nil:
        case error: // runtime faults panic with a runtime.Error
            err = fmt.Errorf("job %d panicked: %w", id, r)
        default:
            err = fmt.Errorf("job %d panicked: %v", id, r)
        }
    }()
    return job(), nil
}

func main() {
    jobs := []func() int{
        func() int { return 42 },
        func() int { var xs []int; return xs[3] }, // a bug: index out of range
        func() int { panic("unreachable state") },
    }

    var wg sync.WaitGroup
    results := make([]error, len(jobs))
    for i, job := range jobs {
        wg.Go(func() { // Go 1.25+: Add, go and Done in one call
            v, err := runJob(i, job)
            if err == nil {
                fmt.Printf("job %d returned %d\n", i, v)
            }
            results[i] = err
        })
    }
    wg.Wait()

    for _, err := range results {
        if err == nil {
            continue
        }
        fmt.Println(err)
        // Because runJob wrapped the panic value with %w, errors.As can detect it.
        var re runtime.Error
        fmt.Println("  runtime error:", errors.As(err, &re))
    }
}

In practice: return errors for anything expected. Panic only on programmer errors and impossible states. Recover only at goroutine or request boundaries (a worker pool, an HTTP handler; net/http already recovers per request) and turn the panic into an error or a 500 there; never use panic and recover as a try/catch for ordinary control flow.

recover only works in a function deferred by the panicking goroutine, and only when called directly by that deferred function, not from a helper it calls.

os.Exit and log.Fatal end the program without running deferred calls; prefer returning from main with a status after cleanup.

sync.WaitGroup.Go needs Go 1.25 or later. Some fatal runtime errors (concurrent map writes, out of memory, deadlock) cannot be recovered at all.

Collect several errors: AggregateError, errors.Join, partition, a vector of errors

Go

errors.Join(errs...) (Go 1.20) combines several errors into one. It drops nil entries and returns nil if all are nil, so you can append to a slice and join at the end. The joined error prints each message on its own line, and errors.Is and errors.As search every member. The result implements Unwrap() []error for code that needs to list the parts; errors.Unwrap does not see them.

Complete program

Complete program.

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

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

var ErrRequired = errors.New("required")

type FieldError struct {
    Field string
    Err   error
}

func (e *FieldError) Error() string { return e.Field + ": " + e.Err.Error() }
func (e *FieldError) Unwrap() error { return e.Err }

// validate checks every field and joins all failures into one error.
func validate(email, age, country string) error {
    var errs []error
    if email == "" {
        errs = append(errs, &FieldError{"email", ErrRequired})
    } else if !strings.Contains(email, "@") {
        errs = append(errs, &FieldError{"email", errors.New("must contain @")})
    }
    if n, err := strconv.Atoi(age); err != nil {
        errs = append(errs, &FieldError{"age", err})
    } else if n < 13 {
        errs = append(errs, &FieldError{"age", errors.New("must be 13 or older")})
    }
    if country == "" {
        errs = append(errs, &FieldError{"country", ErrRequired})
    }
    return errors.Join(errs...) // nil when errs is empty
}

func main() {
    err := validate("", "nine", "")
    // The joined message puts each error on its own line.
    fmt.Println(err)

    // errors.Is and errors.As look inside every joined error.
    fmt.Println("some field missing:", errors.Is(err, ErrRequired))
    var numErr *strconv.NumError
    fmt.Println("has a number error:", errors.As(err, &numErr))

    // To list the parts, use the Unwrap() []error method that Join's result has.
    if joined, ok := err.(interface{ Unwrap() []error }); ok {
        for _, e := range joined.Unwrap() {
            if fe, ok := errors.AsType[*FieldError](e); ok {
                fmt.Println("  field:", fe.Field)
            }
        }
    }

    fmt.Println("valid form error is nil:", validate("ada@example.com", "36", "GB") == nil)
}

In practice: validate every field, append each failure, and return errors.Join(errs...). For concurrent work, errgroup.WithContext (golang.org/x/sync/errgroup) returns the first error and cancels the shared context; collect per-task errors in a slice indexed by task when you need all of them.

The newline-separated text of a joined error suits logs but not single-line output; format the parts yourself when you need a list.

Before Go 1.20 people used hashicorp/go-multierror or uber-go/multierr; errors.Join replaces them in new code.

Decide where to handle an error: translate at boundaries, log once, retry with backoff

Go

The Go convention of returning errors makes the boundaries explicit: each layer either returns the error (wrapped with context) or handles it. The storage layer returns driver errors; the service layer translates the ones callers act on into exported sentinels or types (ErrEmailTaken), wrapping the domain error with %w and formatting the driver error with %v, so the handler can test for the domain error and the log still shows the driver detail; the handler maps errors to status codes and user messages and is the only place that logs. Retry loops live next to the failing call, test for transient errors with errors.Is, back off between attempts and stop when the context is done; ctx.Err() then returns context.Canceled or context.DeadlineExceeded, which the handler detects with errors.Is anywhere in the chain.

Complete program

Complete program.

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

import (
    "context"
    "errors"
    "fmt"
    "math/rand/v2"
    "os"
    "time"
)

// --- storage layer: driver-level errors --------------------------------------
var (
    errConnReset       = errors.New("db: connection reset")
    errUniqueViolation = errors.New("db: duplicate key users_email_key")
)

var calls int

func insertUser(email string) (int, error) {
    calls++
    if calls == 1 || email == "down@example.com" {
        return 0, errConnReset
    }
    if email == "ada@example.com" {
        return 0, errUniqueViolation
    }
    return 42, nil
}

// --- service layer: domain errors that callers are allowed to depend on -----
var ErrEmailTaken = errors.New("email already registered")

// withRetry retries transient errors with capped exponential backoff and full
// jitter (a random wait in [0, backoff)), and stops as soon as ctx is done.
func withRetry(ctx context.Context, attempts int, fn func() (int, error)) (int, error) {
    backoff := 10 * time.Millisecond
    for i := 1; ; i++ {
        if err := ctx.Err(); err != nil {
            return 0, err // context.Canceled or context.DeadlineExceeded
        }
        id, err := fn()
        if err == nil || !errors.Is(err, errConnReset) {
            return id, err // success or a permanent failure: stop now
        }
        if i == attempts {
            return 0, fmt.Errorf("after %d attempts: %w", attempts, err)
        }
        select {
        case <-ctx.Done():
            return 0, ctx.Err()
        case <-time.After(rand.N(backoff)):
        }
        backoff = min(2*backoff, 200*time.Millisecond)
    }
}

func RegisterUser(ctx context.Context, email string) (int, error) {
    id, err := withRetry(ctx, 3, func() (int, error) { return insertUser(email) })
    switch {
    case errors.Is(err, errUniqueViolation):
        // Translate: %w exposes the domain error; %v keeps the driver text for logs only.
        return 0, fmt.Errorf("register %s: %w (%v)", email, ErrEmailTaken, err)
    case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
        return 0, fmt.Errorf("register %s: %w", email, err) // standard errors: safe to expose
    case err != nil:
        return 0, fmt.Errorf("register %s: %v", email, err) // driver errors stay out of the API
    }
    return id, nil
}

// --- handler: decides status, user message and whether to log ---------------
func handleSignup(ctx context.Context, email string) (int, string) {
    id, err := RegisterUser(ctx, email)
    switch {
    case err == nil:
        return 201, fmt.Sprintf("user %d created", id)
    case errors.Is(err, ErrEmailTaken):
        return 409, "That email is already registered." // expected outcome: no log
    case errors.Is(err, context.DeadlineExceeded):
        return 504, "The request timed out. Please try again."
    case errors.Is(err, context.Canceled):
        return 499, "" // the client went away: nobody reads the response
    default:
        fmt.Fprintf(os.Stderr, "[req-7f3a] signup failed: %v\n", err) // log once, here
        return 500, "Something went wrong (reference req-7f3a)."
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    fmt.Println(handleSignup(ctx, "grace@example.com")) // first attempt hits the transient error
    fmt.Println(handleSignup(ctx, "ada@example.com"))
    fmt.Println(handleSignup(ctx, "down@example.com")) // transient every time: gives up after 3

    expired, cancelExpired := context.WithDeadline(context.Background(), time.Now())
    defer cancelExpired()
    fmt.Println(handleSignup(expired, "grace@example.com")) // deadline already passed
}

In practice: handle an error once. Either log it or return it, not both. Do not let driver types (pgconn.PgError, *url.Error) leak into package APIs that callers branch on; translate them. Keep user messages generic and put the wrapped chain in the log.

Wrapping the driver error with %w would expose it to errors.Is and errors.As in callers, making it part of the API. %v keeps its text for the log only.

rand.N (math/rand/v2, Go 1.22) works with time.Duration directly. Check ctx.Err() before each attempt as well as during the wait, so an expired deadline stops the loop without another call.

context.Canceled usually means the client went away, so there is no one to answer; context.DeadlineExceeded is a timeout worth a 504 and a metric.