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.

References & ownership

Borrow access or pass an address

Go

&value takes an address; *pointer accesses the pointed-to value. A pointer parameter can modify the caller’s object. Dereferencing nil panics. Passing an ordinary scalar instead copies its value.

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 increment(value *int) {
  *value += 1
}

count := 2
increment(&count)

Recognize owning and shared handles

Go

Go manages ordinary memory with garbage collection. Copying a pointer shares access to the object; it does not give Rust-style exclusive ownership. Files and other resources still need explicit lifecycle handling.

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+
first := &struct{ Name string }{Name: "north"}
second := first

second.Name = "west" // same object

Read lifetime-related notation

Go

Returning a pointer to a local Go variable is allowed; the implementation keeps its storage alive as needed. Lexical scope and the storage lifetime are different. This is not a license to return a pointer to a dead local in C++.

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 newCount() *int {
  value := 24
  return &value
}

count := newCount()

Copy or move a value: reference semantics, value copies, move, Copy/Clone, std::move

Go

Beyond spotting shared storage (the copying entry), this shows which parts of a Go value a copy shares and how to make an independent copy. Go copies on assignment and on every call: structs and arrays are values, so the copy is independent field by field. Some types are small headers over shared storage, though: a slice is (pointer, len, cap), and maps, channels, pointers, functions and interfaces holding pointers all refer to data that a copy shares. A struct copy is therefore shallow. There is no move and no copy constructor; slices.Clone and maps.Clone (Go 1.21+) copy one level.

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 Stop struct {
    Name    string
    Minutes int
}

type Route struct {
    ID    string
    Stops []Stop          // slice header: copying it shares the backing array
    Tags  map[string]bool // map value is a reference to shared storage
    Depot *Stop           // pointer: copying it shares the pointee
}

func delay(s Stop, by int) Stop    { s.Minutes += by; return s } // works on a copy
func delayInPlace(s *Stop, by int) { s.Minutes += by }           // works on the caller's value

func main() {
    // Structs and arrays are values: assignment copies every field or element.
    a := Stop{"Depot", 0}
    b := a
    b.Minutes = 7
    grid := [3]int{1, 2, 3}
    gridCopy := grid
    gridCopy[0] = 9
    fmt.Println(a.Minutes, b.Minutes, grid[0], gridCopy[0]) // 0 7 1 9

    // A struct copy is shallow: the slice, map and pointer fields still share storage.
    r := Route{ID: "R1", Stops: []Stop{a}, Tags: map[string]bool{}, Depot: &Stop{"Yard", 0}}
    c := r
    c.ID = "R2"
    c.Stops[0].Minutes = 5
    c.Tags["express"] = true
    c.Depot.Minutes = 9
    fmt.Println(r.ID, r.Stops[0].Minutes, r.Tags["express"], r.Depot.Minutes) // R1 5 true 9

    // An independent copy clones each reference-like field explicitly.
    d := r
    d.Stops = slices.Clone(r.Stops)
    d.Tags = maps.Clone(r.Tags)
    depot := *r.Depot
    d.Depot = &depot
    d.Stops[0].Minutes = 100
    d.Depot.Minutes = 100
    fmt.Println(r.Stops[0].Minutes, r.Depot.Minutes) // 5 9

    // Passing a struct copies it; pass a pointer when the callee must change the original.
    later := delay(a, 3)
    delayInPlace(&a, 1)
    fmt.Println(a.Minutes, later.Minutes) // 1 3
}

In practice: pass small structs by value and pass a pointer when the callee must change the caller's value or the struct is large. When a copy must be independent, clone each slice, map and pointer field explicitly.

A struct containing a sync.Mutex (or anything with a noCopy marker) must not be copied after first use; go vet reports this as copylocks.

slices.Clone and maps.Clone are shallow: a slice of pointers or a map of slices still shares the inner values.

Choose an owning pointer: GC references, Box/Rc/Arc/Weak, unique_ptr/shared_ptr/weak_ptr

Go

Beyond recognizing handles (the ownership entry), this covers what Go uses instead of smart pointers: shared *T, escape analysis and weak.Pointer. Go is garbage collected and has no smart pointers. A *T is a plain shared pointer: copying it shares the object, nothing counts owners, and the collector frees the object once nothing reachable points to it, cycles included. Returning &local is safe because escape analysis moves the value to the heap. Go 1.24 added weak.Pointer (package weak) for references that do not keep an object alive, and runtime.AddCleanup for running a function after an object becomes unreachable.

Complete program

Complete program (Go 1.24+ for package weak).

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

import (
    "fmt"
    "runtime"
    "weak"
)

type Node struct {
    Name     string
    Parent   *Node // a back pointer is fine: the collector handles cycles
    Children []*Node
}

// Returning the address of a local is safe; the compiler moves it to the heap.
func newNode(name string, parent *Node) *Node {
    n := Node{Name: name, Parent: parent}
    if parent != nil {
        parent.Children = append(parent.Children, &n)
    }
    return &n
}

func main() {
    root := newNode("root", nil)
    leaf := newNode("leaf", root)
    fmt.Println(leaf.Parent.Name, len(root.Children)) // root 1

    // Copying a pointer shares the object; there is no owner and no reference count.
    alias := leaf
    alias.Name = "renamed"
    fmt.Println(root.Children[0].Name) // renamed

    // weak.Pointer (Go 1.24+) observes without keeping the object alive, e.g. for caches.
    draft := &Node{Name: "draft"}
    w := weak.Make(draft)
    fmt.Println("alive:", w.Value() != nil, draft.Name) // alive: true draft
    // draft is not used after this line, so nothing strong refers to that Node any more.
    runtime.GC()
    fmt.Println("collected:", w.Value() == nil) // usually true after a GC, but not guaranteed
}

In practice: use *T when callers must share or mutate one value, values otherwise. Express ownership of non-memory resources by convention (the code that opens something closes it). Use weak.Pointer only for canonicalization maps and caches.

Value returns nil only after a collection has freed the object, and nothing promises when that happens; a program must work either way.

runtime.SetFinalizer is the older mechanism; prefer runtime.AddCleanup (Go 1.24+), which handles cycles and multiple cleanups.

A pointer into a slice element keeps the whole backing array alive.

Mutate shared state safely: aliasing, pointer receivers, &mut, RefCell/Mutex, const

Go

Beyond passing pointers (the references entry), this covers how receivers, range copies and append decide who sees a write. Go lets any number of pointers and slices share data and lets all of them write. Method receivers decide what a method sees: a value receiver works on a copy, a pointer receiver on the original (Go takes the address automatically for addressable values). The range loop also yields copies of elements. The common surprise is append: a sub-slice shares its parent's backing array, so appending within spare capacity overwrites the parent's elements, while appending past capacity silently allocates a new array. Concurrent access to shared data from goroutines is a data race unless guarded.

Complete program

Complete program (Go 1.25+ for sync.WaitGroup.Go).

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

import (
    "fmt"
    "slices"
    "sync"
)

type Account struct {
    Balance int
}

func (a Account) DepositOnCopy(n int) { a.Balance += n } // value receiver: changes a copy
func (a *Account) Deposit(n int)      { a.Balance += n } // pointer receiver: changes the original

func main() {
    acct := Account{}
    acct.DepositOnCopy(10)
    acct.Deposit(5)           // Go takes &acct automatically because acct is addressable
    fmt.Println(acct.Balance) // 5

    // range yields copies of the elements; write through the index (or use []*Account).
    accounts := []Account{{1}, {2}}
    for _, a := range accounts {
        a.Balance += 100 // lost
    }
    for i := range accounts {
        accounts[i].Balance += 100
    }
    fmt.Println(accounts) // [{101} {102}]

    // append surprise: a sub-slice shares the backing array while it has spare capacity.
    base := make([]int, 3, 4) // len 3, cap 4
    copy(base, []int{1, 2, 3})
    head := base[:2]
    head = append(head, 99) // writes into base[2]
    fmt.Println(base, head) // [1 2 99] [1 2 99]

    // Fixes: cap the sub-slice with a full slice expression, or clone it.
    safe := base[:2:2] // cap 2, so append must allocate a new array
    safe = append(safe, -1)
    owned := slices.Clone(base[:2])
    owned[0] = 0
    fmt.Println(base, safe, owned) // [1 2 99] [1 2 -1] [0 2]

    // Across goroutines, shared state needs a lock (or a single owner fed by a channel).
    var mu sync.Mutex
    var wg sync.WaitGroup
    total := Account{}
    for range 100 {
        wg.Go(func() { // Go 1.25+: Add, go and Done in one call
            mu.Lock()
            defer mu.Unlock()
            total.Deposit(1)
        })
    }
    wg.Wait()
    fmt.Println(total.Balance) // 100
}

In practice: use pointer receivers for types with mutable state, and keep all of a type's methods on the same receiver kind. Write through the index in loops. Cap sub-slices you hand out with a full slice expression s[lo:hi:hi], or clone them. Guard state shared by goroutines with sync.Mutex, or give it to one goroutine and send it messages.

Run tests with go test -race; the race detector finds unsynchronized shared writes at run time.

A function that appends to a slice parameter must return the new slice; the caller's header still has the old length.

sync.WaitGroup.Go needs Go 1.25+; on older versions call wg.Add(1), go func() { defer wg.Done() ... }().

Avoid dangling references: stale handles, loop captures, borrow errors, use-after-free

Go

Beyond reading lifetime notation (the lifetime-notes entry), this covers the two staleness bugs Go still has: captured loop variables and pointers into a grown slice. Go pointers cannot dangle in the use-after-free sense: the collector keeps any reachable object alive, and returning &local is fine. Two staleness bugs remain. Before Go 1.22 a for loop had one variable for all iterations, so closures and goroutines that captured it all saw the last value; since Go 1.22 (when go.mod says go 1.22 or later) each iteration has its own variable. And a pointer into a slice element (&s[i]) refers to the backing array at that moment: after append reallocates, the pointer still works but updates the old array, which the slice no longer uses.

Complete program

Complete program (Go 1.22+ for per-iteration loop variables and range over int).

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

import "fmt"

type Job struct{ ID int }

func main() {
    // The collector keeps anything reachable alive, so pointers never dangle in the
    // use-after-free sense. Escaping a local is fine:
    newJob := func(id int) *Job { j := Job{id}; return &j }
    fmt.Println(newJob(1).ID) // 1

    // Go 1.22+: each loop iteration has its own variable, so closures see 0 1 2.
    // Before 1.22 (or with go < 1.22 in go.mod) they all saw the final value.
    var funcs []func() int
    for i := range 3 {
        funcs = append(funcs, func() int { return i })
    }
    for _, f := range funcs {
        fmt.Print(f(), " ")
    }
    fmt.Println()

    // Stale pointer after append: when append reallocates, &jobs[0] still points to
    // the OLD backing array. It stays valid memory, but updates no longer meet.
    jobs := make([]Job, 1, 1) // full: the next append must allocate
    first := &jobs[0]
    jobs = append(jobs, Job{2})
    first.ID = 99
    fmt.Println(jobs[0].ID, first.ID) // 0 99

    // Fix: keep an index (or a slice of pointers) instead of a pointer into the slice.
    idx := 0
    jobs = append(jobs, Job{3})
    jobs[idx].ID = 42
    fmt.Println(jobs[idx].ID, len(jobs)) // 42 3

    // Maps never let you hold an element's address: &m[k] does not compile,
    // because the map may move entries as it grows.
}

In practice: keep indexes or a []*T instead of pointers into a []T that may grow. Check the go line in go.mod before relying on per-iteration loop variables. Run the race detector on code that shares slices between goroutines.

The loop change applies per module: code in a module whose go.mod says go 1.21 keeps the old shared variable even on a new toolchain.

unsafe and cgo can produce real dangling pointers; C memory is not tracked by the collector.

Release resources by ownership: using and Symbol.dispose, Close conventions, Drop, RAII and deleters

Go

Beyond recognizing defer cleanup (the cleanup entry), this covers who owns a Closer, how to release a partial acquisition and how to report Close errors. Go has no destructors. Release is a convention around io.Closer: whoever receives an open resource from a constructor (os.Open, sql.Open, http.Response.Body) owns it and must call Close once, usually with defer right after the error check. A constructor that acquires several resources must close the ones it already opened if a later step fails, and a type that owns resources exposes its own Close that releases them in reverse order.

Complete program

Complete program. Creates and removes a temporary directory.

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

import (
    "errors"
    "fmt"
    "os"
    "path/filepath"
)

// Store owns two files. Convention: whoever receives an io.Closer from a constructor
// owns it and must call Close exactly once.
type Store struct {
    data, index *os.File
}

func OpenStore(dir string) (*Store, error) {
    data, err := os.Create(filepath.Join(dir, "data.log"))
    if err != nil {
        return nil, err
    }
    index, err := os.Create(filepath.Join(dir, "missing", "index.log"))
    if err != nil {
        data.Close() // partial failure: release what we already own before returning
        return nil, fmt.Errorf("open index: %w", err)
    }
    return &Store{data: data, index: index}, nil // ownership passes to the caller
}

// Close releases in reverse order and reports every failure.
func (s *Store) Close() error {
    return errors.Join(s.index.Close(), s.data.Close())
}

// write owns f for its whole life; for a written file, Close can report a lost write,
// so its error is returned rather than dropped by a bare `defer f.Close()`.
func write(path, text string) (err error) {
    f, err := os.Create(path)
    if err != nil {
        return err
    }
    defer func() { err = errors.Join(err, f.Close()) }()
    _, err = f.WriteString(text)
    return err
}

func main() {
    dir, err := os.MkdirTemp("", "store")
    if err != nil {
        panic(err)
    }
    defer os.RemoveAll(dir)

    if _, err := OpenStore(dir); err != nil {
        fmt.Println("not exist:", errors.Is(err, os.ErrNotExist), "- OpenStore already closed data.log")
    }

    if err := os.Mkdir(filepath.Join(dir, "missing"), 0o755); err != nil {
        panic(err)
    }
    s, err := OpenStore(dir)
    if err != nil {
        panic(err)
    }
    defer func() {
        fmt.Println("store closed, err =", s.Close())
    }()

    path := filepath.Join(dir, "note.txt")
    fmt.Println("write err =", write(path, "hello"))
    b, _ := os.ReadFile(path)
    fmt.Println(string(b))
}

In practice: document who owns each returned Closer. For files you write, check Close's error (it can report a failed flush) with a named result and errors.Join rather than a bare defer f.Close(). Collect multiple Close errors with errors.Join (Go 1.20+).

defer runs at function return, not block exit; deferring Close inside a long loop keeps every file open until the function ends. Move the body into a helper function.

Calling Close twice on an os.File returns an error; make your own Close methods safe to call twice if callers might.

runtime.AddCleanup is a safety net for forgotten Close calls, not a replacement.