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

Go

encoding/json maps JSON to Go values: Marshal encodes, Unmarshal decodes into a pointer, and json.NewDecoder and NewEncoder stream from an io.Reader or to an io.Writer (an HTTP body, a file). Only exported (capitalized) struct fields are included, and struct tags set the JSON names and options such as omitempty (and omitzero, Go 1.24+, which also works for structs and time.Time). Unknown fields are ignored unless the decoder calls DisallowUnknownFields.

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 (
    "encoding/json"
    "fmt"
)

type Order struct {
    ID    int      `json:"id"` // struct tags name the JSON fields
    Items []string `json:"items"`
    Note  string   `json:"note,omitempty"`
}

func main() {
    var order Order
    err := json.Unmarshal([]byte(`{"id": 7, "items": ["bolt", "nut"]}`), &order)
    if err != nil {
        fmt.Println("bad JSON:", err)
        return
    }
    fmt.Println(order.ID, len(order.Items))

    out, err := json.Marshal(Order{ID: 8, Items: []string{}})
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(out))
}

Most used: json.Marshal, json.Unmarshal, json.NewDecoder(r.Body).Decode, json.NewEncoder(w).Encode, `json:"name,omitempty"` tags, json.RawMessage.

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

Go

encoding/xml is in the standard library and works like encoding/json: struct tags map elements and attributes, Unmarshal and Marshal (or MarshalIndent) convert whole documents, and xml.NewDecoder with Token streams large ones. TOML, YAML and protobuf are modules: BurntSushi/toml or pelletier/go-toml/v2 for TOML; go.yaml.in/yaml/v3 (the YAML organization's maintained continuation of the archived gopkg.in/yaml.v3, with v4 newly released) or goccy/go-yaml for YAML; google.golang.org/protobuf with protoc-gen-go for protobuf. All of them follow the same Marshal and Unmarshal pattern with struct tags.

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 (
    "encoding/xml"
    "fmt"
)

type Server struct {
    XMLName xml.Name `xml:"server"`
    Name    string   `xml:"name,attr"` // <server name="...">
    Port    int      `xml:"port"`
    Tags    []string `xml:"tags>tag"` // <tags><tag>...</tag></tags>
}

func main() {
    input := `<server name="orders"><port>8080</port><tags><tag>api</tag><tag>internal</tag></tags></server>`

    var s Server
    if err := xml.Unmarshal([]byte(input), &s); err != nil {
        panic(err)
    }
    fmt.Println(s.Name, s.Port+1, s.Tags)

    s.Port = 9090
    out, err := xml.MarshalIndent(s, "", "  ")
    if err != nil {
        panic(err)
    }
    fmt.Println(xml.Header + string(out)) // Header is the <?xml ...?> line
}

Most used: xml.Unmarshal, xml.MarshalIndent, `xml:"name,attr"` and `xml:"a>b"` tags, xml.Header, toml.Decode, yaml.Unmarshal, proto.Marshal and proto.Unmarshal.

Unknown elements and attributes are ignored and missing ones leave the zero value, so a typo in a tag silently drops data; test a round trip.

gopkg.in/yaml.v3 is archived. Its import path still works, but new code should use go.yaml.in/yaml/v3, a drop-in replacement.

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

Go

[]byte is the type for binary data, and converting between string and []byte copies the bytes. The bytes package mirrors strings for byte slices (Contains, Split, Equal, TrimSpace) and adds bytes.Buffer, a growable buffer that is both an io.Reader and an io.Writer. encoding/binary reads and writes fixed-size numbers in big- or little-endian order, plus varints.

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 (
    "bytes"
    "encoding/binary"
    "fmt"
)

func main() {
    data := []byte("héllo") // a string converts to its UTF-8 bytes
    fmt.Println(len(data), data[1], bytes.Contains(data, []byte("llo")))

    header := make([]byte, 8)
    binary.BigEndian.PutUint32(header[0:], 0xcafebabe)
    binary.LittleEndian.PutUint16(header[4:], 513)
    fmt.Printf("% x\n", header)

    var buf bytes.Buffer // growable; both an io.Reader and an io.Writer
    buf.WriteString("id:")
    buf.WriteByte(42)
    fmt.Println(buf.Bytes(), binary.BigEndian.Uint32(header), string(data))
}

Most used: []byte(s), string(b), bytes.Buffer, bytes.Equal, bytes.Contains, binary.BigEndian.PutUint32, binary.LittleEndian.Uint16, binary.Read and binary.Write.

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

Go

The encoding packages cover the common text forms of bytes and records: encoding/base64 (StdEncoding, URLEncoding, and Raw variants without padding), encoding/hex, encoding/csv (a reader and writer that handle quoting) and encoding/pem. encoding/binary handles fixed-size numbers, and encoding/xml follows the same Marshal and Unmarshal style as encoding/json.

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 (
    "encoding/base64"
    "encoding/csv"
    "encoding/hex"
    "fmt"
    "os"
    "strings"
)

func main() {
    raw := []byte("id=7&ok")
    fmt.Println(base64.StdEncoding.EncodeToString(raw), base64.URLEncoding.EncodeToString(raw))
    fmt.Println(hex.EncodeToString(raw))

    decoded, err := base64.StdEncoding.DecodeString("aWQ9NyZvaw==")
    fmt.Println(string(decoded), err)

    reader := csv.NewReader(strings.NewReader("name,qty\n\"bolt, large\",3\nnut,10\n"))
    records, err := reader.ReadAll() // handles quoted fields that contain commas
    fmt.Println(records, err)

    writer := csv.NewWriter(os.Stdout)
    writer.Write([]string{"note", `has "quotes", commas`})
    writer.Flush()
}

Most used: base64.StdEncoding.EncodeToString, DecodeString, base64.RawURLEncoding, hex.EncodeToString, hex.DecodeString, csv.NewReader, ReadAll, csv.NewWriter, Flush.

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

Go

regexp uses RE2 syntax and guarantees linear-time matching, so it has no backreferences or lookarounds. Compile once with MustCompile (at package level) or Compile (when the pattern comes from input), then use MatchString, FindString, FindAllStringSubmatch and ReplaceAllString. Raw string literals (`...`) avoid double escaping.

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"
    "regexp"
)

var field = regexp.MustCompile(`(\w+)=([\w.]+)`) // compile once, reuse

func main() {
    line := "order=7 total=40.50 status=paid"

    for _, m := range field.FindAllStringSubmatch(line, -1) {
        fmt.Println(m[1], m[2])
    }
    total := regexp.MustCompile(`total=(?P<amount>\d+\.\d{2})`)
    m := total.FindStringSubmatch(line)
    fmt.Println(m[total.SubexpIndex("amount")], field.MatchString(line))
    fmt.Println(regexp.MustCompile(`\d+`).ReplaceAllString(line, "#"))
}

Most used: regexp.MustCompile, MatchString, FindStringSubmatch, FindAllStringSubmatch, SubexpIndex, ReplaceAllString, ReplaceAllStringFunc.

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

Go

The crypto packages are part of the standard library and maintained by the Go team: crypto/sha256 and crypto/sha512 for hashing, crypto/hmac for message authentication codes, crypto/rand for secure random bytes, crypto/aes with crypto/cipher for AES-GCM, crypto/ed25519 and crypto/ecdsa for signatures, and crypto/tls for TLS. Password hashing (bcrypt, argon2) lives in golang.org/x/crypto. hash/fnv and hash/crc32 are fast non-cryptographic hashes.

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 (
    "crypto/hmac"
    "crypto/rand"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
)

func sign(key, message []byte) []byte {
    mac := hmac.New(sha256.New, key)
    mac.Write(message)
    return mac.Sum(nil)
}

func main() {
    sum := sha256.Sum256([]byte("order:7"))
    fmt.Println(hex.EncodeToString(sum[:])[:16]) // checksums, cache keys

    key := make([]byte, 32)
    rand.Read(key) // a shared secret key; never fails since Go 1.24

    signature := sign(key, []byte("order:7"))
    fmt.Println(hmac.Equal(signature, sign(key, []byte("order:7")))) // constant time
}

Most used: sha256.Sum256, hmac.New(sha256.New, key), hmac.Equal, rand.Read, rand.Text, cipher.NewGCM, ed25519.Sign, golang.org/x/crypto/bcrypt.

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

Go

compress/gzip, compress/zlib, compress/flate and compress/bzip2 (decompression only) wrap any io.Writer or io.Reader, so compression slots into files and HTTP bodies without loading everything into memory. archive/zip and archive/tar read and write archives. Writers must be closed to flush the final bytes. Zstandard and Brotli come from third-party packages such as klauspost/compress.

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 (
    "archive/zip"
    "bytes"
    "compress/gzip"
    "fmt"
    "io"
    "strings"
)

func must[T any](value T, err error) T {
    if err != nil {
        panic(err)
    }
    return value
}

func main() {
    text := strings.Repeat("order line\n", 1000)

    var gz bytes.Buffer
    w := gzip.NewWriter(&gz) // compressors are io.Writers
    must(w.Write([]byte(text)))
    must(0, w.Close()) // Close writes the footer; it is required
    fmt.Println(len(text), gz.Len())

    r := must(gzip.NewReader(&gz)) // decompressors are io.Readers
    back := must(io.ReadAll(r))
    fmt.Println(string(back) == text)

    var archive bytes.Buffer
    zw := zip.NewWriter(&archive)
    must(must(zw.Create("orders/today.txt")).Write([]byte(text)))
    must(0, zw.Close())
    zr := must(zip.NewReader(bytes.NewReader(archive.Bytes()), int64(archive.Len())))
    fmt.Println(zr.File[0].Name, archive.Len())
}

Most used: gzip.NewWriter, Close, gzip.NewReader, io.Copy, zip.NewWriter, Create, zip.OpenReader, tar.NewReader, Next.

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

Go

database/sql is the standard interface for SQL databases; a driver package registers itself through a blank import (modernc.org/sqlite or mattn/go-sqlite3, pgx's stdlib adapter for PostgreSQL, go-sql-driver/mysql). sql.Open returns a connection pool. Exec, Query and QueryRow take parameters, rows.Scan copies columns into variables and BeginTx starts a transaction. sqlc and sqlx are common helpers, and pgx can also be used directly for PostgreSQL.

Complete program

Complete program.

Before you use this

database/sql is standard; the driver is a module: go get modernc.org/sqlite

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

import (
    "context"
    "database/sql"
    "fmt"

    _ "modernc.org/sqlite" // registers the "sqlite" driver (pure Go, no cgo)
)

func main() {
    ctx := context.Background()
    db, err := sql.Open("sqlite", ":memory:") // a pool, not a single connection
    if err != nil {
        panic(err)
    }
    defer db.Close()
    db.SetMaxOpenConns(1) // one connection, so every query sees the same in-memory database

    schema := `CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE)`
    if _, err := db.ExecContext(ctx, schema); err != nil {
        panic(err)
    }
    for _, name := range []string{"bolt", "nut"} {
        if _, err := db.ExecContext(ctx, `INSERT INTO items (name) VALUES (?)`, name); err != nil {
            panic(err)
        }
    }

    rows, err := db.QueryContext(ctx, `SELECT id, name FROM items WHERE name LIKE ?`, "b%")
    if err != nil {
        panic(err)
    }
    defer rows.Close()
    for rows.Next() {
        var id int
        var name string
        if err := rows.Scan(&id, &name); err != nil {
            panic(err)
        }
        fmt.Println(id, name)
    }
    if err := rows.Err(); err != nil { // errors during iteration surface here
        panic(err)
    }
}

Most used: sql.Open, rows.Err() after the loop, db.ExecContext, db.QueryRowContext(...).Scan, db.QueryContext with rows.Next and rows.Scan, db.BeginTx, tx.Commit, sql.ErrNoRows.

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

Go

net/url parses URLs into a url.URL struct (Scheme, Host, Path, RawQuery, Fragment) and builds them back with String. Query parameters are url.Values, a map[string][]string with Get, Set, Add and Encode; after changing them, assign Encode() back to RawQuery. ResolveReference resolves relative links, and QueryEscape and PathEscape encode single components.

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"
    "net/url"
)

func main() {
    u, err := url.Parse("https://shop.example/orders?status=paid&page=2#top")
    if err != nil {
        panic(err)
    }
    fmt.Println(u.Hostname(), u.Path, u.Query().Get("status"))

    q := u.Query() // a copy: url.Values is a map[string][]string
    q.Set("q", "bolt & nut")
    u.RawQuery = q.Encode() // write the encoded query back
    u.Path = "/orders/7"
    fmt.Println(u.String())

    base, _ := url.Parse("https://shop.example/api/")
    ref, _ := url.Parse("items?id=7")
    fmt.Println(base.ResolveReference(ref), url.QueryEscape("a b/c"), url.PathEscape("a b/c"))
}

Most used: url.Parse, u.Query(), url.Values Set/Get/Encode, u.RawQuery, u.String(), ResolveReference, url.QueryEscape, url.JoinPath.

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

Go

Go ships two template packages with the same syntax: text/template for any text (configuration files, emails, generated code) and html/template, which escapes values according to where they appear in HTML, CSS, JavaScript or URLs, preventing injection. Templates use {{.Field}} for values, {{range}} and {{if}} for structure and pipelines with functions, and they can be parsed from embedded files with embed and ParseFS.

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 (
    "html/template"
    "os"
)

type Item struct {
    Name string
    Qty  int
}

type Order struct {
    ID    int
    Items []Item
}

var page = template.Must(template.New("order").Parse(`<h1>Order {{.ID}}</h1>
<ul>
{{- range .Items}}
  <li>{{.Name}} × {{.Qty}}</li>
{{- end}}
</ul>
`))

func main() {
    order := Order{ID: 7, Items: []Item{{"bolt <M8>", 3}}}
    if err := page.Execute(os.Stdout, order); err != nil { // escapes HTML by context
        panic(err)
    }
}

Most used: template.Must(template.New(name).Parse(text)), Execute, ExecuteTemplate, {{.Field}}, {{range .Items}}, {{if}}, template.FuncMap, ParseFS with embed.