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: system & OS

The operating system around a program: arguments and environment, files and paths, streams, child processes, signals, platform information, command-line options and logging.

Process, arguments & environment: process, os, std::env, <cstdlib>

Rust

std::env reads the program's surroundings: args(), var() and vars() for environment variables (var returns a Result because a variable can be missing or not valid Unicode), and current_dir(). std::process covers exit status (return ExitCode from main, or call process::exit) and starting other programs with Command.

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::env;
use std::process::ExitCode;

fn main() -> ExitCode {
    let args: Vec<String> = env::args().skip(1).collect(); // first item is the program
    let port = env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    println!("args: {args:?} port: {port}");

    match env::current_dir() {
        Ok(dir) => println!("cwd: {}", dir.display()),
        Err(error) => {
            eprintln!("{error}");
            return ExitCode::FAILURE;
        }
    }
    ExitCode::SUCCESS
}

Most used: env::args, env::var, env::current_dir, process::ExitCode, process::Command. Option parsing beyond a few arguments is usually done with the clap crate.

Files & paths: node:fs, os + path/filepath, std::fs, <filesystem>

Rust

std::fs has whole-file helpers (read_to_string, read, write), directory functions (create_dir_all, read_dir, remove_file) and File for streaming. std::path provides Path (a borrowed path) and PathBuf (an owned one) with join, file_name, extension and parent. Every fallible call returns io::Result, so ? passes errors up.

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::fs;
use std::path::Path;

fn main() -> std::io::Result<()> {
    let dir = Path::new("data").join("reports"); // platform separator
    fs::create_dir_all(&dir)?;

    let file = dir.join("today.txt");
    fs::write(&file, "total: 3\n")?;
    let text = fs::read_to_string(&file)?;

    println!("{:?} {:?}", file.file_name(), file.extension());
    println!("{}", text.trim());
    Ok(())
}

Most used: fs::read_to_string, fs::write, fs::create_dir_all, fs::read_dir, File::open with BufReader, Path::new, PathBuf::join.

Embedding, temp files, globs & watching: fs.glob, embed + os.MkdirTemp, tempfile, #embed

Rust

include_str! and include_bytes! embed a file at compile time, with the path relative to the source file; env!("CARGO_MANIFEST_DIR") gives the crate root, and the include_dir and rust-embed crates embed whole directories. std::env::temp_dir() returns the system temp directory but does not create anything unique: the tempfile crate does, with tempdir() and NamedTempFile, and deletes them when the value is dropped. The glob crate matches patterns such as **/*.csv, walkdir walks trees, and notify (8.x; 9.0 is in release candidates) watches for changes.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add tempfile glob

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

const SOURCE: &str = include_str!("main.rs"); // relative to this file, read at compile time
const MANIFEST: &[u8] = include_bytes!("../Cargo.toml");

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("{} {}", SOURCE.lines().next().unwrap_or(""), MANIFEST.starts_with(b"[package]"));

    let dir = tempfile::tempdir()?; // a fresh directory, deleted when `dir` is dropped
    for name in ["a.csv", "b.csv", "notes.txt", "2026/c.csv"] {
        let path = dir.path().join(name);
        fs::create_dir_all(path.parent().unwrap())?;
        fs::write(&path, "x")?;
    }

    // Escape the literal part so characters like [ in the path are not pattern syntax.
    let root = glob::Pattern::escape(&dir.path().to_string_lossy());
    let mut found = Vec::new();
    for entry in glob::glob(&format!("{root}/**/*.csv"))? {
        found.push(entry?.strip_prefix(dir.path())?.display().to_string());
    }
    found.sort();
    println!("{found:?}");
    Ok(())
}

Most used: include_str!, include_bytes!, env!("CARGO_MANIFEST_DIR"), tempfile::tempdir, NamedTempFile::new, TempDir::keep, glob::glob, glob::Pattern::escape, walkdir::WalkDir, notify::recommended_watcher.

A TempDir is deleted when it is dropped, including on early return with ?, but not when the process exits through std::process::exit or a panic with panic = "abort"; call keep() to hold on to it on purpose.

Escape the directory part of a glob pattern with glob::Pattern::escape: temp and user paths can contain [, ] or *, which would otherwise be read as pattern syntax.

Relative paths in std::fs calls are resolved against the current directory, not the crate; cargo run sets it to wherever you ran the command.

Streams & buffered input: node:readline, io + bufio, std::io, <iostream>

Rust

std::io defines the Read and Write traits for byte input and output, and BufRead for buffered, line-oriented reading. stdin(), stdout() and stderr() return handles; lock() them once for fast repeated access. Files, TCP streams and Vec<u8> implement the same traits, and BufReader/BufWriter add buffering to any of them. Import the traits (BufRead, Write) to call their methods.

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::io::{self, BufRead, Write};

// Read standard input line by line, e.g. `cat numbers.txt | cargo run`.
fn main() -> io::Result<()> {
    let mut total = 0;
    for line in io::stdin().lock().lines() {
        if let Ok(n) = line?.trim().parse::<i64>() {
            total += n;
        }
    }

    let mut out = io::stdout().lock();
    writeln!(out, "total: {total}")?;
    Ok(())
}

Most used: io::stdin().lines(), BufReader::new(file).lines(), read_line, write!/writeln! on a writer, io::copy, io::Result.

Running other programs: child_process, os/exec, std::process::Command, popen

Rust

std::process::Command builds and runs a child process: arg and args add arguments (no shell is involved), current_dir and env configure it, output waits and collects stdout and stderr, status just waits, and spawn returns a Child for streaming through piped stdin and stdout. tokio::process::Command is the async version, and timeouts need either a separate thread or the async version.

Complete program

Complete program for macOS or Linux.

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

fn main() -> std::io::Result<()> {
    // Arguments go straight to the program: no shell, no quoting problems.
    let output = Command::new("rustc").arg("--version").output()?;
    let version = String::from_utf8_lossy(&output.stdout);
    println!("{} {}", &version[..5], output.status);

    let listing = Command::new("ls")
        .args(["-1", "/"])
        .stderr(Stdio::inherit()) // pass errors through to our terminal
        .output()?;
    if !listing.status.success() {
        eprintln!("ls failed: {}", listing.status);
    }
    println!("{} entries listed", !listing.stdout.is_empty());
    Ok(())
}

Most used: Command::new, arg, args, env, current_dir, output, status, spawn, Stdio::piped, child.wait, ExitStatus::success.

Signals & graceful shutdown: process signals, os/signal, tokio::signal, <csignal>

Rust

The standard library cannot handle signals. In async programs tokio::signal provides ctrl_c() and, on Unix, signal(SignalKind::terminate()), which are awaited alongside the main work with tokio::select!; axum's with_graceful_shutdown takes such a future. Synchronous programs use the ctrlc or signal-hook crates.

Complete program

Complete program for macOS or Linux.

Before you use this

Not in the standard library: cargo add tokio --features full

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use tokio::signal::unix::{SignalKind, signal};
use tokio::time::{Duration, sleep};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let mut terminate = signal(SignalKind::terminate())?; // SIGTERM (Unix only)

    tokio::spawn(async {
        // demo: signal ourselves
        sleep(Duration::from_millis(100)).await;
        let pid = std::process::id().to_string();
        let _ = tokio::process::Command::new("kill").args(["-TERM", &pid]).status().await;
    });

    tokio::select! {
        _ = tokio::signal::ctrl_c() => println!("Ctrl-C received"),
        _ = terminate.recv() => println!("SIGTERM received"),
    }
    println!("shutting down"); // close listeners, flush work, then return
    Ok(())
}

Most used: tokio::signal::ctrl_c, signal(SignalKind::terminate()), tokio::select!, CancellationToken, axum::serve(...).with_graceful_shutdown, the ctrlc crate.

Platform info & reflection: node:os, runtime + reflect, cfg/std::mem, <type_traits>

Rust

Rust answers most of these questions at compile time. std::env::consts gives the target OS and architecture, cfg! and #[cfg(...)] select code per platform or build mode, std::mem reports size_of and align_of, and std::any provides type_name and TypeId. At run time, thread::available_parallelism reports usable cores and env::temp_dir the temp directory. The sysinfo crate reads memory and process information.

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::any::type_name; // size_of and align_of are in the prelude (Rust 1.80+)

#[allow(dead_code)]
struct Order {
    id: u32,
    paid: bool,
    total: u64,
}

fn describe<T>(_: &T) -> &'static str {
    type_name::<T>() // the type's name, for debugging
}

fn main() {
    println!("{} {} {}", std::env::consts::OS, std::env::consts::ARCH, cfg!(debug_assertions));
    let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
    println!("{} {}", threads > 0, std::env::temp_dir().is_absolute());

    println!("{} bytes, align {}", size_of::<Order>(), align_of::<Order>()); // layout
    println!("{} {}", describe(&1.5), describe(&"text"));

    #[cfg(target_os = "linux")]
    println!("compiled only on Linux");
}

Most used: std::env::consts::OS, cfg!(target_os = "linux"), #[cfg(test)], size_of, type_name, TypeId, thread::available_parallelism, env::temp_dir, sysinfo.

Command-line options: util.parseArgs, flag, clap, CLI11

Rust

The standard library only provides env::args. clap is the standard crate for command-line parsing: with the derive API a struct describes the options, doc comments become the --help text, values are parsed into the field types, and invalid input produces a clear error and exit code. Subcommands are enums. lexopt and pico-args are minimal alternatives.

Complete program

Complete program; try: cargo run -- --port 8080 -v orders.csv

Before you use this

Not in the standard library: cargo add clap --features derive

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

/// Serve orders from a CSV file.
#[derive(Parser, Debug)]
#[command(version, about)]
struct Args {
    /// Port to listen on
    #[arg(short, long, default_value_t = 3000)]
    port: u16,

    /// Log every request
    #[arg(short, long)]
    verbose: bool,

    /// Input file
    file: String,
}

fn main() {
    let args = Args::parse(); // exits with a helpful message on bad input
    println!("{} {} {}", args.port, args.verbose, args.file);
}

Most used: #[derive(Parser)], #[arg(short, long)], default_value_t, Args::parse(), #[command(subcommand)], ValueEnum.

Logging: console, log/slog, tracing, std::clog

Rust

The standard library has no logger; eprintln! is the built-in fallback. Libraries emit through a facade crate and the application chooses where output goes: log (simple macros such as info!) or tracing (structured fields, plus spans that time units of work). tracing-subscriber prints tracing events (env_logger does the same for the log facade); filtering with RUST_LOG needs tracing-subscriber's env-filter feature and EnvFilter. Nothing is printed until a subscriber is installed.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add tracing tracing-subscriber

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use tracing::{debug, error, info, warn};

fn main() {
    // Nothing is printed until a subscriber is installed.
    tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();

    info!("server starting");
    info!(order_id = 7, total = 40, "order created"); // structured fields
    debug!("not shown below the configured level");
    warn!("cache disabled");
    error!(error = %std::io::Error::other("connect failed"), "request failed");
}

Most used: info!, warn!, error!, debug!, fields like order_id = 7, #[instrument], tracing_subscriber::fmt().init(), RUST_LOG=info with EnvFilter::from_default_env().