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.

Libraries: core

What each language ships for everyday programming: printing, text, collections, iteration, optional values, errors and assertions, standard interfaces, numbers and bits, time and memory. Each entry compares the same role across languages.

Printing & formatting: console, fmt, println!, <print>

Rust

Formatting lives in std::fmt and is used through macros: println! and print! write to standard output, eprintln! to standard error, format! returns a String, and write!/writeln! target any writer. {} uses a type's Display implementation (for people) and {:?} uses Debug (for programmers; #[derive(Debug)] provides one). Format strings are checked at compile time.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

struct Item {
    name: String,
    count: u32,
}

impl fmt::Display for Item {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} x{}", self.name, self.count)
    }
}

fn main() {
    let item = Item { name: "bolt".to_string(), count: 3 };

    println!("{item}"); // uses Display
    println!("{:>8}|{:03}", item.name, item.count); // width and padding
    let label = format!("{} items", item.count); // a String, not printed
    eprintln!("warning: {label}"); // standard error
    println!("{:?}", vec![1, 2, 3]); // Debug format
}

Most used: println!, eprintln!, format!, write!, {:?} and {:#?} for debugging, width and precision like {:>8} and {:.2}, impl fmt::Display for your own types.

Text: String methods, strings, str/String, <string>

Rust

Rust has two string types: &str, a borrowed view of UTF-8 text (string literals are &str), and String, an owned, growable buffer. The methods are defined on str and work on both: trim, split, contains, find, starts_with, replace, to_uppercase, lines and chars. String adds push_str and push. Byte-range slicing like &s[..3] panics if it cuts a multi-byte character.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let raw = "  Ada Lovelace,Grace Hopper ";

    let names: Vec<&str> = raw.trim().split(',').collect();
    println!("{} {}", names[0].to_uppercase(), names.len());
    println!("{} {:?}", raw.contains("Grace"), raw.find("Ada"));
    println!("{} {}", &names[0][..3], names[1].replace(' ', "_"));
    println!("{} {}", names.join(" & "), "-".repeat(5));

    let mut initials = String::new(); // owned, growable
    for name in &names {
        initials.push_str(&name[..1]);
    }
    println!("{initials}");
}

Most used: split, trim, lines, contains, starts_with, replace, to_string/to_owned, format!, push_str, chars, parse.

Text ↔ number conversion: Number, strconv, parse, <charconv>

Rust

str::parse::<T>() converts text to any type that implements the FromStr trait: all integer and float types, bool, char, IP addresses and more. It returns a Result, so malformed or out-of-range input is an error you handle, never a silent 0. from_str_radix parses other bases; to_string() and format! convert back.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    for text in ["42", "3.5", "12px", ""] {
        match text.parse::<i32>() {
            Ok(n) => println!("{text:?} -> {n}"),
            Err(error) => println!("{text:?} -> error: {error}"),
        }
    }

    let f: f64 = "3.5".parse().expect("valid float");
    let u = u8::from_str_radix("ff", 16).expect("valid hex");
    let too_big = "300".parse::<u8>(); // out of range is an error, not a wrap
    println!("{f} {u} {too_big:?}");
    println!("{} {:.2} {:x}", 42.to_string(), 3.14159, 255);
}

Most used: text.parse::<i32>(), text.trim().parse(), u8::from_str_radix, n.to_string(), format!("{:.2}", x), implementing FromStr for your own types.

Collections: Array/Map/Set, slices/maps, std::collections, containers

Rust

Vec<T> is the growable array and needs no import. std::collections holds the rest: HashMap and HashSet (fast, unordered), BTreeMap and BTreeSet (sorted by key), VecDeque (double-ended queue) and BinaryHeap (priority queue). Lookups such as get return Option, so a missing key is explicit, and the entry API inserts or updates in one step.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

fn main() {
    let mut scores = vec![72, 95, 88]; // Vec<i32>: growable array
    scores.push(61);

    let mut by_name = HashMap::new();
    by_name.insert("ada", 95);
    *by_name.entry("grace").or_insert(0) += 88; // insert or update

    let tags: HashSet<&str> = ["go", "rust", "go"].into_iter().collect();
    let sorted: BTreeMap<_, _> = by_name.iter().collect(); // ordered by key
    let mut queue = VecDeque::from([1, 2]);
    queue.push_front(0);

    println!("{} {:?} {:?}", scores.len(), scores.iter().max(), by_name.get("linus"));
    println!("{} {:?} {:?}", tags.len(), sorted, queue);
}

Most used: vec![], push, len, iter, HashMap::new, insert, get, entry().or_insert, HashSet, BTreeMap, VecDeque.

Collection algorithms: Array methods, slices, Iterator, <algorithm>

Rust

Algorithms come from the Iterator trait. .iter() produces an iterator, adaptors (map, filter, enumerate, zip, take) build a lazy pipeline, and a consumer (sum, collect, count, find, any, max_by_key) runs it. Nothing happens until the consumer is called. Slices add in-place methods: sort, sort_by_key, binary_search, dedup, windows and chunks.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

fn main() {
    let mut orders = vec![
        Order { id: 1, total: 40, paid: true },
        Order { id: 2, total: 15, paid: false },
        Order { id: 3, total: 90, paid: true },
    ];

    let revenue: u32 = orders.iter().filter(|o| o.paid).map(|o| o.total).sum();
    let unpaid = orders.iter().find(|o| !o.paid).map(|o| o.id);
    orders.sort_by_key(|o| std::cmp::Reverse(o.total)); // descending

    println!("{revenue} {unpaid:?} {}", orders[0].id);
}

Most used: iter, map, filter, collect, sum, find, any, enumerate, zip, sort_by_key, sort_unstable. The itertools crate adds more adaptors.

Iterators & generators: function*, iter.Seq, Iterator, <ranges>

Rust

Implementing the Iterator trait means writing one method, next, which returns Some(item) until it returns None; every adaptor and consumer (map, filter, take, collect, sum) then works on your type. std::iter has constructors for quick cases: from_fn, successors, repeat, once and empty. Implementing IntoIterator makes a type usable directly in a for loop.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
struct Range {
    next: u32,
    end: u32,
    step: u32,
}

impl Iterator for Range {
    type Item = u32;

    fn next(&mut self) -> Option<u32> { // the one required method
        if self.next >= self.end {
            return None;
        }
        let current = self.next;
        self.next += self.step;
        Some(current)
    }
}

fn main() {
    let stepped: Vec<u32> = Range { next: 0, end: 10, step: 3 }.collect();
    println!("{stepped:?}"); // every adaptor works on it: map, filter, zip...

    let squares = (1..).map(|n| n * n); // infinite and lazy
    println!("{:?}", squares.take(4).collect::<Vec<_>>());

    let mut countdown = 3;
    let launch = std::iter::from_fn(|| {
        countdown -= 1;
        (countdown > 0).then_some(countdown) // an ad-hoc iterator from a closure
    });
    println!("{:?}", launch.collect::<Vec<_>>());
}

Most used: impl Iterator for T, type Item, next, IntoIterator, iter::from_fn, iter::successors, open ranges (1..), rev, peekable, collect.

Optional & variant values: unions, comma-ok, Option, <optional>/<variant>

Rust

Option<T> (Some or None) and enums that carry data are part of the language, and match must handle every variant, so a forgotten case is a compile error. Option has many methods for working with a value that may be missing without unwrapping it: map, and_then, unwrap_or, ok_or, filter and take. Result<T, E> applies the same idea to failures.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

enum Shipping {
    Pickup,
    Courier { address: String },
}

fn describe(shipping: &Shipping, note: Option<&str>) -> String {
    let extra = note.unwrap_or("no note");
    match shipping {
        Shipping::Pickup => format!("pickup ({extra})"),
        Shipping::Courier { address } => format!("courier to {address} ({extra})"),
    }
}

fn main() {
    let names = HashMap::from([(7, "Ada")]);
    let upper = names.get(&8).map(|name| name.to_uppercase()); // None stays None
    println!("{upper:?}");

    if let Some(name) = names.get(&7) {
        println!("found {name}");
    }
    let courier = Shipping::Courier { address: "1 Main St".into() };
    println!("{}", describe(&courier, None));
    println!("{}", describe(&Shipping::Pickup, Some("fragile")));
}

Most used: Some/None, if let Some(x), match, map, and_then, unwrap_or, unwrap_or_default, ok_or, ? on Option, enum variants with fields.

Errors: Error, errors, Result + std::error, <stdexcept>/<expected>

Rust

Recoverable failures are values of Result<T, E>, and missing values are Option<T>; both need no import. The ? operator returns early with the error. The std::error::Error trait, together with Display and Debug, marks a type as an error so it can be boxed as Box<dyn Error> or chained through source(). Many projects derive error types with thiserror and use anyhow for application errors with context.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

#[derive(Debug)]
enum LoadError {
    NotFound(String),
}

impl fmt::Display for LoadError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            LoadError::NotFound(id) => write!(f, "order {id} not found"),
        }
    }
}

impl std::error::Error for LoadError {}

fn load(id: &str) -> Result<u32, LoadError> {
    if id != "1" {
        return Err(LoadError::NotFound(id.to_string()));
    }
    Ok(40)
}

fn main() {
    match load("7") {
        Ok(total) => println!("{total}"),
        Err(error) => println!("missing: {error}"),
    }
}

Most used: Result, Option, ?, match, map_err, ok_or, unwrap_or, Box<dyn Error>, impl std::error::Error. panic! is for bugs.

Libraries usually define an error enum with the thiserror crate (2.x): #[derive(Debug, thiserror::Error)] on the enum, #[error("could not read {path}")] for the message, and #[from] on a field to convert a source error so ? works.

Applications usually return anyhow::Result<T> (anyhow 1.x), which holds any error type, and add context while propagating: fs::read_to_string(&path).with_context(|| format!("reading {path}"))?. Print with {:#} or {:?} to see the whole chain.

Install with cargo add thiserror or cargo add anyhow. A common split: thiserror in library crates, so callers can match on variants, and anyhow in the binary.

Assertions & invariants: node:assert, panic, assert!, <cassert>/static_assert

Rust

assert! and assert_eq!/assert_ne! check invariants in every build and panic with a message when one fails. debug_assert! and its _eq/_ne forms are checked only when debug assertions are on (the default for cargo build and cargo test) and are compiled out with --release, so they suit expensive checks. unreachable! marks code that should never run, todo! and unimplemented! mark unfinished code, and all of them panic. const { assert!(...) } blocks (Rust 1.79+) or const _: () = assert!(...) fail the build instead. Use Result for failures a caller can expect and panic for bugs.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

const PAGE: usize = 4096;
const _: () = assert!(PAGE.is_power_of_two()); // checked at compile time

fn parse_status(code: u8) -> Result<&'static str, String> { // expected failure: Result
    match code {
        0 => Ok("open"),
        1 => Ok("paid"),
        _ => Err(format!("unknown status {code}")),
    }
}

fn split(total: u32, parts: u32) -> u32 {
    assert!(parts > 0, "parts must be positive"); // checked in every build
    debug_assert!(total % parts == 0, "uneven split {total}/{parts}"); // gone with --release
    total / parts
}

fn main() {
    const { assert!(size_of::<u64>() == 8) }; // inline const block, Rust 1.79+
    println!("{:?} {:?}", parse_status(1), parse_status(9));
    assert_eq!(split(10, 2), 5);

    panic::set_hook(Box::new(|_| {})); // silence the default panic message
    match panic::catch_unwind(|| split(10, 3)) {
        Ok(n) => println!("release build: split returned {n}"),
        Err(payload) => println!("debug build: {}", payload.downcast_ref::<String>().unwrap()),
    }
    let n = 7 % 3;
    let kind = match n {
        0 | 1 | 2 => "small",
        _ => unreachable!("remainder of % 3 is below 3"),
    };
    println!("{kind}");
}

Most used: assert!(cond, "msg {x}"), assert_eq!, debug_assert!, unreachable!(), todo!(), const { assert!(...) }, expect("why this cannot fail"), Result for expected errors.

This program prints different lines in debug and --release builds: debug_assert! is gone in release, so the uneven split returns 3.

catch_unwind is for boundaries such as thread pools and FFI; it does not catch panics when the crate is built with panic = "abort".

Standard interfaces & traits: protocols, Stringer, derive, concepts

Rust

The standard traits are how Rust types plug into the language and library. Most are derived in one line: Debug ({:?}), Clone and Copy (duplication), PartialEq/Eq and PartialOrd/Ord (comparison and sorting), Hash (HashMap keys) and Default. Others are written by hand: Display ({}), From/Into and TryFrom (conversions), Iterator, Drop (cleanup), Deref, and the operator traits in std::ops such as Add.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
struct Money {
    cents: u64,
}

impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "${}.{:02}", self.cents / 100, self.cents % 100)
    }
}

impl From<u64> for Money {
    fn from(cents: u64) -> Self {
        Money { cents }
    }
}

fn main() {
    let mut prices: Vec<Money> = vec![500.into(), 1250.into(), 120.into()]; // From gives Into
    prices.sort(); // Ord
    let unique: HashSet<Money> = prices.iter().copied().collect(); // Hash + Eq, Copy
    let zero = Money::default(); // Default

    println!("{} {:?} {}", prices[0], prices.last(), unique.len()); // Display, Debug
    println!("{}", zero == Money::from(0)); // PartialEq
}

Most used: #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)], impl Display, impl From<T>, .into(), impl Iterator, AsRef<str>, std::ops::Add, Drop.

Functions as values: closures, func types, Fn traits, <functional>

Rust

Closures implement one of three traits depending on how they use what they capture: Fn (reads), FnMut (mutates) and FnOnce (consumes). Accept them generically (impl Fn(u32) -> u32, or F: Fn) or box them (Box<dyn Fn(...)>) to store different closures together; plain functions coerce to function pointers (fn(u32) -> u32). std::mem has the utilities for moving values in and out: swap, replace and take.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

fn compose(steps: Vec<Box<dyn Fn(u32) -> u32>>) -> impl Fn(u32) -> u32 {
    move |n| steps.iter().fold(n, |value, step| step(value))
}

fn add_fee(fee: u32) -> impl Fn(u32) -> u32 {
    move |n| n + fee // the closure owns its copy of fee
}

fn double(n: u32) -> u32 {
    n * 2
}

fn main() {
    let pipeline = compose(vec![
        Box::new(double), // a plain function works where a closure is expected
        Box::new(|n| n * 12 / 10),
        Box::new(add_fee(5)),
    ]);
    println!("{}", pipeline(10));

    let mut name = String::from("old");
    let previous = mem::replace(&mut name, String::from("new")); // swap in a value
    let (mut a, mut b) = (1, 2);
    mem::swap(&mut a, &mut b);
    let taken = mem::take(&mut name); // leaves String::default() behind
    println!("{previous} {taken} {name:?} {a} {b}");
}

Most used: |x| x + 1, move closures, impl Fn, F: FnMut, Box<dyn Fn>, fn pointers, mem::swap, mem::replace, mem::take, Option::take.

Math & random numbers: Math, math + math/rand, number methods, <cmath>/<random>

Rust

Rust has no math module: numeric operations are methods on the number types (x.sqrt(), x.abs(), x.pow(3), a.max(b)), with constants such as i64::MAX and std::f64::consts::PI. Integer types also have checked_add, wrapping_add and saturating_add so you choose what overflow does. Random numbers are not in the standard library; the rand crate is the usual choice.

Complete program

Complete program.

Before you use this

Random numbers use the rand crate (0.10): cargo add rand@0.10. Everything else is the standard library.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    println!("{} {} {}", 2.5_f64.round(), (-1.5_f64).floor(), (-1.5_f64).trunc());
    println!("{} {} {}", 9.max(4), (-7_i32).abs(), 16_f64.sqrt());
    println!("{} {:?} {}", i64::MAX, 250_u8.checked_add(10), f64::NAN.is_nan());

    let roll = rand::random_range(1..=6); // rand crate: not in the standard library
    println!("{roll}");
}

Most used: round, floor, abs, sqrt, pow, max/min, checked_add, i64::MAX, f64::consts::PI, rand::random_range.

Integer & bit math: bitwise ops + Math.clz32, math/bits, integer methods, <bit>/<numeric>

Rust

Bit and integer helpers are methods on each integer type: count_ones, leading_zeros, trailing_zeros, rotate_left, swap_bytes, pow, ilog2 and ilog10 (1.67), isqrt (1.84), is_power_of_two and next_power_of_two (unsigned), and div_ceil (unsigned, 1.73). Plain + - * panic on overflow in debug builds and wrap in release builds, so code that cares picks a method family: checked_* (Option), wrapping_*, saturating_* or overflowing_* (value plus a flag). i128 and u128 hold full 64-bit products. There is no gcd in the standard library; the num-integer crate has one.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let x: u32 = 0b1011_0110;
    println!("{} {} {} {}", x.count_ones(), x.leading_zeros(), x.trailing_zeros(), x.ilog2());
    println!("{:08b} {:#x}", 0b1000_0001u8.rotate_left(1), 0x1234u16.swap_bytes());
    println!(
        "{} {} {} {} {}",
        64u32.is_power_of_two(),
        100u32.next_power_of_two(),
        10u32.div_ceil(3),
        99u64.isqrt(), // integer square root, Rust 1.84+
        3u64.pow(4)
    );

    let top = u8::MAX; // 255; top + 1 would panic in debug and wrap in release
    println!(
        "{:?} {} {} {:?}",
        top.checked_add(1),     // None
        top.wrapping_add(1),    // 0
        top.saturating_add(1),  // 255
        top.overflowing_add(1)  // (0, true)
    );
    println!("{:?}", 7i32.checked_div(0)); // None instead of a panic

    let wide = u64::MAX as u128 * u64::MAX as u128; // no overflow in 128 bits
    println!("{wide} {}", u128::BITS);
}

Most used: count_ones, leading_zeros, trailing_zeros, rotate_left, checked_add, wrapping_mul, saturating_sub, is_power_of_two, div_ceil, ilog2, u32::BITS, as u128 for wide products.

Release builds wrap on overflow unless the profile sets overflow-checks = true; std::num::Wrapping<T> and Saturating<T> make the intended behaviour part of the type.

as casts between integer sizes truncate or reinterpret silently; u8::try_from(x) returns an error instead.

Big numbers & decimals: BigInt, math/big, num-bigint, Boost.Multiprecision

Rust

The standard library stops at fixed-size integers, though they go up to i128 and u128, and checked_*, wrapping_* and saturating_* make overflow explicit. Larger integers come from num-bigint (BigInt, BigUint) and exact decimal arithmetic for money from rust_decimal (Decimal). f64 is a binary float, so 0.1 + 0.2 is not 0.3.

Complete program

Complete program.

Before you use this

Big integers and decimals are crates: cargo add num-bigint rust_decimal

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use num_bigint::BigUint;
use rust_decimal::Decimal;
use std::str::FromStr;

fn main() {
    let big = BigUint::from(2u32).pow(100); // arbitrary-precision integer
    println!("{big}");

    let checked = u64::MAX.checked_mul(2); // built-in integers: overflow is explicit
    let wide = u64::MAX as u128 * 2; // or use a wider type
    println!("{checked:?} {wide}");

    let price = Decimal::from_str("19.99").expect("valid decimal"); // exact, for money
    println!("{} {}", price * Decimal::from(3), 0.1 + 0.2);
}

Most used: u128 and i128, checked_mul, BigUint::from, pow, parse::<BigInt>(), Decimal::from_str, Decimal arithmetic, round_dp.

Time & durations: Date + performance, time, std::time, <chrono>

Rust

std::time is small on purpose: Instant (monotonic, for measuring), SystemTime (wall clock, as an offset from UNIX_EPOCH) and Duration. There are no calendars, time zones or date formatting in the standard library; the chrono and jiff crates provide those. Async code sleeps with tokio::time::sleep instead of thread::sleep.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

fn main() {
    let start = Instant::now(); // monotonic, for measuring

    let since_epoch = SystemTime::now().duration_since(UNIX_EPOCH).expect("clock after 1970");
    println!("{} seconds since the epoch", since_epoch.as_secs());

    thread::sleep(Duration::from_millis(50));
    let tomorrow = since_epoch + Duration::from_secs(24 * 60 * 60);
    println!("tomorrow: {} seconds", tomorrow.as_secs());

    println!("took {:?}", start.elapsed());
}

Most used: Instant::now, elapsed, Duration::from_millis, thread::sleep, SystemTime::now, duration_since(UNIX_EPOCH).

jiff (0.2, pre-1.0) is the newer date-time crate: Timestamp, Zoned (a time in an IANA time zone), civil::Date and Span for calendar arithmetic that respects daylight-saving changes.

chrono (0.4) is the long-established choice: DateTime<Utc>, DateTime<FixedOffset>, NaiveDate and format strings; it pairs with chrono-tz for named time zones. Both crates integrate with serde behind a feature flag.

Unicode & localization: Intl, unicode/utf8, char methods, <locale>/ICU

Rust

str and String are always valid UTF-8; len counts bytes, chars() yields Unicode scalar values and char_indices gives their byte offsets. char has classification and case methods (is_alphabetic, is_numeric, to_uppercase), and str::to_uppercase handles multi-character mappings such as ß to SS. Grapheme clusters come from the unicode-segmentation crate, normalization from unicode-normalization and localization from ICU4X.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let word = "café👍🏽";

    println!("{} {}", word.len(), word.chars().count()); // 13 bytes, 6 chars
    for (i, c) in word.char_indices().take(4) {
        print!("{i}:{c} ");
    }
    println!();

    println!("{} {} {}", 'é'.is_alphabetic(), 'É'.is_uppercase(), "straße".to_uppercase());
    println!("{} {}", "Go".eq_ignore_ascii_case("GO"), word.is_char_boundary(4));
    println!("{:?}", "é".bytes().collect::<Vec<u8>>()); // UTF-8 bytes
}

Most used: chars, char_indices, bytes, len, is_char_boundary, to_uppercase, to_lowercase, eq_ignore_ascii_case, String::from_utf8, unicode-segmentation.

Memory & smart pointers: GC, Box/Rc/Arc, <memory>

Rust

Memory is managed through ownership: each value has one owner and is freed when the owner goes out of scope, with no garbage collector. Smart pointers cover the other cases: Box<T> (a single owner, on the heap), Rc<T> (shared ownership on one thread) and Arc<T> (shared ownership across threads). RefCell and Mutex allow mutation through shared pointers, and Weak breaks reference cycles.

Complete program

Complete program. Standard library: ships with Rust, no install.

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

#[derive(Debug)]
struct Config {
    name: String,
}

fn main() {
    let boxed = Box::new(Config { name: "dev".into() }); // single owner, on the heap

    let shared = Rc::new(RefCell::new(Config { name: "dev".into() })); // one thread
    let other = Rc::clone(&shared);
    other.borrow_mut().name = "prod".into(); // RefCell allows mutation

    let across = Arc::new(Config { name: "worker".into() }); // shared across threads
    let handle = {
        let across = Arc::clone(&across);
        thread::spawn(move || across.name.len())
    };

    println!("{} {:?}", boxed.name, shared.borrow());
    println!("{} {}", Rc::strong_count(&shared), handle.join().unwrap());
}

Most used: Box::new, Box<dyn Trait>, Rc::new and Rc::clone, Arc::new and Arc::clone, RefCell::borrow_mut, Weak, Rc::strong_count.