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.

Numbers & operators

Choose a numeric type

Rust

i/u prefixes select signed/unsigned integers; the suffix is their bit width. isize/usize are pointer-sized. f32/f64 are floating point; bool is separate. Unsuffixed integer literals commonly infer i32, floats f64.

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+
let count: i64 = 24;
let mask = 0xff_u8;
let ratio: f64 = 1.5;
let ready: bool = true;

Recognize limits and overflow

Rust

checked_* returns Option, wrapping_* wraps and saturating_* clamps. Ordinary integer overflow checking depends on compilation settings, so use an explicit operation when that behavior is required.

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+
let n = u8::MAX;

let checked = n.checked_add(1);   // None
let wrapped = n.wrapping_add(1);  // 0
let capped = n.saturating_add(1); // 255

Read arithmetic, comparisons and bit operations

Rust

Integer division truncates toward zero. == uses PartialEq; bitwise operators work on integer types. ! negates bool or complements integer bits. ** is not an exponentiation operator; numeric types have pow methods.

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+
let quotient = 7 / 2; // 3
let square = 3_i32.pow(2);
let enabled = (0b1010_u8 & 0b0010) != 0;

Detect integer overflow: safe integers, math/bits, checked_*, __builtin_add_overflow

Rust

Beyond the limits in Recognize limits and overflow, this shows when to pick each method family and how to turn overflow into an error. Rust treats integer overflow as a program error: plain + - * panic with "attempt to add with overflow" in debug builds, and wrap in release builds unless overflow-checks is enabled in the Cargo profile. To choose the behavior explicitly, every integer type has method families: checked_* returns Option (None on overflow), wrapping_* wraps, saturating_* clamps to MIN/MAX, and overflowing_* returns the wrapped value plus a bool. The Wrapping<T> and Saturating<T> wrappers make that the default for a value's operators.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let n: u8 = 250;

    // checked_*: None on overflow.
    assert_eq!(n.checked_add(10), None);
    assert_eq!(n.checked_add(5), Some(255));

    // wrapping_*: modular arithmetic on purpose (hashes, checksums).
    assert_eq!(n.wrapping_add(10), 4);

    // saturating_*: clamp to the type's bounds (counters, audio samples).
    assert_eq!(n.saturating_add(10), u8::MAX);
    assert_eq!((-100_i8).saturating_sub(100), i8::MIN);

    // overflowing_*: the wrapped value plus a flag.
    assert_eq!(n.overflowing_add(10), (4, true));

    // Propagate overflow as an error with ok_or and ?.
    fn total(items: &[u32]) -> Result<u32, String> {
        items.iter().try_fold(0_u32, |acc, &x| {
            acc.checked_add(x).ok_or(format!("overflow adding {x}"))
        })
    }
    assert_eq!(total(&[1, 2, 3]), Ok(6));
    assert!(total(&[u32::MAX, 1]).is_err());

    // Plain n + 10 would panic here in a debug build ("attempt to add with
    // overflow") and wrap to 4 in a release build, unless overflow-checks is set.
    println!(
        "{:?} {} {}",
        n.checked_add(10),
        n.wrapping_add(10),
        n.saturating_add(10)
    );
}

In practice: use checked_* with ok_or / ? for untrusted input and sums of external data, saturating_* for counters and gauges, and wrapping_* for hashes and checksums. Do not rely on release-mode wrapping; if you want wrapping, say so in the code.

Set overflow-checks = true under [profile.release] in Cargo.toml to keep the debug-build panics in release, at a small runtime cost.

An overflow the compiler can see, such as let n: u8 = 250; n + 10, is rejected at compile time by the deny-by-default arithmetic_overflow lint.

Divide integers and take remainders: / and %, Math.trunc, rem_euclid, divide by zero

Rust

Beyond the operator summary in Read arithmetic, comparisons and bit operations, this covers negative remainders, div_euclid and rem_euclid, and the divisions that panic. Integer division truncates toward zero and % is a remainder with the dividend's sign: -7 / 2 is -3 and -7 % 3 is -1. div_euclid and rem_euclid give Euclidean results, where the remainder is never negative. Mixing integers and floats is a compile error, so float division needs as or From. Integer division by zero panics, and so does i32::MIN / -1 (it overflows); checked_div and checked_rem return None for both. Float division by zero gives inf or NaN.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The asserts spell out each rule on constants, which Clippy flags; allow it here.
#[allow(clippy::eq_op, clippy::zero_divided_by_zero)]
fn main() {
    // Integer division truncates toward zero; % keeps the dividend's sign.
    assert_eq!(7 / 2, 3);
    assert_eq!(-7 / 2, -3);
    assert_eq!(-7 % 3, -1);

    // Euclidean division: the remainder is never negative.
    assert_eq!((-7_i32).div_euclid(3), -3);
    assert_eq!((-7_i32).rem_euclid(3), 2);
    assert_eq!((-1_i32).rem_euclid(24), 23);

    // Float division and conversion are explicit.
    let (a, b) = (7_i32, 2_i32);
    assert_eq!(a as f64 / b as f64, 3.5);
    assert_eq!((-7.0_f64 / 2.0).floor(), -4.0);

    // Integer divide by zero panics; checked_div returns None instead.
    // It also catches i32::MIN / -1, which overflows.
    assert_eq!(7_i32.checked_div(0), None);
    assert_eq!(i32::MIN.checked_div(-1), None);
    assert_eq!(7_i32.checked_rem(0), None);
    assert_eq!(7_i32.checked_div(2), Some(3));

    // Float divide by zero gives inf or NaN.
    assert!((1.0_f64 / 0.0).is_infinite());
    assert!((0.0_f64 / 0.0).is_nan());

    println!(
        "{} {} {} {:?}",
        -7 / 2,
        -7 % 3,
        (-7_i32).rem_euclid(3),
        7_i32.checked_div(0)
    );
}

In practice: use rem_euclid for wrap-around indexes and time-of-day arithmetic, checked_div when the divisor comes from input, and floor() on f64 for floor division.

Dividing by a literal 0 is rejected at compile time by the unconditional_panic lint; the panic only happens with runtime values.

NonZeroU32 and friends encode "not zero" in the type, so a division by one of them needs no check.

Convert between numeric types: Math.trunc, T(x), as + TryFrom, static_cast

Rust

Beyond the type list in Choose a numeric type, this covers as, From and TryFrom, and which one each conversion calls for. Rust never converts numbers implicitly. as is the infallible cast: integer to integer keeps the low bits (300_i32 as u8 is 44), and float to integer truncates toward zero and saturates at the target's bounds, with NaN becoming 0 (defined since Rust 1.45). From covers conversions that cannot lose information (i64::from(x_i32), f64::from(x_i32)), and TryFrom / try_into return a Result for narrowing that can fail.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[allow(clippy::cast_nan_to_int)] // NaN as i32 is shown on purpose
fn main() {
    // `as` between integers truncates to the low bits: never an error.
    assert_eq!(300_i32 as u8, 44);
    assert_eq!(-1_i32 as u32, u32::MAX);

    // `as` from float to int truncates toward zero and saturates (Rust 1.45+);
    // NaN becomes 0.
    assert_eq!(-2.7_f64 as i32, -2);
    assert_eq!(1e10_f64 as i32, i32::MAX);
    assert_eq!(-1.0_f64 as u8, 0);
    assert_eq!(f64::NAN as i32, 0);

    // Lossless widening has From; use it instead of `as` so a later type change
    // that makes it lossy fails to compile.
    let wide: i64 = i64::from(7_i32);
    let as_float = f64::from(7_i32);

    // Narrowing that can fail: TryFrom / try_into return a Result.
    let ok: Result<u8, _> = u8::try_from(200_i32);
    let too_big: Result<u8, _> = 300_i32.try_into();
    let negative = u32::try_from(-1_i64);
    assert_eq!(ok, Ok(200));
    assert!(too_big.is_err() && negative.is_err());

    // Explicit saturation for integers: clamp, then convert.
    let clamped = 300_i32.clamp(0, 255) as u8;
    assert_eq!(clamped, 255);

    // i64 -> f64 rounds above 2^53.
    let n: i64 = (1 << 53) + 1;
    assert_ne!(n as f64 as i64, n);

    println!("{wide} {as_float} {ok:?} {too_big:?} {clamped}");
}

In practice: prefer From and TryFrom over as, so a later type change that makes a conversion lossy becomes a compile error or a handled Err. Keep as for deliberate bit truncation and float-to-int casts where saturation is the behavior you want.

There is no From<i64> for f64, because large i64 values do not fit exactly in f64; as is the only built-in way and it rounds.

clippy's cast_possible_truncation and cast_sign_loss lints flag risky as casts if you want them reviewed.

Compare floats and keep money in integer cents: EPSILON, math.IsNaN, total_cmp, std::signbit

Rust

Beyond the type list in Choose a numeric type and the decimal libraries in Big numbers & decimals, this covers comparing and sorting floats, NaN, negative zero and keeping money in integer cents. f64 and f32 are IEEE 754 binary floats, so 0.1 + 0.2 != 0.3. Because NaN != NaN, floats implement PartialEq and PartialOrd but not Eq or Ord: they cannot be HashMap keys or sorted with sort() directly. f64::total_cmp provides the IEEE total order (negative NaN, -inf, ..., -0.0, +0.0, ..., inf, NaN) for sorting. f64::EPSILON is the gap between 1.0 and the next value. -0.0 == 0.0, while is_sign_negative shows the sign.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn nearly_equal(a: f64, b: f64) -> bool {
    let (rel, abs) = (1e-9, 1e-12);
    (a - b).abs() <= (rel * a.abs().max(b.abs())).max(abs)
}

#[allow(clippy::eq_op)] // nan != nan is the point of the example
fn main() {
    let x = 0.1_f64 + 0.2;
    assert_ne!(x, 0.3);
    assert!(nearly_equal(x, 0.3));
    println!("{x} epsilon {}", f64::EPSILON);

    // NaN != NaN, so f64 is PartialEq/PartialOrd but not Eq/Ord.
    let nan = f64::NAN;
    assert!(nan != nan && nan.is_nan());

    // Sorting floats: total_cmp gives a total order (NaN sorts last, -0 before +0).
    let mut v = vec![2.5, f64::NAN, -1.0, 0.0, -0.0];
    v.sort_by(|a, b| a.total_cmp(b));
    println!("{v:?}"); // [-1.0, -0.0, 0.0, 2.5, NaN]

    // -0.0 == 0.0, but the sign is still there.
    assert!(-0.0_f64 == 0.0 && (-0.0_f64).is_sign_negative());

    // Money: integer cents, round once.
    let total_cents: i64 = 1999 * 3;
    let tax = (total_cents as f64 * 825.0 / 10_000.0).round() as i64;
    let all = total_cents + tax;
    assert_eq!(all, 6492);
    println!("total: {}.{:02}", all / 100, all % 100);
}

In practice: compare with a relative plus absolute tolerance, sort with sort_by(|a, b| a.total_cmp(b)), and keep money in integer cents or a decimal crate. Wrap floats in a newtype that rejects NaN when you need Eq or Hash.

rust_decimal (1.43.0) provides a 96-bit decimal type for money; the ordered-float crate provides NaN-free float wrappers that implement Ord and Hash.

f64::round rounds half away from zero; round_ties_even rounds half to even (banker's rounding).

Parse and format numbers: Number + Intl.NumberFormat, strconv + fmt, parse + format!, from_chars + std::format

Rust

Beyond the basic calls in Text ↔ number conversion and Printing & formatting, this covers parse error kinds, and output width, precision, rounding and separators. str::parse::<T>() is the parser for every numeric type, through the FromStr trait. It is strict: no surrounding whitespace, no trailing characters, and range checked against T. Errors are ParseIntError or ParseFloatError; ParseIntError::kind() returns an IntErrorKind such as Empty, InvalidDigit or PosOverflow. from_str_radix parses other bases. Formatting uses format! and println! specs: {:.2} precision, {:5} width, {:<5} alignment, {:05} zero padding, {:#x} and {:08b} for hex and binary.

Complete program

Complete program.

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

// Rust's std has no locale formatting; this inserts thousands separators.
fn group(n: i64) -> String {
    let digits = n.unsigned_abs().to_string();
    let mut out = String::new();
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(c);
    }
    if n < 0 { format!("-{out}") } else { out }
}

fn main() {
    // str::parse needs the target type and returns a Result.
    let n: i64 = "42".parse().unwrap();
    assert_eq!(n, 42);
    assert!("12px".parse::<i64>().is_err());
    assert!(" 42".parse::<i64>().is_err()); // no whitespace: trim() first
    assert_eq!(" 42 ".trim().parse::<i64>(), Ok(42));

    // The error says why it failed.
    let err: ParseIntError = "300".parse::<u8>().unwrap_err();
    assert_eq!(err.kind(), &IntErrorKind::PosOverflow);
    assert_eq!("".parse::<u8>().unwrap_err().kind(), &IntErrorKind::Empty);

    // Other bases.
    assert_eq!(i64::from_str_radix("ff", 16), Ok(255));
    let x: f64 = "2.5".parse().unwrap();

    // Formatting: precision, width, alignment, zero padding, hex.
    assert_eq!(format!("{:.2}", 2.34567), "2.35");
    assert_eq!(
        format!("[{:5}] [{:<5}] [{:05}] [{:>8.3}]", 42, 42, 42, x),
        "[   42] [42   ] [00042] [   2.500]"
    );
    assert_eq!(format!("{:#x} {:08b}", 255, 5), "0xff 00000101");
    assert_eq!(group(-1234567), "-1,234,567");

    // Rounding to 2 decimals: {:.2} rounds an exact tie (0.125 is exact in binary)
    // to even, while f64::round rounds half away from zero.
    assert_eq!(format!("{:.2} {:.0}", 0.125, 2.5), "0.12 2");
    assert_eq!((0.125_f64 * 100.0).round() / 100.0, 0.13);

    println!("{n} {x:.2} {} {err}", group(1234567));
}

In practice: trim() before parse when input comes from users or files, and map the error with ? into your own error type. std has no locale-aware formatting or thousands separators; write a helper or use a crate such as num-format. When rounding to 2 decimals, {:.2} rounds an exact tie such as 0.125 to even (0.12) while (x * 100.0).round() / 100.0 rounds it away from zero (0.13), so choose one rule for money and apply it to integer cents.

A leading + is accepted ("+42".parse::<i64>() is Ok(42)), and underscores are not.

Float formatting with {} prints the shortest string that parses back to the same value, so 0.1 + 0.2 prints 0.30000000000000004.

Use integers wider than 64 bits: BigInt, math/big, u128, unsigned __int128

Rust

Beyond the overview in Big numbers & decimals, this shows how far the built-in u128 goes and how to detect when it runs out. The standard library goes up to 128-bit integers (i128, u128) and has no arbitrary-precision type. u128 holds up to about 3.4 x 10^38 (39 digits), which covers the full product of two u64 values and factorials up to 34!. Beyond that you need a crate. checked_mul and friends tell you exactly when u128 runs out, and parse::<u128>() returns an error for numbers that do not fit.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The standard library stops at 128-bit integers; beyond that use a crate
// such as num-bigint. This shows how far u128 goes and how to detect the end.
fn factorial(n: u32) -> Option<u128> {
    (2..=n as u128).try_fold(1_u128, |acc, i| acc.checked_mul(i))
}

fn main() {
    println!("u128::MAX = {}", u128::MAX); // 39 digits

    let f30 = factorial(30).unwrap();
    assert_eq!(f30, 265_252_859_812_191_058_636_308_480_000_000);

    // 34! fits, 35! does not.
    assert!(factorial(34).is_some());
    assert_eq!(factorial(35), None);

    // Parsing and formatting work like the smaller types.
    let n: u128 = "123456789012345678901234567890".parse().unwrap();
    assert_eq!(n + 1, 123456789012345678901234567891);
    assert!("1".repeat(40).parse::<u128>().is_err());

    // Exact multiply of two u64 values without overflow.
    let wide = u64::MAX as u128 * u64::MAX as u128;
    println!("30! = {f30}\nu64::MAX^2 = {wide}");
}

In practice: use u128 / i128 for exact wide intermediates, such as multiplying two u64 values or summing many i64 amounts, and reach for num-bigint when inputs are unbounded. Keep the overflow checks either way, so the limit fails loudly.

num-bigint (0.5.1) provides BigInt and BigUint; add it with cargo add num-bigint. dashu and rug (GMP bindings) are faster alternatives.

u128 and i128 are 16-byte aligned on x86_64 since Rust 1.77, which matters only for FFI with C's __int128.