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

Rust

Rust supports imperative code fully, but mutation is opt-in: a binding is immutable unless declared let mut, and the borrow checker allows either one writer or many readers at a time. That rule removes the classic risk of procedural code, shared mutable state changed from two places at once. Iterator chains are equally idiomatic; a for loop is fine when it reads better.

Complete program

Complete program.

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

struct Order {
    category: &'static str,
    cents: u32,
}

// A procedure: borrow the input, build the result with a loop and mutation.
fn totals_by_category(orders: &[Order]) -> BTreeMap<&'static str, u32> {
    let mut totals = BTreeMap::new(); // sorted keys, so output is deterministic
    for order in orders {
        *totals.entry(order.category).or_insert(0) += order.cents;
    }
    totals
}

fn main() {
    let orders = [
        Order { category: "books", cents: 1200 },
        Order { category: "games", cents: 5999 },
        Order { category: "books", cents: 850 },
        Order { category: "music", cents: 999 },
        Order { category: "games", cents: 2000 },
    ];
    let mut grand = 0;
    for (category, cents) in totals_by_category(&orders) {
        println!("{category:<6} ${}.{:02}", cents / 100, cents % 100);
        grand += cents;
    }
    println!("total  ${}.{:02}", grand / 100, grand % 100);
}

In practice: borrow inputs (&[T]) and return owned results; keep let mut to the smallest scope; use the entry API to update a map in one lookup.

HashMap iteration order is unspecified; BTreeMap keeps keys sorted, so the output is deterministic.

*entry(k).or_insert(0) += x dereferences the &mut u32 the entry returns; forgetting the * is a type error, not a silent bug.

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

Rust

A Rust struct holds data and an impl block adds methods. Privacy is per module: fields are private to the module that defines the struct unless marked pub, so code outside that module cannot build the struct with a literal and must call a constructor. By convention that is an associated function new, returning Result<Self, E> when input can be invalid. Types do part of the job too: a u64 balance cannot be negative.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
mod bank {
    pub struct Account {
        owner: String, // private: only code inside mod bank can touch it
        cents: u64,    // unsigned: a negative balance cannot be represented
    }

    impl Account {
        // The constructor validates what the types cannot express.
        pub fn new(owner: &str, opening: u64) -> Result<Self, String> {
            if owner.trim().is_empty() {
                return Err("owner must not be empty".to_string());
            }
            Ok(Self { owner: owner.to_string(), cents: opening })
        }

        pub fn owner(&self) -> &str {
            &self.owner
        }

        pub fn balance(&self) -> u64 {
            self.cents
        }

        pub fn deposit(&mut self, cents: u64) {
            self.cents += cents;
        }

        pub fn withdraw(&mut self, cents: u64) -> Result<(), String> {
            self.cents = self.cents.checked_sub(cents).ok_or("insufficient funds")?;
            Ok(())
        }
    }
}

use bank::Account;

fn main() {
    let mut account = Account::new("Ada", 5000).expect("valid account");
    account.deposit(2500);
    let big = account.withdraw(10000);
    let small = account.withdraw(3000);
    println!("{} {big:?} {small:?} {}", account.owner(), account.balance()); // Ada Err("insufficient funds") Ok(()) 4500
    println!("{:?}", Account::new(" ", 0).err());
    // account.cents = 0; // error[E0616]: field `cents` of struct `Account` is private
}

In practice: choose field types that make invalid states unrepresentable, then validate the rest in new; keep fields private and expose methods; take &self for queries and &mut self for changes.

Privacy stops at the module, not the type: everything inside mod bank can touch cents. In a one-file program, an inline mod is what keeps main out.

checked_sub returns None instead of wrapping or panicking on underflow, which turns the invariant into an ordinary error path.

A struct with only pub fields can be built by anyone with a literal, which bypasses new entirely.

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

Rust

Rust expresses polymorphism with traits and offers both dispatch strategies explicitly. Static dispatch (generics, impl Trait) compiles a separate copy per concrete type, so calls can be inlined and cost nothing extra. Dynamic dispatch (&dyn Trait, Box<dyn Trait>) uses one compiled function and calls through a vtable, which is what a list of mixed types needs. A trait must be dyn compatible (no generic methods, no Self return) to be used as dyn.

Complete program

Complete program.

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

trait Shape {
    fn name(&self) -> &str;
    fn area(&self) -> f64;
}

struct Circle { radius: f64 }
struct Rect { w: f64, h: f64 }

impl Shape for Circle {
    fn name(&self) -> &str { "circle" }
    fn area(&self) -> f64 { PI * self.radius * self.radius }
}

impl Shape for Rect {
    fn name(&self) -> &str { "rect" }
    fn area(&self) -> f64 { self.w * self.h }
}

// Static dispatch: compiled once per concrete type; calls can be inlined.
fn describe(shape: &impl Shape) -> String {
    format!("{:<6} {:.2}", shape.name(), shape.area())
}

// Dynamic dispatch: one function; each call goes through the vtable.
fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
    shapes.iter().map(|s| s.area()).sum()
}

fn main() {
    println!("{}", describe(&Circle { radius: 1.0 }));
    println!("{}", describe(&Rect { w: 2.0, h: 3.0 }));

    // A heterogeneous list needs trait objects: the element types differ in size.
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { radius: 1.0 }),
        Box::new(Rect { w: 2.0, h: 3.0 }),
        Box::new(Rect { w: 2.0, h: 2.0 }),
    ];
    println!("total  {:.2}", total_area(&shapes));
}

In practice: default to generics or impl Trait; switch to Box<dyn Trait> when you need a heterogeneous collection or want to shrink code size; prefer an enum when the set of variants is closed.

&impl Shape implies a Sized type, so a &dyn Shape cannot be passed to it; write fn f<T: Shape + ?Sized>(s: &T) to accept both.

A Box<dyn Trait> has an implicit 'static bound; storing borrowed data needs Box<dyn Trait + 'a>.

Generic code is monomorphised: many instantiations of a large generic function increase binary size.

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

Rust

Rust has no struct inheritance. Shared behaviour lives in traits: a trait can provide default method bodies that implementors inherit or override, and a supertrait bound (trait Describe: Display) requires implementors to also implement another trait. Data reuse is composition: a struct holds other structs as fields and delegates to them explicitly.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::fmt::{self, Display};

// A supertrait: every Describe type must also be Display.
trait Describe: Display {
    fn kind(&self) -> &'static str;

    // A default method: implementors get it for free and may override it.
    fn describe(&self) -> String {
        format!("{self} ({})", self.kind())
    }
}

struct Engine { hp: u32 }

// Composition: a Car has an Engine; there is no "extends".
struct Car {
    name: String,
    engine: Engine,
}

impl Display for Engine {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} hp engine", self.hp) }
}
impl Describe for Engine {
    fn kind(&self) -> &'static str { "part" }
}

impl Display for Car {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name) }
}
impl Describe for Car {
    fn kind(&self) -> &'static str { "vehicle" }
    fn describe(&self) -> String { // overrides the default and delegates to the part
        format!("{} with a {}", self.name, self.engine.describe())
    }
}

fn main() {
    let car = Car { name: "Roadster".to_string(), engine: Engine { hp: 300 } };
    let items: [&dyn Describe; 2] = [&car.engine, &car];
    for item in items {
        println!("{}", item.describe());
    }
}

In practice: put reusable behaviour in default methods built on a few required ones; compose structs and write the small forwarding methods by hand; use supertraits to state "is also a", never to emulate a class hierarchy.

A default method cannot read fields; it can only call other trait methods, which keeps implementors free to store data however they like.

Deref to an inner type looks like inheritance but is meant for smart pointers; implementing Deref for delegation is considered an anti-pattern.

Design principles: SOLID and dependency inversion with an injected interface

Rust

In Rust the SOLID ideas map onto traits: a small trait per capability (interface segregation), implementations that honour the trait's documented contract (Liskov), and dependency inversion by making the service generic over the trait, OrderService<N: Notifier>, or holding a Box<dyn Notifier>. Generics are resolved at compile time and cost nothing at runtime; a trait object allows choosing the implementation at runtime.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Interface segregation: OrderService needs exactly one capability.
trait Notifier {
    fn send(&mut self, to: &str, message: &str);
}

// Dependency inversion: generic over the abstraction; the detail is injected in new.
struct OrderService<N> {
    notifier: N,
    next_id: u32,
}

impl<N: Notifier> OrderService<N> {
    fn new(notifier: N) -> Self {
        Self { notifier, next_id: 1 }
    }

    fn place(&mut self, customer: &str, cents: u32) -> u32 {
        let id = self.next_id;
        self.next_id += 1;
        self.notifier.send(customer, &format!("order {id} confirmed: {cents} cents"));
        id
    }
}

struct ConsoleNotifier;
impl Notifier for ConsoleNotifier {
    fn send(&mut self, to: &str, message: &str) { println!("to {to}: {message}"); }
}

// A fake for tests: records messages instead of sending them.
#[derive(Default)]
struct FakeNotifier { sent: Vec<String> }
impl Notifier for FakeNotifier {
    fn send(&mut self, to: &str, message: &str) { self.sent.push(format!("{to} | {message}")); }
}

fn main() {
    let mut service = OrderService::new(FakeNotifier::default());
    let first = service.place("ada@example.com", 4200);
    let second = service.place("ada@example.com", 999);
    println!("{first} {second} {:?}", service.notifier.sent);

    let mut live = OrderService::new(ConsoleNotifier); // same policy, real detail
    live.place("bob@example.com", 1500);
}

In practice: take the dependency in new and own it in a field; prefer a generic parameter, and switch to Box<dyn Trait> when the choice is made at runtime or the type parameter spreads too far; give fakes plain fields that tests can inspect.

With send(&mut self) the service needs &mut self too; if the notifier must be shared, take &self and use interior mutability (RefCell or Mutex) inside the fake.

Put trait bounds on the impl block rather than the struct definition, so every use of the type does not have to repeat them.

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

Rust

Rust is expression-oriented (if, match and blocks all produce values), variables are immutable unless declared mut, and the borrow checker makes mutation visible in signatures: a function that takes &T cannot change it. Closures and lazy iterators give the usual functional toolkit. Purity is not tracked by the type system, though; any function can still print or touch a static.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
struct Order {
    subtotal_cents: u32,
    loyalty_years: u32,
}

// Pure: the body is one expression of the inputs, with no I/O and no shared state.
fn discount_percent(years: u32) -> u32 {
    match years {
        5.. => 15,
        2..=4 => 5,
        _ => 0,
    }
}

fn total_cents(order: &Order) -> u32 {
    order.subtotal_cents * (100 - discount_percent(order.loyalty_years)) / 100
}

fn format_cents(cents: u32) -> String {
    format!("{}.{:02}", cents / 100, cents % 100)
}

fn main() {
    // Testing a pure function needs no setup: inputs in, assert on the output.
    assert_eq!(total_cents(&Order { subtotal_cents: 10_000, loyalty_years: 5 }), 8_500);
    assert_eq!(total_cents(&Order { subtotal_cents: 10_000, loyalty_years: 0 }), 10_000);

    let orders = [
        Order { subtotal_cents: 12_000, loyalty_years: 1 },
        Order { subtotal_cents: 8_000, loyalty_years: 3 },
        Order { subtotal_cents: 20_000, loyalty_years: 6 },
    ];
    // Pure functions slot straight into iterator chains.
    let grand: u32 = orders.iter().map(total_cents).sum();

    // Imperative shell: printing stays at the edge of the program.
    for (i, order) in orders.iter().enumerate() {
        println!("order {}: {}", i + 1, format_cents(total_cents(order)));
    }
    println!("all orders: {}", format_cents(grand));
}

In practice: write the core as functions over borrowed data (&T) that return new values, and keep printing and I/O in main. Prefer match and expressions to mutable flags. Reach for &mut only where in-place updates are clearly cheaper or clearer.

Interior mutability (Cell, RefCell, Mutex) lets a function change state behind a shared &T reference, so &T alone does not prove a function is pure.

Integer overflow panics in debug builds and wraps in release builds; use checked_mul or wider types when the inputs are untrusted.

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

Rust

Bindings are immutable by default; let mut opts in. Borrowing makes sharing explicit: many &T readers or exactly one &mut T writer, never both at once, so aliasing bugs are compile errors. Struct update syntax (..old) builds a new value from an existing one, moving or copying the fields you did not list.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[derive(Debug, Clone)]
struct Account {
    id: String,
    balance: u32,
    tags: Vec<String>,
}

// Takes ownership and returns the updated value; ..account moves the other fields over.
fn credited(account: Account, amount: u32) -> Account {
    Account { balance: account.balance + amount, ..account }
}

// &mut: one writer at a time, and the caller can see exactly where mutation happens.
fn add_tag(tags: &mut Vec<String>, tag: &str) {
    tags.push(tag.to_string());
}

fn main() {
    let original = Account { id: "a1".into(), balance: 100, tags: vec!["new".into()] };
    // original.balance = 50; // error: `original` is not declared as mutable

    // clone() keeps the original; without it, original would be moved into credited().
    let updated = credited(original.clone(), 25);
    println!("{original:?}");
    println!("{updated:?}");

    // Mutation is opt-in and local.
    let mut tags = updated.tags.clone();
    add_tag(&mut tags, "vip");
    println!("{tags:?}");

    // Any number of shared & borrows can read at once.
    let (first, second) = (&original, &original);
    println!("{} {}", first.id, second.balance);
}

In practice: start every binding without mut and add it only where the compiler asks. Take &T to read, &mut T to change in place, and T by value to consume and return an updated value. Clone deliberately when you need to keep the old value.

..old moves non-Copy fields such as String and Vec out of old, so old cannot be used afterwards unless only Copy fields were taken.

Shadowing (let x = x + 1) creates a new binding; it is not mutation, and the old value is still there for anyone who borrowed it.

Cell, RefCell and Mutex allow mutation through &T; that is interior mutability, an explicit and visible opt-out.

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

Rust

Iterator adapters (map, filter, fold, take_while and many more) are higher-order functions that compile to tight loops. Functions are accepted generically (impl Fn(T) -> U or F: Fn) and returned as impl Fn, or boxed as Box<dyn Fn> when different closures must share one type. Currying and composition are not built in but are short to write with move closures.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Returning a closure: impl Fn names the behavior and hides the closure's own type.
fn multiply_by(factor: u32) -> impl Fn(u32) -> u32 {
    move |n| n * factor
}

// compose(f, g) runs f, then g.
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
    move |x| g(f(x))
}

// Taking a function as an argument.
fn apply_twice(f: impl Fn(u32) -> u32, x: u32) -> u32 {
    f(f(x))
}

fn main() {
    let prices = [12, 40, 7, 25];
    // Iterator adapters are higher-order functions; nothing runs until sum() pulls values.
    let total: u32 = prices.iter().copied().filter(|&p| p >= 10).map(multiply_by(3)).sum();
    println!("{total}");

    let label = compose(multiply_by(10), |n: u32| format!("{n} pts"));
    println!("{}", label(4));
    println!("{}", apply_twice(multiply_by(2), 5));

    // Currying by hand: each closure fixes one argument and returns the next closure.
    let between = |lo: u32| move |hi: u32| move |n: u32| n.clamp(lo, hi);
    let to_percent = between(0)(100);
    println!("{:?}", [35, 85, 125].map(to_percent));
}

In practice: use iterator chains for transformations; they are as fast as hand-written loops. Take impl Fn in arguments and return impl Fn from factory functions. Use move closures whenever the returned closure must own what it captured.

Each closure has its own unnamed type, so a function returning two different closures from if/else branches needs Box<dyn Fn> instead of impl Fn.

Iterator adapters are lazy: a map with no consumer such as collect, sum or for does nothing, and the compiler warns about it.

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

Rust

enum is a real sum type: each variant can carry its own fields (tuple or struct style), and match destructures them. The compiler requires every match to be exhaustive, so adding a variant turns every unhandled match into a compile error. Option and Result are ordinary enums built the same way.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A sum type whose variants carry their own data (each variant is a product type).
enum PaymentEvent {
    Authorized { amount_cents: u32 },
    Captured { amount_cents: u32 },
    Refunded { amount_cents: u32, reason: String },
    Failed(String),
}

fn describe(event: &PaymentEvent) -> String {
    // match is checked for exhaustiveness: a new variant breaks the build until handled.
    match event {
        PaymentEvent::Authorized { amount_cents } => format!("hold {amount_cents}"),
        PaymentEvent::Captured { amount_cents } => format!("charge {amount_cents}"),
        PaymentEvent::Refunded { amount_cents, reason } => {
            format!("refund {amount_cents} ({reason})")
        }
        PaymentEvent::Failed(code) => format!("failed: {code}"),
    }
}

fn net_cents(events: &[PaymentEvent]) -> i64 {
    events
        .iter()
        .map(|e| match e {
            PaymentEvent::Captured { amount_cents } => i64::from(*amount_cents),
            PaymentEvent::Refunded { amount_cents, .. } => -i64::from(*amount_cents),
            _ => 0, // a deliberate catch-all; it also hides future variants from the check
        })
        .sum()
}

fn main() {
    let events = [
        PaymentEvent::Authorized { amount_cents: 5000 },
        PaymentEvent::Captured { amount_cents: 5000 },
        PaymentEvent::Refunded { amount_cents: 1200, reason: "damaged".into() },
        PaymentEvent::Failed("card_declined".into()),
    ];
    for event in &events {
        println!("{}", describe(event));
    }
    println!("net {}", net_cents(&events));
}

In practice: model states that cannot coexist as enum variants with only the data each one needs. Match on every variant by name in core logic and use _ only when the remaining cases truly do not matter. Use if let or let else for single-variant checks.

A _ arm silences exhaustiveness for every future variant too; list variants explicitly where a new one should force a decision.

Matching on a reference (&PaymentEvent) binds the fields by reference, so amount_cents is &u32 and net_cents dereferences it with *.

#[non_exhaustive] on a public enum forces other crates to include a wildcard arm.

Declarative vs imperative: loops vs pipelines, recursion vs iteration

Rust

Rust supports both styles equally well: a for loop with a mut Vec, or an iterator chain (filter, map, take, collect) that compiles to the same machine code. Sorting is in place on a Vec or slice, so a chain usually collects once, sorts, and continues. Rust does not guarantee tail-call elimination, so deep recursion can overflow the main thread's stack (typically 8 MB).

Complete program

Complete program.

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

struct User {
    name: &'static str,
    active: bool,
    score: u32,
}

// Recursion is fine for shallow input; Rust does not guarantee tail-call elimination.
fn sum_to(n: u64) -> u64 {
    if n == 0 { 0 } else { n + sum_to(n - 1) }
}

fn main() {
    let users = [
        User { name: "ana", active: true, score: 82 },
        User { name: "ben", active: false, score: 97 },
        User { name: "cy", active: true, score: 91 },
        User { name: "dee", active: true, score: 64 },
        User { name: "eli", active: true, score: 88 },
    ];

    // Imperative: a loop with a mutable accumulator.
    let mut picked: Vec<&User> = Vec::new();
    for u in &users {
        if u.active {
            picked.push(u);
        }
    }
    picked.sort_by(|a, b| b.score.cmp(&a.score));
    let mut imperative = Vec::new();
    for u in picked.iter().take(3) {
        imperative.push(u.name);
    }

    // Declarative: iterator chains. Sorting needs the items in a Vec, so collect once.
    let mut active: Vec<&User> = users.iter().filter(|u| u.active).collect();
    active.sort_by_key(|u| Reverse(u.score));
    let declarative: Vec<&str> = active.iter().take(3).map(|u| u.name).collect();
    println!("{imperative:?} {declarative:?}");

    // Iteration uses constant stack however large n gets.
    let total: u64 = (1..=1_000_000).sum();
    println!("{} {total}", sum_to(1_000));
}

In practice: use iterator chains for filter, transform and aggregate steps and loops when the body has complex control flow or several outputs. Use find, any or position for early exit. Turn deep recursion into a loop or an explicit Vec stack.

Release builds often optimize tail recursion into a loop, but debug builds do not, so code that relies on it can overflow only in tests.

sort_by_key with Reverse sorts descending; sort_by is stable, sort_unstable_by is faster when ties do not matter.