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

Rust

&T borrows shared access; &mut T borrows exclusive access for mutation. Rust checks lifetimes/aliasing for safe references. Borrowing does not transfer ownership of the referred-to value.

Fragment

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

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn increment(value: &mut i32) {
    *value += 1;
}

let mut count = 2;
increment(&mut count);

Recognize owning and shared handles

Rust

Box<T> uniquely owns an allocation; Rc<T> shares ownership on one thread; Arc<T> supports shared ownership across threads when its type permits it. Shared ownership alone does not grant mutable access; RefCell adds runtime borrow checking for single-threaded use.

Fragment

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

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::rc::Rc;

let owned = Box::new(24);
let shared = Rc::new(String::from("north"));
let another = Rc::clone(&shared);

Read lifetime-related notation

Rust

A lifetime annotation relates borrows; it does not extend storage lifetime. Here the returned string slice borrows from the input. Many simple signatures can elide the annotation. A string literal can have a static lifetime.

Fragment

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

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn same<'a>(text: &'a str) -> &'a str {
    text
}

let owned = String::from("north");
let view = same(&owned);

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

Rust

Beyond recognizing a move (the copying entry), this covers when Rust moves, copies or clones a value and how to choose. Every value has one owner. Assignment and passing by value move it by default: the bytes are copied and the old binding becomes unusable, which the compiler enforces (error E0382, use of moved value). Types that implement Copy (integers, floats, bool, char, shared references, and tuples, arrays and structs made only of Copy types that derive it) are duplicated instead, and both bindings stay valid. Clone is the explicit, possibly expensive, copy: .clone() on a String or Vec allocates.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Copy: duplicated bit for bit on assignment; the original stays usable.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Stop {
    minutes: u32,
}

// Not Copy (it owns a String and a Vec): assignment and by-value calls move it.
#[derive(Debug, Clone)]
struct Route {
    id: String,
    stops: Vec<Stop>,
}

fn total_minutes(route: Route) -> u32 {
    route.stops.iter().map(|s| s.minutes).sum()
} // `route` is dropped here: this function owned it

fn stop_count(route: &Route) -> usize {
    route.stops.len() // borrowing leaves ownership with the caller
}

fn main() {
    let a = Stop { minutes: 0 };
    let mut b = a; // copy
    b.minutes = 7;
    assert_eq!((a.minutes, b.minutes), (0, 7));

    let route = Route { id: String::from("R1"), stops: vec![a, b] };
    let moved = route; // move: `route` is no longer usable
    // println!("{}", route.id);
    // error[E0382]: borrow of moved value: `route`
    //   value borrowed here after move

    // clone() is an explicit, possibly expensive, deep copy.
    let mut copy = moved.clone();
    copy.id.push_str("-copy");
    copy.stops.push(Stop { minutes: 12 });
    assert_eq!(moved.stops.len(), 2);

    println!("{} has {} stops", moved.id, stop_count(&moved)); // borrow: still ours
    let total = total_minutes(copy); // move into the call
    // copy.stops.len(); // error[E0382]: borrow of moved value: `copy`
    println!("{} minutes; original still {:?}", total, moved);
}

In practice: borrow (&T or &mut T) when a function only needs to look or change, take ownership (T) when it keeps or consumes the value, and call clone() only where you really need a second owner. Derive Copy only for small plain data.

A type cannot be Copy if it implements Drop or owns heap data (String, Vec, Box).

A move is a shallow byte copy that the compiler may elide; it never runs user code, unlike a C++ move constructor.

Moving out of a field of a borrowed struct is not allowed; use std::mem::take, std::mem::replace or Option::take.

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

Rust

Beyond recognizing handles (the ownership entry), this says which owning pointer to pick (Box, Rc, Arc or Weak) and why. A plain value or Box<T> has exactly one owner and is freed when that owner is dropped. Box puts the value on the heap: use it for recursive types, trait objects (Box<dyn Trait>) and large values you want to move cheaply. Rc<T> counts owners on one thread; Rc::clone bumps the count, and the value is freed when the last Rc goes. Arc<T> is the same with an atomic count, so it is Send and Sync when T is. Weak<T> (from Rc::downgrade or Arc::downgrade) observes without owning; upgrade() returns None once the value is gone. Rc and Arc give shared, read-only access; mutation needs RefCell, Mutex or an atomic inside.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::thread;

// Box: one owner, value on the heap. Needed for recursive types and trait objects.
enum Expr {
    Num(i64),
    Add(Box<Expr>, Box<Expr>),
}

fn eval(e: &Expr) -> i64 {
    match e {
        Expr::Num(n) => *n,
        Expr::Add(a, b) => eval(a) + eval(b),
    }
}

// Rc for shared ownership on one thread; Weak for the back edge so the cycle can be freed.
struct Team {
    name: String,
    members: RefCell<Vec<Rc<Member>>>,
}
struct Member {
    name: String,
    team: Weak<Team>,
}

fn main() {
    let expr = Expr::Add(Box::new(Expr::Num(2)), Box::new(Expr::Num(40)));
    assert_eq!(eval(&expr), 42);

    let team = Rc::new(Team { name: "core".into(), members: RefCell::new(Vec::new()) });
    let ada = Rc::new(Member { name: "ada".into(), team: Rc::downgrade(&team) });
    team.members.borrow_mut().push(Rc::clone(&ada)); // clone bumps the count, no deep copy
    assert_eq!(Rc::strong_count(&ada), 2);
    assert_eq!((Rc::strong_count(&team), Rc::weak_count(&team)), (1, 1));

    let team_name = ada.team.upgrade().map(|t| t.name.clone());
    println!("{} is on {:?}", ada.name, team_name); // ada is on Some("core")
    println!("{} has {} member(s)", team.name, team.members.borrow().len());
    drop(team); // the only strong owner is gone, so the Team is freed
    assert!(ada.team.upgrade().is_none());

    // Arc: atomic reference count, so clones can move to other threads.
    let prices = Arc::new(vec![120, 340, 75]);
    let handles: Vec<_> = (0..3)
        .map(|i| {
            let prices = Arc::clone(&prices);
            thread::spawn(move || prices[i] * 2)
        })
        .collect();
    let doubled: Vec<i32> = handles.into_iter().map(|h| h.join().unwrap()).collect();
    println!("{:?} (owners now {})", doubled, Arc::strong_count(&prices));
}

In practice: start with plain ownership and borrows. Use Box when the type needs indirection, Rc for single-threaded graphs or shared immutable data, Arc to share across threads, and Weak for back edges (child to parent) so cycles do not leak.

Two Rc values that point at each other never reach a count of zero and leak; safe Rust permits this. Make one direction Weak.

Write Rc::clone(&x) rather than x.clone() so a reader can see it is a count bump, not a deep copy.

Rc is not Send: moving one into thread::spawn fails with E0277 (`Rc<i32>` cannot be sent between threads safely). Use Arc for values shared across threads.

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

Rust

Beyond borrowing (the references entry), this covers mutation through a shared handle: Cell, RefCell and Arc<Mutex<T>>. The borrow rules forbid shared mutation by default: at any moment a value has either any number of &T borrows or exactly one &mut T, checked at compile time (error E0502 or E0499 otherwise). When a design needs mutation through a shared handle, interior mutability moves the check: Cell<T> replaces the value with no borrows at all (set and replace work for any T; get needs T: Copy and take needs T: Default), RefCell<T> tracks borrows at run time and panics on a conflict (try_borrow_mut returns an error instead), and both are single-threaded. Across threads the pattern is Arc<Mutex<T>> or Arc<RwLock<T>>, or atomics for single numbers; the compiler requires Send and Sync, so data races do not compile.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::cell::{Cell, RefCell};
use std::sync::{Arc, Mutex};
use std::thread;

struct Ledger {
    entries: Vec<i64>,
    reads: Cell<u32>, // changed through &self, with no borrow
}

impl Ledger {
    fn total(&self) -> i64 {
        self.reads.set(self.reads.get() + 1);
        self.entries.iter().sum()
    }
}

fn main() {
    // &mut is exclusive: while it is live, no other reference to the value may be used.
    let mut ledger = Ledger { entries: vec![10, -3], reads: Cell::new(0) };
    let writer = &mut ledger.entries;
    writer.push(5);
    // let reader = &ledger.entries;
    // writer.push(1);
    // error[E0502]: cannot borrow `ledger.entries` as immutable because it is also borrowed as mutable
    assert_eq!(ledger.total(), 12);
    assert_eq!(ledger.reads.get(), 1);

    // RefCell moves the borrow check to run time, for shared (Rc) single-threaded data.
    let log = RefCell::new(Vec::<String>::new());
    log.borrow_mut().push("opened".to_string());
    {
        let reading = log.borrow();
        // A second mutable borrow now would panic; try_borrow_mut reports it instead.
        assert!(log.try_borrow_mut().is_err());
        println!("{} entry while reading", reading.len());
    }
    log.borrow_mut().push("closed".to_string()); // the shared borrow has ended
    println!("{:?}", log.borrow());

    // Across threads: Arc shares ownership, Mutex grants one writer at a time.
    let balance = Arc::new(Mutex::new(0_i64));
    let workers: Vec<_> = (0..4)
        .map(|_| {
            let balance = Arc::clone(&balance);
            thread::spawn(move || {
                for _ in 0..1000 {
                    *balance.lock().unwrap() += 1; // guard is dropped at the end of the statement
                }
            })
        })
        .collect();
    for w in workers {
        w.join().unwrap();
    }
    println!("balance {}", *balance.lock().unwrap()); // balance 4000
}

In practice: restructure first (shorter borrows, pass &mut down, return values), and use RefCell or Mutex only where ownership is truly shared. Keep lock guards short-lived and never hold a RefCell borrow across a call that might borrow again.

lock() returns Err if another thread panicked while holding the lock (poisoning); unwrap is common when that should abort.

A RefCell double borrow is a panic, not a compile error, so it shows up only on the path that triggers it.

parking_lot (0.13) offers smaller, non-poisoning Mutex and RwLock types.

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

Rust

Beyond reading lifetime annotations (the lifetime-notes entry), this shows the borrow errors that stop a reference from dangling and the usual fix for each. In safe Rust a reference can never outlive what it points to: the borrow checker rejects the program instead. The usual errors are E0515 (returning a reference to a local), E0597 (a value does not live long enough for a borrow that is still used) and E0502 (mutating a collection while a reference into it is live, for example push while holding &v[0], since push may reallocate). These are design feedback, not something to silence.

Complete program

Complete program. The commented blocks are rejected by the compiler with the error shown.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Each commented block is rejected at compile time; the compiled code shows the fix.

// fn longest_word(text: &str) -> &str {
//   let upper = text.to_uppercase();
//   upper.split(' ').next().unwrap()
// }
// error[E0515]: cannot return value referencing local variable `upper`
//   returns a value referencing data owned by the current function

// Fix 1: return an owned value.
fn first_word_upper(text: &str) -> String {
    text.split(' ').next().unwrap_or("").to_uppercase()
}

// Fix 2: return a borrow tied to the input, which the caller keeps alive.
fn first_word(text: &str) -> &str {
    text.split(' ').next().unwrap_or("")
}

fn main() {
    let mut queue = vec![String::from("build"), String::from("test")];

    // let first = &queue[0];
    // queue.push(String::from("deploy")); // push may reallocate and move the elements
    // println!("{first}");
    // error[E0502]: cannot borrow `queue` as mutable because it is also borrowed as immutable

    // Fix: finish with the borrow first, keep an index, or clone what you need.
    let first = queue[0].clone();
    queue.push(String::from("deploy"));
    let idx = 1;
    println!("{first} {} {}", queue[idx], queue.len()); // build test 3

    // let view: &str;
    // {
    //   let line = String::from("ship it");
    //   view = first_word(&line);
    // }
    // println!("{view}");
    // error[E0597]: `line` does not live long enough

    let line = String::from("ship it");
    let view = first_word(&line); // line outlives view
    println!("{view} {}", first_word_upper(&line)); // ship SHIP
}

In practice: return owned values (String, Vec) from functions that create data, and return a borrow only when it comes from an input. Hold indexes or keys instead of references across mutations, end a borrow before mutating, or clone the small part you need. When lifetimes get tangled across a struct, the struct usually should own its data.

unsafe code with raw pointers can dangle; Miri (cargo +nightly miri test) detects use-after-free in tests.

rustc --explain E0597 prints the long explanation for any error code.

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

Rust

Beyond recognizing Drop (the cleanup entry), this covers drop order, moving the duty to drop and releasing early. Ownership decides release: when the owner of a value goes out of scope, its Drop implementation runs, then its fields drop. The order is fixed: local variables drop in reverse order of declaration, struct fields and tuple or array elements in declaration order. Moving a value moves the duty to drop it, so a function that takes T by value drops it at its end unless it passes it on. std::mem::drop(x) releases early (it simply takes ownership), and Option::take or mem::replace move a value out of a place you only borrow.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::mem;
use std::sync::Mutex;

static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());

struct Handle(&'static str);

impl Drop for Handle {
    fn drop(&mut self) {
        LOG.lock().unwrap().push(format!("drop {}", self.0));
    }
}

struct Session {
    conn: Handle, // fields drop in declaration order: conn, then cache
    cache: Handle,
}

// Taking a value by move transfers the duty to drop it.
fn archive(h: Handle) {
    LOG.lock().unwrap().push(format!("archive {}", h.0));
} // h dropped here

fn main() {
    {
        let _a = Handle("a");
        let _b = Handle("b");
        let s = Session { conn: Handle("conn"), cache: Handle("cache") };
        LOG.lock().unwrap().push(format!("using {}+{}", s.conn.0, s.cache.0));
    } // locals drop in reverse order: s (conn, cache), then _b, then _a

    let early = Handle("early");
    mem::drop(early); // release now, e.g. a lock guard before slow work

    let moved = Handle("moved");
    archive(moved); // dropped inside archive, not at the end of main

    let mut slot = Some(Handle("slot"));
    let taken = slot.take(); // move out of a field or Option, leaving None
    drop(taken);
    assert!(slot.is_none());

    let _ = Handle("ignored"); // a temporary bound to _ drops at once; `let _name =` would keep it

    let log = LOG.lock().unwrap();
    assert_eq!(
        *log,
        [
            "using conn+cache", "drop conn", "drop cache", "drop b", "drop a", "drop early",
            "archive moved", "drop moved", "drop slot", "drop ignored"
        ]
    );
    println!("{}", log.join(", "));
}

In practice: wrap each resource in a type whose Drop releases it, and let scopes do the rest. Drop lock guards and files early with drop() before slow work. Watch the underscore patterns: let _ = Handle::new() drops the new temporary at once, let _ = existing neither moves nor drops existing, and let _guard = value keeps the value until the end of the scope.

Drop cannot return an error. Types like BufWriter flush on drop and ignore failures; call flush() or an explicit close method where errors matter.

mem::forget and Rc cycles skip Drop without unsafe, so Drop is not guaranteed to run; process::exit also skips it.

Temporaries in a match or if let scrutinee live until the end of the statement; Edition 2024 shortened this for if let and tail expressions.