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>

Go

os is Go's interface to the operating system: Args, Getenv and LookupEnv, Exit, Getwd, the Stdin/Stdout/Stderr files, and file functions (Open, Create, ReadFile, WriteFile, MkdirAll, Remove). Failures come back as error values. os.Exit ends the program at once and skips deferred calls.

Complete program

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

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "fmt"
    "os"
)

func main() {
    args := os.Args[1:] // os.Args[0] is the program path
    port, ok := os.LookupEnv("PORT")
    if !ok {
        port = "3000"
    }

    wd, err := os.Getwd()
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1) // exits immediately; deferred calls do not run
    }
    fmt.Println("args:", args, "port:", port, "cwd:", wd)
}

Most used: os.Args, os.LookupEnv, os.Getenv, os.Exit, os.Getwd. Related packages: flag parses options, os/exec runs other programs, os/signal handles Ctrl-C.

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

Go

Go splits this between os (ReadFile, WriteFile, Open, Create, MkdirAll, ReadDir, Remove) and path/filepath (Join, Base, Ext, Dir, Abs, WalkDir), which uses the operating system's separator. The plain path package is for slash-separated paths such as URLs. Files from os.Open and os.Create are *os.File values that implement io.Reader and io.Writer; close them when done, and check the error from Close on files you write (a failed Close can mean lost data), or use os.WriteFile. os.Root (Go 1.24) confines access to one directory tree.

Complete program

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

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    dir := filepath.Join("data", "reports") // platform separator
    if err := os.MkdirAll(dir, 0o755); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    file := filepath.Join(dir, "today.txt")
    if err := os.WriteFile(file, []byte("total: 3\n"), 0o644); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    data, err := os.ReadFile(file)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println(filepath.Base(file), filepath.Ext(file), string(data))
}

Most used: os.ReadFile, os.WriteFile, os.Open, os.Create, os.MkdirAll, os.ReadDir, filepath.Join, filepath.WalkDir.

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

Go

//go:embed bakes files into the binary at build time: into a string or []byte for one file, or an embed.FS for many, which implements io/fs.FS. Patterns are relative to the package directory and cannot contain .. or start with /, so the files must live in or below it. io/fs gives one interface to embedded files, os.DirFS directories and zip archives, with fs.WalkDir, fs.Glob and fs.ReadFile working on all of them. os.MkdirTemp and os.CreateTemp make uniquely named temporary directories and files ("" means os.TempDir()), which you remove yourself. filepath.Glob matches one directory level (no **). Watching needs the third-party fsnotify, and os.Executable finds files installed next to the binary.

Complete program

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

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "embed"
    "fmt"
    "io/fs"
    "os"
    "path/filepath"
    "strings"
)

//go:embed main.go
var source string // this file's text, baked into the binary

//go:embed *.go
var sources embed.FS // a read-only file system of the matching files

func main() {
    first, _, _ := strings.Cut(source, "\n")
    names, _ := fs.Glob(sources, "*.go")
    fmt.Println(first, names)

    dir, err := os.MkdirTemp("", "reports-") // "" means os.TempDir()
    if err != nil {
        panic(err)
    }
    defer os.RemoveAll(dir) // temp dirs are not cleaned up for you

    for _, name := range []string{"a.csv", "b.csv", "notes.txt", "2026/c.csv"} {
        path := filepath.Join(dir, name)
        if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
            panic(err)
        }
        if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
            panic(err)
        }
    }

    top, _ := filepath.Glob(filepath.Join(dir, "*.csv")) // one level only: no **
    fmt.Println(len(top))
    fs.WalkDir(os.DirFS(dir), ".", func(path string, d fs.DirEntry, err error) error {
        if err == nil && !d.IsDir() && filepath.Ext(path) == ".csv" {
            fmt.Println(path) // lexical order, slash-separated
        }
        return err
    })
}

Most used: //go:embed name with a string, []byte or embed.FS variable, fs.ReadFile, fs.WalkDir, os.DirFS, os.MkdirTemp, os.CreateTemp, filepath.Glob, t.TempDir() in tests, fsnotify.NewWatcher.

A //go:embed directive must sit directly above a package-level var, and the file must import embed (import _ "embed" when only string or []byte variables use it).

Embedding a directory skips files whose names start with . or _ unless the pattern uses the all: prefix, as in //go:embed all:static.

In tests, t.TempDir() creates a directory that is removed automatically when the test ends.

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

Go

io defines the two interfaces nearly everything uses: io.Reader (read bytes in) and io.Writer (write bytes out). Files, network connections, HTTP bodies, buffers and os.Stdin all implement them, so helpers like io.Copy and io.ReadAll work with any of them. bufio adds buffering: bufio.Scanner reads line by line (lines over 64 KiB fail unless you raise the limit with scanner.Buffer) and bufio.Writer batches small writes (call Flush).

Complete program

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

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

// Read standard input line by line, e.g. `cat numbers.txt | go run .`.
func main() {
    scanner := bufio.NewScanner(os.Stdin)
    total := 0
    for scanner.Scan() {
        n, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
        if err == nil {
            total += n
        }
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println("total:", total)
}

Most used: io.Reader, io.Writer, io.Copy, io.ReadAll, bufio.NewScanner, scanner.Scan/Text/Err, bufio.NewWriter, bytes.Buffer.

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

Go

os/exec runs external programs. exec.Command takes the program and its arguments separately (no shell is involved), Output and CombinedOutput collect output, and Stdin, Stdout and Stderr accept any io.Reader or io.Writer for streaming. CommandContext kills the process when the context is cancelled or times out, and a non-zero exit comes back as *exec.ExitError.

Complete program

Complete program for macOS or Linux.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "bytes"
    "context"
    "fmt"
    "os/exec"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    // Arguments go straight to the program: no shell, no quoting problems.
    out, err := exec.CommandContext(ctx, "go", "version").Output()
    fmt.Printf("%s %v\n", bytes.TrimSpace(out)[:10], err)

    cmd := exec.Command("ls", "-1", "/")
    var stdout bytes.Buffer
    cmd.Stdout = &stdout // any io.Writer
    if err := cmd.Run(); err != nil { // *exec.ExitError carries the exit code
        fmt.Println("failed:", err)
        return
    }
    fmt.Println(bytes.Count(stdout.Bytes(), []byte("\n")) > 0, "entries listed")
}

Most used: exec.Command, exec.CommandContext, Output, CombinedOutput, Run, Start and Wait, cmd.Stdout = w, cmd.Dir, cmd.Env, *exec.ExitError, exec.LookPath.

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

Go

os/signal delivers operating-system signals to the program. signal.NotifyContext returns a context that is cancelled on the chosen signals, which fits servers and workers that already accept a context; signal.Notify sends them on a channel instead. http.Server.Shutdown stops accepting connections and waits for active requests until its context expires.

Complete program

Complete program for macOS or Linux.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "context"
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    // ctx is cancelled on Ctrl-C (SIGINT) or SIGTERM.
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    server := &http.Server{Addr: "127.0.0.1:0"}
    go server.ListenAndServe()

    go func() { // demo: signal ourselves
        time.Sleep(100 * time.Millisecond)
        syscall.Kill(os.Getpid(), syscall.SIGTERM)
    }()

    <-ctx.Done()
    fmt.Println("signal received, shutting down")
    shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    fmt.Println(server.Shutdown(shutdownCtx)) // stop accepting, finish open requests
}

Most used: signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM), <-ctx.Done(), server.Shutdown(ctx), signal.Notify with a channel, signal.Stop.

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

Go

runtime reports on the Go runtime and machine: GOOS, GOARCH, NumCPU, NumGoroutine, Version, memory statistics (ReadMemStats) and GC control. runtime/debug reads build information and tunes the GC, and runtime/pprof writes profiles. reflect inspects types and values at run time, which is how encoding/json reads struct tags; ordinary code rarely needs it. Build constraints (//go:build linux) select per-platform files.

Complete program

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

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "fmt"
    "os"
    "reflect"
    "runtime"
    "runtime/debug"
)

type Order struct {
    ID    int    `json:"id"`
    Notes string `json:"notes,omitempty"`
}

func main() {
    fmt.Println(runtime.GOOS, runtime.GOARCH, runtime.NumCPU() > 0, runtime.NumGoroutine())
    fmt.Println(os.TempDir() != "", runtime.Version()[:2])

    var stats runtime.MemStats
    runtime.ReadMemStats(&stats)
    fmt.Println(stats.HeapAlloc > 0, "bytes of heap in use")

    if info, ok := debug.ReadBuildInfo(); ok { // module path and dependency versions
        fmt.Println(info.Main.Path)
    }

    t := reflect.TypeOf(Order{}) // reflection: inspect a type at run time
    for i := range t.NumField() {
        field := t.Field(i)
        fmt.Println(field.Name, field.Type, field.Tag.Get("json"))
    }
}

Most used: runtime.GOOS, runtime.NumCPU, runtime.Version, runtime.ReadMemStats, debug.ReadBuildInfo, reflect.TypeOf, Field(i).Tag.Get, //go:build constraints.

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

Go

flag parses -name value and -name=value options into typed variables, prints generated help for -h and leaves the remaining arguments in flag.Args(). Both -port and --port are accepted, but short and long aliases for the same option are not built in. flag.NewFlagSet supports subcommands, and spf13/cobra (with pflag) is the common choice for large tools with nested commands.

Complete program

Complete program; try: go run . -port 8080 -verbose orders.csv

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "flag"
    "fmt"
)

func main() {
    port := flag.Int("port", 3000, "port to listen on") // name, default, help text
    verbose := flag.Bool("verbose", false, "log every request")
    var config string
    flag.StringVar(&config, "config", "app.toml", "configuration file")
    flag.Parse() // reads os.Args[1:]; -h prints generated help

    fmt.Println(*port, *verbose, config, flag.Args()) // flag.Args: what is left over
}

Most used: flag.Int, flag.String, flag.Bool, flag.StringVar, flag.Duration, flag.Parse, flag.Args, flag.NewFlagSet, flag.Usage.

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

Go

log is the original logger: it prints timestamped lines to standard error, and log.Fatal exits the program. log/slog (Go 1.21+) is structured logging in the standard library: levels (Debug, Info, Warn, Error), key-value attributes, and handlers that write text or JSON. Libraries should accept a *slog.Logger instead of creating their own.

Complete program

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

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "log"
    "log/slog"
    "os"
)

func main() {
    log.Println("server starting") // classic log: timestamp + message to stderr

    handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
    logger := slog.New(handler)

    logger.Info("order created", "orderId", 7, "total", 40)
    logger.Debug("not shown below the configured level")
    logger.Error("connect failed", "err", os.ErrDeadlineExceeded)
}

Most used: slog.Info, slog.Error, slog.New(slog.NewJSONHandler(os.Stdout, nil)), logger.With, log.Printf, log.Fatal.