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: data & formats

Structured and binary data: JSON and config formats, bytes, encodings, regular expressions, hashing and cryptography, compression, SQL databases, URLs and templates. Entries outside the standard library name what to install.

JSON: JSON, encoding/json, serde_json, nlohmann/json

Rust

The standard library has no JSON support. The usual choice is two crates: serde, a general serialization framework whose derive macros (#[derive(Serialize, Deserialize)]) generate the conversion code, and serde_json for the JSON format (from_str, to_string, to_string_pretty and the json! macro). Unknown fields are ignored unless the struct has #[serde(deny_unknown_fields)]. Decoding checks types and required fields, so a parsed struct has the shape you declared.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add serde --features derive && cargo add serde_json

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Order {
    id: u32,
    items: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    note: Option<String>, // a missing field becomes None
}

fn main() -> Result<(), serde_json::Error> {
    let order: Order = serde_json::from_str(r#"{"id": 7, "items": ["bolt", "nut"]}"#)?;
    println!("{} {}", order.id, order.items.len());

    let out = serde_json::to_string(&Order { id: 8, items: vec![], note: None })?;
    println!("{out}");
    Ok(())
}

Most used: #[derive(Serialize, Deserialize)], serde_json::from_str, serde_json::to_string, to_string_pretty, json!, serde_json::Value for untyped data, #[serde(rename = "...")].

Config formats (TOML, YAML, XML, protobuf): yaml, encoding/xml, serde + toml, toml++

Rust

serde handles every format: derive Serialize and Deserialize once, then pick a format crate. toml (from_str, to_string, to_string_pretty) is the one Cargo itself uses; quick-xml reads and writes XML, with serde support behind its serialize feature; prost generates protobuf structs from .proto files in a build script. For YAML, serde_yaml is deprecated and unmaintained, and so is its fork serde_yml; serde-saphyr and serde_norway (a serde_yaml fork) are the alternatives to evaluate. Deserializing checks types and required fields, so a parsed struct has the shape you declared.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add toml serde --features serde/derive

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct Config {
    name: String,
    port: u16,
    tags: Vec<String>,
    db: Database, // the [db] table
}

#[derive(Debug, Deserialize, Serialize)]
struct Database {
    url: String,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let text = r#"
name = "orders"
port = 8080 # comments are allowed
tags = ["api", "internal"]

[db]
url = "postgres://localhost/orders"
"#;
    let mut config: Config = toml::from_str(text)?; // checks types and required keys
    println!("{} {} {:?} {}", config.name, config.port + 1, config.tags, config.db.url);

    config.port = 9090;
    print!("{}", toml::to_string(&config)?);

    let wrong = toml::from_str::<Config>("name = 1"); // wrong type and missing keys
    println!("{}", wrong.is_err());
    Ok(())
}

Most used: #[derive(Deserialize, Serialize)], toml::from_str, toml::to_string, #[serde(default)], #[serde(rename_all = "kebab-case")], toml::Table for untyped data, quick_xml::de::from_str, prost::Message::encode and decode.

Unknown keys are ignored unless the struct has #[serde(deny_unknown_fields)], which is worth adding for config files so a misspelled key is an error instead of a silent default.

toml::from_str and to_string drop comments and layout. To change a value in a hand-written file and keep the rest, edit it with the toml_edit crate (DocumentMut) instead.

Bytes & binary data: Uint8Array, encoding/binary, Vec<u8>, std::byte

Rust

Owned bytes are Vec<u8> and borrowed bytes are &[u8]; byte-string literals are written b"...". Integer types convert to and from fixed-size byte arrays in a chosen order (to_be_bytes, from_le_bytes), and String::from_utf8 checks that bytes are valid text. The bytes crate (cheaply cloneable Bytes and BytesMut) is common in networking code.

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 data = "héllo".as_bytes(); // &[u8] view of the UTF-8 bytes
    println!("{} {:x} {}", data.len(), data[1], data.ends_with(b"llo"));

    let mut header = [0u8; 8];
    header[0..4].copy_from_slice(&0xcafebabe_u32.to_be_bytes()); // big-endian
    header[4..6].copy_from_slice(&513_u16.to_le_bytes()); // little-endian
    let hex: Vec<String> = header.iter().map(|b| format!("{b:02x}")).collect();
    println!("{}", hex.join(" "));

    let mut buffer: Vec<u8> = Vec::new(); // growable bytes
    buffer.extend_from_slice(b"id:");
    buffer.push(42);
    let first = u32::from_be_bytes([header[0], header[1], header[2], header[3]]);
    println!("{buffer:?} {first:x} {}", String::from_utf8_lossy(data));
}

Most used: Vec<u8>, &[u8], b"...", as_bytes, to_be_bytes, from_le_bytes, copy_from_slice, extend_from_slice, String::from_utf8, from_utf8_lossy.

Base64, hex & CSV: Buffer, encoding/*, base64/hex/csv crates, OpenSSL

Rust

The standard library has none of these encodings. The usual crates are base64 (pick an Engine such as STANDARD or URL_SAFE, or URL_SAFE_NO_PAD without padding, to encode and decode), hex, and csv, which reads and writes records, handles quoting and, with serde, deserializes rows straight into structs.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add base64 hex csv

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let raw = b"id=7&ok";
    println!("{} {}", STANDARD.encode(raw), URL_SAFE.encode(raw));
    println!("{}", hex::encode(raw));

    let decoded = STANDARD.decode("aWQ9NyZvaw==")?;
    println!("{}", String::from_utf8(decoded)?);

    let data = "name,qty\n\"bolt, large\",3\nnut,10\n";
    let mut reader = csv::Reader::from_reader(data.as_bytes()); // first row is the header
    for record in reader.records() {
        let record = record?;
        println!("{} x{}", &record[0], &record[1]);
    }
    Ok(())
}

Most used: STANDARD.encode, STANDARD.decode, URL_SAFE_NO_PAD, hex::encode, hex::decode, csv::Reader::from_path, records, deserialize, csv::Writer.

Regular expressions: RegExp, regexp, regex crate, <regex>

Rust

Regular expressions are not in the standard library; the regex crate is the standard choice. Like Go's regexp it guarantees linear-time matching and leaves out backreferences and lookarounds (fancy-regex adds them). Compile with Regex::new (keep it in a static LazyLock to reuse it), then use is_match, find, captures, captures_iter and replace_all. Raw strings r"..." avoid double escaping.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add regex

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

static FIELD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(\w+)=([\w.]+)").unwrap()); // compiled once

fn main() {
    let line = "order=7 total=40.50 status=paid";

    for caps in FIELD.captures_iter(line) {
        println!("{} {}", &caps[1], &caps[2]);
    }
    let total = Regex::new(r"total=(?<amount>\d+\.\d{2})").unwrap();
    let amount = total.captures(line).map(|c| c["amount"].to_string());
    println!("{amount:?} {}", FIELD.is_match(line));
    println!("{}", Regex::new(r"\d+").unwrap().replace_all(line, "#"));
}

Most used: Regex::new, is_match, find, captures, captures_iter, named groups (?<name>...), replace_all, LazyLock<Regex> statics.

Hashing & cryptography: node:crypto, crypto/*, RustCrypto, OpenSSL

Rust

The standard library has no cryptography. The RustCrypto crates are the common pure-Rust choice: sha2 (SHA-256), hmac, aes-gcm and argon2 for passwords, all sharing traits such as Digest, Mac and KeyInit (import KeyInit for new_from_slice since hmac 0.13); ed25519-dalek (from the dalek project) covers Ed25519 signatures. ring (derived from BoringSSL) and aws-lc-rs (wrapping AWS-LC, the default provider for rustls) are the main alternatives. rand (or getrandom) supplies secure random bytes. std::hash is only for HashMap keys and is not cryptographic.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add sha2 hmac hex rand

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use hmac::{Hmac, KeyInit, Mac};
use sha2::{Digest, Sha256};

type HmacSha256 = Hmac<Sha256>;

fn main() {
    let digest = Sha256::digest(b"order:7");
    println!("{}", &hex::encode(digest)[..16]); // checksums, cache keys

    let key: [u8; 32] = rand::random(); // a shared secret key
    let mut mac = HmacSha256::new_from_slice(&key).expect("HMAC accepts any key length");
    mac.update(b"order:7");
    let tag = mac.finalize().into_bytes();

    let mut check = HmacSha256::new_from_slice(&key).expect("HMAC accepts any key length");
    check.update(b"order:7");
    println!("{}", check.verify_slice(&tag).is_ok()); // constant-time check
}

Most used: Sha256::digest, Hmac::<Sha256>::new_from_slice, update, finalize, verify_slice, rand::random, argon2::Argon2, aes_gcm::Aes256Gcm.

Compression & archives: node:zlib, compress/* + archive/*, flate2, zlib

Rust

The standard library has no compression. flate2 handles gzip, zlib and raw deflate through encoder and decoder types that wrap any Read or Write, so they work with files and sockets. The zip and tar crates read and write archives, zstd, brotli and lz4 cover other formats, and async-compression adapts them to tokio.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add flate2

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use flate2::Compression;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use std::io::{Read, Write};

fn main() -> std::io::Result<()> {
    let text = "order line\n".repeat(1000);

    let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); // wraps any Write
    encoder.write_all(text.as_bytes())?;
    let gz = encoder.finish()?; // writes the gzip footer
    println!("{} {}", text.len(), gz.len());

    let mut decoder = GzDecoder::new(&gz[..]); // wraps any Read
    let mut back = String::new();
    decoder.read_to_string(&mut back)?;
    println!("{}", back == text);
    Ok(())
}

Most used: GzEncoder::new(writer, Compression::default()), write_all, finish, GzDecoder::new(reader), read_to_string or read_to_end, tar::Archive, zip::ZipArchive.

SQL databases: node:sqlite, database/sql, rusqlite/sqlx, SQLite C API

Rust

The standard library has no database support. rusqlite is a synchronous SQLite binding; sqlx is an async driver for PostgreSQL, MySQL and SQLite that can check queries against the database at compile time; tokio-postgres and diesel (an ORM with a query DSL) are the other common choices. Bind values rather than formatting them into SQL: rusqlite uses ?1 placeholders with params!, sqlx uses $1 or ? placeholders with .bind().

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add rusqlite (add --features bundled to compile SQLite in)

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use rusqlite::{Connection, params};

fn main() -> rusqlite::Result<()> {
    let db = Connection::open_in_memory()?; // or Connection::open("items.db")
    db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE)", [])?;

    for name in ["bolt", "nut"] {
        db.execute("INSERT INTO items (name) VALUES (?1)", params![name])?; // bound values
    }

    let mut query = db.prepare("SELECT id, name FROM items WHERE name LIKE ?1")?;
    let rows = query.query_map(["b%"], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)))?;
    for row in rows {
        let (id, name) = row?;
        println!("{id} {name}");
    }
    Ok(())
}

Most used: Connection::open, execute with params!, prepare, query_map, query_row, transaction, sqlx::query!, PgPool::connect.

URLs & query strings: URL, net/url, url crate, Boost.URL

Rust

The standard library has no URL type. The url crate implements the same WHATWG standard as browsers: Url::parse validates, accessors (scheme, host_str, path, query_pairs) read the parts, setters and query_pairs_mut change them with correct encoding, and join resolves relative references. percent-encoding and form_urlencoded (both used by url) handle individual components.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add url

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

fn main() -> Result<(), url::ParseError> {
    let mut url = Url::parse("https://shop.example/orders?status=paid&page=2#top")?;
    let status = url.query_pairs().find(|(k, _)| k == "status").map(|(_, v)| v.into_owned());
    println!("{:?} {} {status:?}", url.host_str(), url.path());

    url.query_pairs_mut().append_pair("q", "bolt & nut"); // encodes the value
    url.set_path("/orders/7");
    println!("{url}");

    let base = Url::parse("https://shop.example/api/")?;
    println!("{}", base.join("items?id=7")?); // resolve a relative reference
    Ok(())
}

Most used: Url::parse, host_str, path, query_pairs, query_pairs_mut().append_pair, set_path, join, percent_encoding::utf8_percent_encode.

Text templates: template literals, text/template, minijinja, std::format

Rust

The standard library has format! but no template engine. minijinja (Jinja2 syntax, templates loaded at runtime) and askama (Jinja-like templates compiled into Rust code and type-checked at build time) are the common choices, with tera as an older runtime engine. Each escapes HTML automatically for .html templates.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add minijinja

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use minijinja::{Environment, context};

const ORDER: &str = r#"<h1>Order {{ id }}</h1>
<ul>
{% for item in items %}  <li>{{ item.name }} × {{ item.qty }}</li>
{% endfor %}</ul>"#;

fn main() -> Result<(), minijinja::Error> {
    let mut env = Environment::new();
    env.add_template("order.html", ORDER)?; // the .html name turns on HTML escaping
    let page = env.get_template("order.html")?;

    let items = vec![context! { name => "bolt <M8>", qty => 3 }];
    println!("{}", page.render(context! { id => 7, items })?);
    Ok(())
}

Most used: Environment::new, add_template, get_template, render(context! { ... }), {{ value }}, {% for %}, {% if %}, #[derive(Template)] with askama.