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

C++

C++ began as procedural C and still compiles straight-line loops over contiguous data to very fast code, which is why imperative style dominates performance-sensitive work. Range-based for, structured bindings and std::map::operator[] keep the procedural version short.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <map>
#include <print>
#include <string>
#include <vector>

struct Order {
    std::string category;
    int cents;
};

// A procedure: a loop that updates local state and returns the result.
std::map<std::string, int> totals_by_category(const std::vector<Order>& orders) {
    std::map<std::string, int> totals; // sorted by key
    for (const auto& order : orders) {
        totals[order.category] += order.cents; // operator[] inserts 0 for a new key
    }
    return totals;
}

int main() {
    const std::vector<Order> orders{
        {"books", 1200}, {"games", 5999}, {"books", 850}, {"music", 999}, {"games", 2000}};
    int grand = 0;
    for (const auto& [category, cents] : totals_by_category(orders)) {
        std::println("{:<6} ${}.{:02}", category, cents / 100, cents % 100);
        grand += cents;
    }
    std::println("total  ${}.{:02}", grand / 100, grand % 100);
}

In practice: pass inputs by const reference and return results by value (the compiler moves or elides the copy); keep mutable variables local; prefer a named function or a standard algorithm to a long block of loose statements.

map::operator[] inserts a value-initialised element for a missing key, which is what an accumulator wants and a surprise in a plain lookup (use find or contains there).

std::map keeps keys sorted; std::unordered_map is faster for large inputs but iterates in an unspecified order.

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

C++

A C++ class bundles data and member functions with access control per class: private members are reachable only from the class's own members and friends. The constructor establishes the invariant (throwing if it cannot), every public member function preserves it, and const member functions promise not to change the object, so they can be called on const objects and references.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <print>
#include <stdexcept>
#include <string>
#include <utility>

class Account {
public:
    // The constructor establishes the invariant; every member function keeps it.
    Account(std::string owner, long long opening) : owner_{std::move(owner)}, cents_{opening} {
        if (cents_ < 0) throw std::invalid_argument{"opening balance must not be negative"};
    }

    long long balance() const { return cents_; } // const: cannot modify, callable on const objects
    const std::string& owner() const { return owner_; }

    void deposit(long long cents) {
        if (cents <= 0) throw std::invalid_argument{"deposit must be positive"};
        cents_ += cents;
    }

    [[nodiscard]] bool withdraw(long long cents) {
        if (cents <= 0 || cents > cents_) return false; // keeps cents_ >= 0
        cents_ -= cents;
        return true;
    }

private:
    std::string owner_;
    long long cents_;
};

int main() {
    Account account{"Ada", 5000};
    account.deposit(2500);
    const bool big = account.withdraw(10000);
    const bool small = account.withdraw(3000);
    std::println("{} {} {} {}", account.owner(), big, small, account.balance()); // Ada false true 4500
    try {
        Account bad{"Bob", -1};
    } catch (const std::invalid_argument& e) {
        std::println("{}", e.what());
    }
    // account.cents_ = 0; // error: 'cents_' is a private member of 'Account'
}

In practice: use class with private data when there is an invariant and a plain struct when the fields vary independently; mark every query const; initialise members in the member initialiser list, and mark single-argument constructors explicit.

Access control is per class, not per object: one Account member function may read another Account's private cents_.

Returning a non-const reference or pointer to a private member hands out write access and defeats the invariant.

[[nodiscard]] makes the compiler warn when a caller ignores whether withdraw succeeded.

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

C++

C++ has two polymorphism mechanisms. Dynamic: an abstract base class declares virtual functions, derived classes override them, and calls through a base reference or pointer dispatch at runtime via a vtable. Static: templates constrained by concepts accept any type with the required operations, resolved at compile time with no base class and no virtual call.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <concepts>
#include <memory>
#include <numbers>
#include <print>
#include <string>
#include <vector>

// Dynamic polymorphism: an abstract base class with pure virtual functions.
struct Shape {
    virtual ~Shape() = default; // deleting through Shape* runs the derived destructor
    virtual std::string name() const = 0;
    virtual double area() const = 0;
};

class Circle final : public Shape {
public:
    explicit Circle(double r) : r_{r} {}
    std::string name() const override { return "circle"; } // override: error if the signature drifts
    double area() const override { return std::numbers::pi * r_ * r_; }
private:
    double r_;
};

class Rect final : public Shape {
public:
    Rect(double w, double h) : w_{w}, h_{h} {}
    std::string name() const override { return "rect"; }
    double area() const override { return w_ * h_; }
private:
    double w_, h_;
};

// Static polymorphism: a concept states the requirement, checked at compile time.
template <typename T>
concept HasArea = requires(const T& t) { { t.area() } -> std::convertible_to<double>; };

struct Square { double side; double area() const { return side * side; } }; // no base class

double twice_area(const HasArea auto& s) { return 2 * s.area(); }

int main() {
    std::vector<std::unique_ptr<Shape>> shapes; // owns objects of different derived types
    shapes.push_back(std::make_unique<Circle>(1.0));
    shapes.push_back(std::make_unique<Rect>(2.0, 3.0));
    for (const auto& s : shapes) {
        std::println("{:<6} {:.2f}", s->name(), s->area()); // virtual call through the vtable
    }
    std::println("square twice {:.2f}", twice_area(Square{2.0}));
}

In practice: give every polymorphic base a public virtual destructor (or a protected non-virtual one); write override on every overriding function and final where no further overriding is intended; own heterogeneous objects with std::vector<std::unique_ptr<Base>>, and use templates or concepts when the type is known at compile time.

Deleting a derived object through a base pointer whose destructor is not virtual is undefined behaviour.

Without override, a misspelled name or a missing const silently declares a new function instead of overriding.

Virtual calls made inside a constructor or destructor go to the class being constructed, not the most-derived override.

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

C++

C++ supports public, protected and private inheritance, including multiple inheritance. Public inheritance models is-a: a derived object can be used through a base reference, and virtual functions dispatch to its overrides. Copying a derived object into a base by value slices it: only the base part is copied and the overrides are gone. Composition (a member, or a container of members) models has-a and exposes only what the outer class chooses.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <memory>
#include <print>
#include <string>
#include <utility>
#include <vector>

class Employee {
public:
    explicit Employee(std::string name) : name_{std::move(name)} {}
    virtual ~Employee() = default;
    virtual int pay() const { return 3000; }
    const std::string& name() const { return name_; }
private:
    std::string name_;
};

// Public inheritance models is-a: a Manager can stand wherever an Employee is expected.
class Manager : public Employee {
public:
    using Employee::Employee; // inherit the constructor
    int pay() const override { return Employee::pay() + 1000; } // call the base version explicitly
};

void print_pay(const Employee& e) { std::println("{} {}", e.name(), e.pay()); }
// Composition: a Team has employees and exposes only hire and payroll.
class Team {
public:
    void hire(std::unique_ptr<Employee> e) { members_.push_back(std::move(e)); }
    int payroll() const {
        int sum = 0;
        for (const auto& m : members_) sum += m->pay();
        return sum;
    }
private:
    std::vector<std::unique_ptr<Employee>> members_;
};

int main() {
    Manager grace{"Grace"};
    print_pay(grace); // Grace 4000: by reference, dynamic dispatch works
    Employee sliced = grace; // object slicing: copies only the Employee part
    print_pay(sliced); // Grace 3000: the Manager override is gone
    Team team;
    team.hire(std::make_unique<Employee>("Ada"));
    team.hire(std::make_unique<Manager>("Grace"));
    std::println("payroll {}", team.payroll()); // 7000
}

In practice: favour composition over inheritance; inherit publicly only when the derived class honours every promise of the base (Liskov substitution); pass polymorphic objects by reference or smart pointer, never by value, and consider deleting the base class copy operations to make slicing a compile error.

Slicing also happens in std::vector<Base> and in catch (Base e); catch exceptions by const reference.

Inheriting from standard containers (class Team : public std::vector<...>) is legal but exposes every vector operation and has no virtual destructor; hold the vector as a member.

Employee::pay() inside Manager names the base version explicitly and bypasses virtual dispatch; an unqualified pay() there would recurse into the override.

Design principles: SOLID and dependency inversion with an injected interface

C++

In C++ the abstraction is usually an abstract class with pure virtual functions (an interface in all but name), and the dependency is injected through the constructor as a reference or smart pointer. The service depends only on the interface header, so a new implementation needs no change to it (open/closed) and tests can pass a fake. A template parameter or concept is the compile-time alternative when the choice is fixed per build.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <format>
#include <print>
#include <string>
#include <vector>

// Interface segregation: OrderService needs exactly one capability.
struct Notifier {
    virtual ~Notifier() = default;
    virtual void send(const std::string& to, const std::string& message) = 0;
};

// Dependency inversion: the policy depends on Notifier, injected by the caller.
class OrderService {
public:
    explicit OrderService(Notifier& notifier) : notifier_{notifier} {}
    int place(const std::string& customer, int cents) {
        const int id = next_id_++;
        notifier_.send(customer, std::format("order {} confirmed: {} cents", id, cents));
        return id;
    }
private:
    Notifier& notifier_; // not owned: the caller keeps it alive
    int next_id_ = 1;
};

struct ConsoleNotifier final : Notifier {
    void send(const std::string& to, const std::string& message) override {
        std::println("to {}: {}", to, message);
    }
};

// A fake for tests: records messages instead of sending them.
struct FakeNotifier final : Notifier {
    std::vector<std::string> sent;
    void send(const std::string& to, const std::string& message) override {
        sent.push_back(to + " | " + message);
    }
};

int main() {
    FakeNotifier fake;
    OrderService service{fake};
    service.place("ada@example.com", 4200);
    service.place("ada@example.com", 999);
    for (const auto& line : fake.sent) std::println("{}", line);

    ConsoleNotifier console;
    OrderService{console}.place("bob@example.com", 1500); // same policy, real detail
}

In practice: keep interfaces small and free of data members; inject by reference when the caller guarantees the dependency outlives the service, or by std::unique_ptr when the service should own it; give the interface a virtual destructor.

A reference member makes the class non-assignable and dangles if the referenced object is destroyed first; the caller must keep the notifier alive.

A reference cannot be null, which documents that the dependency is required; use a pointer only when it is genuinely optional.

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

C++

C++ supports functional style without requiring it: lambdas, std::function and <functional> treat functions as values, <ranges> adds lazy pipelines, and const and constexpr limit what a function may change. A constexpr function evaluated at compile time cannot perform I/O or touch non-constant globals, so static_assert can test pure logic during the build.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <print>
#include <vector>

struct Order {
    int subtotal_cents;
    int loyalty_years;
};

// A constexpr function must be free of most side effects, so it is a natural pure function.
constexpr int discount_percent(int years) {
    if (years >= 5) return 15;
    if (years >= 2) return 5;
    return 0;
}

constexpr int total_cents(const Order& o) {
    return o.subtotal_cents * (100 - discount_percent(o.loyalty_years)) / 100;
}

// Tests that run during compilation: a failing case stops the build.
static_assert(total_cents({.subtotal_cents = 10000, .loyalty_years = 5}) == 8500);
static_assert(total_cents({.subtotal_cents = 10000, .loyalty_years = 0}) == 10000);

int main() {
    const std::vector<Order> orders{{12000, 1}, {8000, 3}, {20000, 6}};

    // Imperative shell: the loop and the printing live outside the pure core.
    int n = 0;
    for (const Order& o : orders) {
        const int cents = total_cents(o);
        std::println("order {}: {}.{:02}", ++n, cents / 100, cents % 100);
    }
}

In practice: pass inputs by value or const reference and return results instead of writing through out-parameters. Mark small rules constexpr so they can be checked with static_assert. Keep printing, files and clocks in main or a thin outer layer.

constexpr allows a function to run at compile time; called with runtime values it runs normally, so the compiler only checks the calls it actually evaluates at compile time.

A const member function can still change mutable members or data behind a pointer; const limits the object, not everything the function can reach.

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

C++

Objects are mutable unless declared const, and const applies through the type: a const object, a const& parameter and a const member function all promise not to change the value. constexpr marks values and functions usable at compile time. Copying is explicit in the type: a plain parameter or assignment copies (deep for std::string and std::vector), while a reference or pointer aliases.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <print>
#include <string>
#include <vector>

struct Account {
    std::string id;
    int balance;
    std::vector<std::string> tags;
};

// const& reads the caller's value without copying it and without permission to change it.
Account with_credit(const Account& a, int amount) {
    Account next = a;  // a real copy: string and vector copy their elements
    next.balance += amount;
    next.tags.push_back("active");
    return next;
}

constexpr int max_retries = 3;  // a compile-time constant

int main() {
    const Account original{.id = "a1", .balance = 100, .tags = {"new"}};
    // original.balance = 50;  // error: original is const
    const Account credited = with_credit(original, 25);
    std::println("{} {}", original.balance, original.tags);
    std::println("{} {}", credited.balance, credited.tags);

    // A non-const reference is an alias: writing through it changes the referred-to object.
    Account draft = original;
    Account& alias = draft;
    alias.balance = 0;
    std::println("{} {} {}", draft.balance, original.balance, max_retries);
}

In practice: make local variables const by default and pass inputs as const&. Return updated values instead of changing arguments, unless the copy is too costly. Use non-const references only where the function's job is to modify its argument.

const on a pointer is two different things: const T* forbids writing the pointee, T* const forbids repointing.

A const member that is a pointer or reference still lets you change what it points at; const is shallow through pointers.

Returning a local by value is cheap: the compiler moves it or elides the copy entirely.

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

C++

Lambdas are function objects with a unique type, so they can be passed to templates, returned from functions with auto, and stored in std::function when the type must be fixed. <functional> adds std::bind_front for partial application and ready-made operators like std::plus; <ranges> views (filter, transform, take) compose lazily with |, and C++23 adds std::ranges::fold_left.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <functional>
#include <print>
#include <ranges>
#include <string>
#include <vector>

// A function returning a lambda: capture by value so the result outlives this call.
auto multiply_by(int factor) {
    return [factor](int n) { return n * factor; };
}

// compose(f, g)(x) is g(f(x)); abbreviated templates accept any callables.
auto compose(auto f, auto g) {
    return [=](auto x) { return g(f(x)); };
}

int clamp_to(int lo, int hi, int n) { return std::clamp(n, lo, hi); }

int main() {
    const std::vector prices{12, 40, 7, 25};
    // Each | stage takes a function; the view is lazy until something iterates it.
    auto tripled = prices | std::views::filter([](int p) { return p >= 10; }) |
                   std::views::transform(multiply_by(3));
    std::println("{}", std::ranges::fold_left(tripled, 0, std::plus{}));

    auto label = compose(multiply_by(10), [](int n) { return std::to_string(n) + " pts"; });
    std::println("{}", label(4));

    // Partial application: bind_front fixes the leading arguments.
    auto to_percent = std::bind_front(clamp_to, 0, 100);
    const std::vector scores{35, 85, 125};
    std::println("{}", scores | std::views::transform(to_percent));
}

In practice: use views and range algorithms for transformations and plain lambdas for the steps. Capture by value in any lambda that outlives the current scope. Prefer bind_front or a lambda to the older std::bind.

A lambda that captures by reference ([&]) and is returned or stored will dangle once the captured locals go out of scope.

std::function erases the type and may allocate; take callables as auto or template parameters when you do not need to store them.

views::filter caches its first match, so iterating a filter view requires it to be non-const.

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

C++

std::variant<A, B, C> is a type-safe tagged union: it holds exactly one alternative and knows which. std::visit calls a visitor with the active alternative, and the overloaded helper (a struct inheriting several lambdas) gives one case per type; the call fails to compile if some alternative has no matching overload. std::get_if and std::holds_alternative check for a single alternative.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <format>
#include <print>
#include <string>
#include <variant>
#include <vector>

// Product types: plain structs.
struct Authorized { int amount_cents; };
struct Captured { int amount_cents; };
struct Refunded { int amount_cents; std::string reason; };
struct Failed { std::string code; };

// Sum type: a PaymentEvent holds exactly one of these alternatives at a time.
using PaymentEvent = std::variant<Authorized, Captured, Refunded, Failed>;

// overloaded inherits each lambda's operator(), giving one visitor with a case per type.
template <class... Fs>
struct overloaded : Fs... { using Fs::operator()...; };

std::string describe(const PaymentEvent& event) {
    // std::visit does not compile if some alternative has no matching overload.
    return std::visit(overloaded{
        [](const Authorized& e) { return std::format("hold {}", e.amount_cents); },
        [](const Captured& e) { return std::format("charge {}", e.amount_cents); },
        [](const Refunded& e) { return std::format("refund {} ({})", e.amount_cents, e.reason); },
        [](const Failed& e) { return std::format("failed: {}", e.code); },
    }, event);
}

int main() {
    const std::vector<PaymentEvent> events{
        Authorized{5000}, Captured{5000}, Refunded{1200, "damaged"}, Failed{"card_declined"}};
    int net = 0;
    for (const PaymentEvent& e : events) {
        std::println("{}", describe(e));
        // get_if checks for one alternative and returns nullptr otherwise.
        if (const auto* c = std::get_if<Captured>(&e)) net += c->amount_cents;
        if (const auto* r = std::get_if<Refunded>(&e)) net -= r->amount_cents;
    }
    std::println("net {}", net);
}

In practice: use variant plus visit for closed sets of shapes, and a virtual base class when other code must be able to add new types. Write one typed lambda per alternative and avoid a generic auto catch-all where you want the compiler to catch new alternatives. Use get_if instead of std::get when the alternative might not be active.

Overload resolution, not exact matching, picks the visitor case: an int alternative can silently match a lambda taking double, so give each alternative its own exact-typed case.

std::get<T> throws std::bad_variant_access when T is not the active alternative.

A variant can become valueless_by_exception if an assignment throws midway; with ordinary value types this almost never happens.

Declarative vs imperative: loops vs pipelines, recursion vs iteration

C++

Classic C++ is imperative: loops and in-place algorithms. C++20 ranges add a declarative layer: views (filter, transform, take) chain lazily with |, range algorithms accept projections such as &User::score, and C++23 std::ranges::to collects a view into a container. The standard does not guarantee tail-call elimination, so deep recursion can overflow the stack even when compilers sometimes optimize it away.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <functional>
#include <print>
#include <ranges>
#include <string>
#include <vector>

struct User {
    std::string name;
    bool active;
    int score;
};

// Recursion: no tail-call guarantee in C++, so deep input can overflow the stack.
constexpr long long sum_to(long long n) { return n == 0 ? 0 : n + sum_to(n - 1); }

int main() {
    const std::vector<User> users{
        {"ana", true, 82}, {"ben", false, 97}, {"cy", true, 91}, {"dee", true, 64}, {"eli", true, 88}};

    // Imperative: loop, push, sort, index.
    std::vector<User> picked;
    for (const User& u : users)
        if (u.active) picked.push_back(u);
    std::ranges::sort(picked, std::greater{}, &User::score);  // &User::score is a projection
    std::vector<std::string> imperative;
    for (std::size_t i = 0; i < picked.size() && i < 3; ++i) imperative.push_back(picked[i].name);

    // Declarative: views describe the steps; ranges::to (C++23) materializes them.
    auto active = users | std::views::filter(&User::active) | std::ranges::to<std::vector>();
    std::ranges::sort(active, std::greater{}, &User::score);
    auto declarative =
        active | std::views::take(3) | std::views::transform(&User::name) | std::ranges::to<std::vector>();
    std::println("{} {}", imperative, declarative);

    long long total = 0;
    for (long long i = 1; i <= 1'000'000; ++i) total += i;  // iteration: constant stack
    std::println("{} {}", sum_to(1000), total);
}

In practice: use range algorithms with projections instead of hand-written comparators and views for simple filter-transform-take chains. Fall back to a loop when the logic needs early exit with side effects or several outputs. Convert recursion that can go deep into iteration.

Views do not own their data: returning a view over a local vector dangles. Materialize with std::ranges::to before the source goes away.

libc++ (Apple clang) still lacks some C++23 views such as views::enumerate; check your standard library before relying on newer views.

Stack size is set by the platform (often 8 MB for the main thread, less for others), so the safe recursion depth varies.