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: concurrency & network

Doing several things at once and talking to other machines: threads and tasks, locks and atomics, CPU parallelism, event loops, cancellation, request context, sockets, TLS and HTTP.

Concurrency: Promise, sync + goroutines, std::thread/std::sync, <thread>

Go

Concurrency is built into the language: go f() starts a goroutine, and channels (chan T) pass values between goroutines. The sync package provides WaitGroup (wait for a group), Mutex and RWMutex (protect shared data) and Once; sync/atomic has atomic counters. context carries cancellation and deadlines through call chains, and errgroup (golang.org/x/sync) adds error handling to a WaitGroup.

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"
    "sync"
    "time"
)

func fetchPrice(id int) int {
    time.Sleep(time.Duration(id) * 10 * time.Millisecond) // stands in for I/O
    return id * 100
}

func main() {
    var (
        wg     sync.WaitGroup
        mu     sync.Mutex
        prices = map[int]int{}
    )
    for _, id := range []int{1, 2, 3} {
        wg.Go(func() { // Go 1.25+; older code uses wg.Add(1) and defer wg.Done()
            price := fetchPrice(id) // each iteration has its own id (Go 1.22+)
            mu.Lock()
            prices[id] = price
            mu.Unlock()
        })
    }
    wg.Wait()
    fmt.Println(prices)
}

Most used: go func(), chan, select, sync.WaitGroup with wg.Go (Go 1.25+), sync.Mutex, context.WithTimeout, errgroup.Group. go test -race finds data races.

Locks, atomics & one-time init: Atomics, sync.Once, OnceLock, std::call_once

Go

sync.Mutex guards data shared by goroutines; RWMutex lets many readers in at once and gives writers exclusive access. sync.OnceValue and OnceFunc (Go 1.21+) wrap a function so it runs once, however many goroutines call it, and sync.Once is the older form. sync/atomic has typed atomics (atomic.Int64, atomic.Bool, atomic.Pointer[T]) for counters and flags that do not justify a lock. Keep a mutex next to the fields it guards and lock with defer Unlock so every return path releases it.

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"
    "sync"
    "sync/atomic"
)

type Inventory struct {
    mu    sync.RWMutex // guards stock; share an Inventory by pointer, never copy it
    stock map[string]int
}

func (inv *Inventory) Take(item string) bool {
    inv.mu.Lock()
    defer inv.mu.Unlock()
    if inv.stock[item] == 0 {
        return false
    }
    inv.stock[item]--
    return true
}

func (inv *Inventory) Count(item string) int {
    inv.mu.RLock() // readers share the lock; a writer waits for them
    defer inv.mu.RUnlock()
    return inv.stock[item]
}

var loadRegion = sync.OnceValue(func() string {
    fmt.Println("loading region") // runs once, however many goroutines call it
    return "eu"
})

func main() {
    inv := &Inventory{stock: map[string]int{"widget": 5}}
    var taken atomic.Int64 // a typed atomic: no lock for a simple counter
    var wg sync.WaitGroup
    for range 8 {
        wg.Go(func() {
            loadRegion()
            if inv.Take("widget") {
                taken.Add(1)
            }
        })
    }
    wg.Wait()
    fmt.Println(loadRegion(), "taken:", taken.Load(), "left:", inv.Count("widget"))
}

Most used: sync.Mutex, Lock with defer Unlock, sync.RWMutex RLock, sync.OnceValue, sync.OnceFunc, sync.Once, atomic.Int64 Add and Load, atomic.Bool, atomic.Pointer, CompareAndSwap.

Never copy a Mutex, WaitGroup or a struct holding one after first use: pass pointers. go vet reports copies.

Go mutexes are not reentrant: locking one the same goroutine already holds deadlocks.

When code takes two locks, always take them in the same order everywhere, or two goroutines can deadlock.

go test -race (or go run -race) finds unsynchronised access that tests happen to survive.

CPU parallelism & worker pools: worker_threads, errgroup, rayon, std::jthread

Go

Goroutines already run in parallel on up to GOMAXPROCS operating-system threads (by default the CPU count, and since Go 1.25 a container CPU limit too), so parallel work is just many goroutines. Bound how many run at once: a fixed set of workers reading from a channel, or errgroup.Group from golang.org/x/sync, whose SetLimit caps concurrent g.Go calls and whose Wait returns the first error (WithContext also cancels the others). Give each goroutine its own output slot, or send results over a channel, rather than sharing a locked accumulator.

Complete program

Complete program.

Before you use this

Not in the standard library: go get golang.org/x/sync/errgroup

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

import (
    "context"
    "fmt"
    "runtime"

    "golang.org/x/sync/errgroup"
)

func countPrimes(from, to int) int {
    count := 0
    for n := max(from, 2); n < to; n++ {
        prime := true
        for d := 2; d*d <= n && prime; d++ {
            prime = n%d != 0
        }
        if prime {
            count++
        }
    }
    return count
}

func main() {
    const limit, chunks = 200_000, 16
    counts := make([]int, chunks) // one slot per goroutine: no lock needed
    g, ctx := errgroup.WithContext(context.Background())
    g.SetLimit(runtime.GOMAXPROCS(0)) // at most one running chunk per thread; 0 only reads it
    for i := range chunks {
        g.Go(func() error { // blocks here while the limit is reached
            if err := ctx.Err(); err != nil {
                return err // a sibling failed: skip the work
            }
            size := limit / chunks
            counts[i] = countPrimes(i*size, (i+1)*size)
            return nil
        })
    }
    if err := g.Wait(); err != nil {
        fmt.Println("failed:", err)
        return
    }
    total := 0
    for _, c := range counts {
        total += c
    }
    fmt.Println("primes below", limit, "=", total)
}

Most used: errgroup.Group, errgroup.WithContext, g.SetLimit, g.Go, g.Wait, runtime.GOMAXPROCS(0), runtime.NumCPU, worker goroutines ranging over a jobs channel, sync.WaitGroup.Go.

Unbounded go statements over a large input start one goroutine per item; that is cheap for waiting but wastes memory and gains nothing for CPU work beyond GOMAXPROCS.

Writing to distinct elements of a slice from different goroutines is safe; appending to a shared slice is not.

Event loops & async runtimes: EventEmitter, the Go scheduler, tokio, Asio

Go

Go has no event-loop library because the runtime is the event loop: it schedules goroutines onto operating-system threads and parks them while they wait on network I/O, timers or channels, so blocking-style code is cheap and concurrent. select waits on several channels at once, which is how event-driven code is written; time.Ticker, time.After and ctx.Done() supply timer and cancellation events. GOMAXPROCS sets how many threads run Go code at once.

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

func main() {
    orders := make(chan int)
    drained := make(chan struct{})

    go func() { // the runtime schedules goroutines across OS threads
        for id := range 3 {
            orders <- id + 7
        }
        close(drained)
    }()

    tick := time.NewTicker(time.Millisecond)
    defer tick.Stop()
    for {
        select { // wait on several event sources at once
        case id := <-orders:
            fmt.Println("received", id)
        case <-drained:
            fmt.Println("drained")
            return
        case <-tick.C:
            // periodic work would go here
        }
    }
}

Most used: go statements, chan, select, time.Ticker, time.After, ctx.Done(), runtime.GOMAXPROCS, sync.Cond in rare cases.

Cancellation & deadlines: AbortController, context, CancellationToken, std::stop_token

Go

context carries cancellation, deadlines and request-scoped values through a call chain. Functions that do I/O take ctx context.Context as their first parameter and stop when <-ctx.Done() fires, returning ctx.Err() (context.Canceled or context.DeadlineExceeded). WithCancel, WithTimeout and WithDeadline derive child contexts, and cancelling a parent cancels every child. The standard library's network, HTTP, database and exec APIs all accept a context.

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 (
    "context"
    "errors"
    "fmt"
    "time"
)

func fetchReport(ctx context.Context) (string, error) {
    select {
    case <-time.After(time.Second): // stands in for slow I/O
        return "report", nil
    case <-ctx.Done(): // cancelled or past its deadline
        return "", ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    go func() {
        time.Sleep(50 * time.Millisecond)
        cancel() // cancel by hand...
    }()
    _, err := fetchReport(ctx)
    fmt.Println("stopped:", err)

    deadline, stop := context.WithTimeout(context.Background(), 20*time.Millisecond) // ...or by deadline
    defer stop()
    _, err = fetchReport(deadline)
    fmt.Println("stopped:", err, errors.Is(err, context.DeadlineExceeded))
}

Most used: context.Background, context.WithCancel, context.WithTimeout, defer cancel(), <-ctx.Done(), ctx.Err(), errors.Is(err, context.DeadlineExceeded), context.WithoutCancel, context.AfterFunc.

Request-scoped context: AsyncLocalStorage, context.WithValue, task_local!, thread_local

Go

context.WithValue returns a child context carrying one key-value pair, and ctx.Value(key) looks it up through the parent chain. Define the key as a value of an unexported type so no other package can collide with it, and wrap access in small typed helpers. Context values are for request-scoped data that crosses API boundaries, such as request ids, trace spans and authenticated users; options a function needs belong in its parameters. Lookups walk the chain, so keep values few.

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 (
    "context"
    "fmt"
)

type ctxKey int // unexported: no other package can make this key

const requestIDKey ctxKey = 0

func WithRequestID(ctx context.Context, id string) context.Context {
    return context.WithValue(ctx, requestIDKey, id)
}

func RequestID(ctx context.Context) string {
    if id, ok := ctx.Value(requestIDKey).(string); ok { // ok is false when unset
        return id
    }
    return "-"
}

func log(ctx context.Context, message string) {
    fmt.Printf("[%s] %s\n", RequestID(ctx), message)
}

// user is a real parameter: context values are for request-scoped data, not options.
func loadOrders(ctx context.Context, user string) {
    log(ctx, "orders for "+user)
}

func main() {
    ctx := WithRequestID(context.Background(), "r1")
    log(ctx, "start")
    loadOrders(ctx, "ada")
    log(ctx, "done")
    log(context.Background(), "outside")
}

Most used: context.WithValue, ctx.Value(key).(T), an unexported key type, WithX/FromContext helper pairs, context.WithoutCancel to keep values but drop cancellation, slog handlers that read values from the context.

A string key such as "requestID" can collide with another package’s; go vet and staticcheck flag built-in key types.

ctx.Value returns any; the type assertion with ok (v, ok := ...(string)) handles a missing value without panicking.

TCP & UDP sockets: node:net, net, std::net, Boost.Asio

Go

net provides TCP, UDP and Unix sockets with a blocking API that goroutines make concurrent: net.Listen and Accept for servers, net.Dial (or a net.Dialer with a timeout) for clients. A net.Conn is an io.Reader and io.Writer, so bufio, io.Copy and encoders all work on it, and SetDeadline bounds reads and writes. net/netip has small, comparable IP address types, and crypto/tls wraps connections in TLS.

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"
    "io"
    "net"
)

func main() {
    listener, err := net.Listen("tcp", "127.0.0.1:0") // port 0: pick a free port
    if err != nil {
        panic(err)
    }
    defer listener.Close()

    go func() { // an echo server: one goroutine per connection
        for {
            conn, err := listener.Accept()
            if err != nil {
                return
            }
            go func() {
                defer conn.Close()
                io.Copy(conn, conn) // a net.Conn is an io.Reader and an io.Writer
            }()
        }
    }()

    conn, err := net.Dial("tcp", listener.Addr().String())
    if err != nil {
        panic(err)
    }
    defer conn.Close()
    fmt.Fprintln(conn, "ping")
    reply, err := bufio.NewReader(conn).ReadString('\n')
    fmt.Print("echoed: ", reply, err, "\n")
}

Most used: net.Listen, listener.Accept, net.Dial, net.Dialer{Timeout: ...}, conn.SetDeadline, net.ListenPacket for UDP, netip.ParseAddr, tls.Dial.

TLS & certificates: node:tls, crypto/tls + crypto/x509, rustls, OpenSSL

Go

crypto/tls is a complete TLS 1.2 and 1.3 implementation in the standard library: tls.Dial and tls.Client for clients, tls.Listen and http.Server.ListenAndServeTLS for servers, both configured by a tls.Config. Verification is on by default against the system roots. To trust a private CA, put it in an x509.CertPool (from x509.SystemCertPool to keep the system roots, or x509.NewCertPool for only your own) and set RootCAs. crypto/x509 parses and verifies certificates and can create them; net/http/httptest starts a local HTTPS server with a throwaway certificate for tests.

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/tls"
    "crypto/x509"
    "fmt"
    "io"
    "log"
    "net/http"
    "net/http/httptest"
)

func main() {
    // A local HTTPS server with a freshly generated self-signed certificate.
    server := httptest.NewUnstartedServer(http.NotFoundHandler())
    server.Config.ErrorLog = log.New(io.Discard, "", 0) // keep the failed handshake below quiet
    server.StartTLS()
    defer server.Close()
    addr := server.Listener.Addr().String()

    roots := x509.NewCertPool() // or x509.SystemCertPool() to add to the OS roots
    roots.AddCert(server.Certificate())
    config := &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}

    conn, err := tls.Dial("tcp", addr, config) // handshake: verifies the chain and the name
    if err != nil {
        panic(err)
    }
    state := conn.ConnectionState()
    fmt.Println(tls.VersionName(state.Version), state.PeerCertificates[0].Subject.Organization)
    conn.Close()

    // Without the root the handshake fails: the check InsecureSkipVerify would switch off.
    _, err = tls.Dial("tcp", addr, &tls.Config{MinVersion: tls.VersionTLS12})
    fmt.Println(err)
}

Most used: tls.Dial, tls.Config{RootCAs, MinVersion, ServerName}, conn.ConnectionState(), tls.LoadX509KeyPair, x509.SystemCertPool, AppendCertsFromPEM, http.Transport{TLSClientConfig}, httptest.NewTLSServer.

Never set InsecureSkipVerify: true outside a test: it accepts any certificate for any name, so an attacker on the network path can impersonate the server and read the traffic. The failure it hides, shown at the end of this program, is fixed by adding the right root to RootCAs.

For HTTP, set the config on http.Transport{TLSClientConfig: config}; a tls.Config should not be modified after it has been used.

HTTP: fetch + node:http, net/http, reqwest/axum, cpp-httplib

Go

net/http is a production-grade client and server in the standard library. http.Client sends requests (bound them with a context or a Timeout, and close the response Body). The server side is http.Handler and HandlerFunc plus ServeMux routing, which since Go 1.22 understands methods and {path} wildcards. Set http.Server timeouts: the zero-value server, and http.ListenAndServe, have none. Many services need no framework; chi, echo and gin add middleware and routing helpers.

Complete program

Complete program that needs network access; it keeps serving until stopped.

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

import (
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

func main() {
    // Client: bound the whole request with a context (or http.Client{Timeout: ...}).
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/", nil)
    if err != nil {
        panic(err)
    }
    if resp, err := http.DefaultClient.Do(req); err == nil {
        fmt.Println(resp.Status)
        resp.Body.Close() // always close the body
    }

    // Server: method and path patterns are built in (Go 1.22+).
    mux := http.NewServeMux()
    mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(map[string]string{"id": r.PathValue("id")})
    })
    server := &http.Server{
        Addr:              ":8080",
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second, // the zero-value server has no timeouts
        IdleTimeout:       time.Minute,
    }
    fmt.Println(server.ListenAndServe())
}

Most used: http.Client with Timeout, http.NewRequestWithContext, resp.Body.Close, http.HandleFunc("GET /path/{id}", ...), r.PathValue, http.Server{ReadHeaderTimeout: ...}, httptest for tests.