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: core

What each language ships for everyday programming: printing, text, collections, iteration, optional values, errors and assertions, standard interfaces, numbers and bits, time and memory. Each entry compares the same role across languages.

Printing & formatting: console, fmt, println!, <print>

Go

fmt is Go's formatting package. Print, Println and Printf write to standard output, Sprint* return a string, Fprint* write to any io.Writer (stderr, a file, an HTTP response), and Errorf builds an error. Verbs such as %v (default format), %+v (with field names), %q (quoted) and %T (type) work on any value.

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() {
    name, items := "Ada", 3

    fmt.Println("Hello,", name)                  // values separated by spaces
    fmt.Printf("%s has %d items\n", name, items) // format verbs
    label := fmt.Sprintf("%-6s|%3d", name, items) // returns a string
    fmt.Println(label)
    fmt.Fprintln(os.Stderr, "warning: low stock") // any io.Writer
    fmt.Printf("%v %+v %T\n", items, struct{ N int }{items}, items)
}

Most used: fmt.Println, fmt.Printf, fmt.Sprintf, fmt.Fprintln, fmt.Errorf. Implement String() string on a type to control how %v prints it.

Text: String methods, strings, str/String, <string>

Go

Go strings are immutable byte sequences, and the operations live in the strings package as functions rather than methods: Split, Fields, TrimSpace, Contains, HasPrefix, Index, ReplaceAll, ToUpper, Join and Repeat. strings.Builder builds text efficiently. len and slicing count bytes, not characters; ranging over a string yields runes (Unicode code points).

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

func main() {
    raw := "  Ada Lovelace,Grace Hopper "

    names := strings.Split(strings.TrimSpace(raw), ",")
    fmt.Println(strings.ToUpper(names[0]), len(names))
    fmt.Println(strings.Contains(raw, "Grace"), strings.Index(raw, "Ada"))
    fmt.Println(names[0][:3], strings.ReplaceAll(names[1], " ", "_"))
    fmt.Println(strings.Join(names, " & "), strings.Repeat("-", 5))

    var b strings.Builder // efficient repeated appends
    for _, name := range names {
        b.WriteString(strings.Fields(name)[0])
    }
    fmt.Println(b.String())
}

Most used: strings.Cut and CutPrefix, strings.Split, strings.Fields, strings.TrimSpace, strings.Contains, strings.HasPrefix, strings.Join, strings.Builder. strings.Lines and SplitSeq (Go 1.24) return iterators. bytes mirrors the same API for []byte; unicode/utf8 counts runes.

Text ↔ number conversion: Number, strconv, parse, <charconv>

Go

strconv converts between strings and basic types. Atoi and Itoa handle int; ParseInt, ParseUint, ParseFloat and ParseBool take a base and bit size and return an error (*strconv.NumError) when the text is malformed or out of range. FormatInt, FormatFloat and Quote convert the other way.

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

func main() {
    for _, text := range []string{"42", "3.5", "12px", ""} {
        n, err := strconv.Atoi(text)
        fmt.Printf("%q -> %d, err=%v\n", text, n, err)
    }

    f, err := strconv.ParseFloat("3.5", 64)
    if err != nil {
        panic(err)
    }
    u, err := strconv.ParseUint("ff", 16, 8) // base 16, must fit in 8 bits
    if err != nil {
        panic(err)
    }
    fmt.Println(f, u, strconv.Itoa(42), strconv.FormatFloat(3.14159, 'f', 2, 64))
}

Most used: strconv.Atoi, strconv.Itoa, strconv.ParseInt, strconv.ParseFloat, strconv.ParseBool, strconv.FormatFloat, strconv.Quote. fmt.Sprint also formats numbers but is slower and less explicit.

Collections: Array/Map/Set, slices/maps, std::collections, containers

Go

Slices ([]T) and maps (map[K]V) are built into the language, created with literals or make and grown with append. The slices package (Go 1.21+) adds generic helpers such as Contains, Index, Sort, Max and Equal; maps adds Keys, Values and Clone. There is no set type: use map[T]struct{}. container/heap and container/list cover heaps and linked lists.

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"
    "maps"
    "slices"
)

func main() {
    scores := []int{72, 95, 88} // slice: growable view over an array
    scores = append(scores, 61)

    byName := map[string]int{"ada": 95} // built-in hash map
    byName["grace"] = 88
    score, ok := byName["linus"] // ok is false when the key is missing

    tags := map[string]struct{}{"go": {}, "rust": {}} // a set is a map with empty values

    fmt.Println(len(scores), slices.Contains(scores, 88), slices.Max(scores))
    fmt.Println(score, ok, slices.Sorted(maps.Keys(byName)), len(tags))
}

Most used: append, len, make, map[key] with the comma-ok form, delete, slices.Contains, slices.Sort, maps.Keys.

Collection algorithms: Array methods, slices, Iterator, <algorithm>

Go

Go favours plain for loops over map/filter/reduce chains. The slices package (Go 1.21+) supplies the reusable pieces: Sort and SortFunc, BinarySearch, Index and IndexFunc, Contains, Max and Min, Reverse and Compact, with cmp.Compare for comparators. The older sort package (sort.Slice, sort.Ints) is still common in existing code.

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

type Order struct {
    ID    int
    Total int
    Paid  bool
}

func main() {
    orders := []Order{{1, 40, true}, {2, 15, false}, {3, 90, true}}

    revenue := 0
    for _, o := range orders { // a plain loop instead of map/filter/reduce
        if o.Paid {
            revenue += o.Total
        }
    }

    unpaid := slices.IndexFunc(orders, func(o Order) bool { return !o.Paid })
    fmt.Println(revenue, orders[unpaid].ID)

    slices.SortFunc(orders, func(a, b Order) int {
        return cmp.Compare(b.Total, a.Total) // descending
    })
    fmt.Println(orders[0].ID)
}

Most used: for range loops, slices.Sort, slices.SortFunc with cmp.Compare, slices.IndexFunc, slices.BinarySearch, sort.Slice in older code.

Iterators & generators: function*, iter.Seq, Iterator, <ranges>

Go

Since Go 1.23, for range accepts iterator functions, and the iter package names their types: iter.Seq[V] and iter.Seq2[K, V] are functions that call yield for each value and stop when yield returns false. The standard library returns them from slices.All, slices.Values, maps.Keys and maps.Values, and slices.Collect or slices.Sorted turn them back into slices. iter.Pull converts one into a next() style iterator.

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"
    "iter"
    "maps"
    "slices"
)

func Range(start, end, step int) iter.Seq[int] { // a push iterator: calls yield per value
    return func(yield func(int) bool) {
        for n := start; n < end; n += step {
            if !yield(n) { // false means the loop stopped early
                return
            }
        }
    }
}

func Naturals() iter.Seq[int] {
    return func(yield func(int) bool) {
        for n := 1; yield(n); n++ {
        }
    }
}

func main() {
    for n := range Range(0, 10, 3) { // range over a function (Go 1.23+)
        fmt.Print(n, " ")
    }
    fmt.Println()

    for n := range Naturals() {
        if n > 4 {
            break
        }
        fmt.Print(n, " ")
    }
    fmt.Println()

    ages := map[string]int{"ada": 36, "grace": 45}
    fmt.Println(slices.Collect(Range(0, 5, 1)), slices.Sorted(maps.Keys(ages)))
}

Most used: iter.Seq, iter.Seq2, for x := range seq, slices.Collect, slices.Sorted, maps.Keys, slices.All, iter.Pull.

Optional & variant values: unions, comma-ok, Option, <optional>/<variant>

Go

Go has no Option or sum type. Absence is expressed with zero values, the comma-ok form (v, ok := m[k]), an extra bool or error result, or a nil pointer. Alternatives are modelled as an interface plus a type switch; the compiler does not check that every case is handled. cmp.Or picks the first non-zero value.

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

type Shipping interface{ isShipping() } // a closed set of alternatives, by convention

type Pickup struct{}
type Courier struct{ Address string }

func (Pickup) isShipping()  {}
func (Courier) isShipping() {}

func describe(s Shipping) string {
    switch v := s.(type) {
    case Pickup:
        return "pickup"
    case Courier:
        return "courier to " + v.Address
    default:
        return "unknown"
    }
}

func main() {
    names := map[int]string{7: "Ada"}
    name, ok := names[8] // comma-ok: the zero value plus a found flag
    fmt.Printf("%q %v\n", name, ok)

    var limit *int // a nil pointer as "no value"
    if limit == nil {
        fmt.Println("no limit")
    }
    fmt.Println(cmp.Or(name, "guest"), describe(Courier{"1 Main St"}), describe(Pickup{}))
}

Most used: v, ok := m[key], v, ok := x.(T), switch v := x.(type), *T as an optional value, cmp.Or(a, b) for defaults.

Errors: Error, errors, Result + std::error, <stdexcept>/<expected>

Go

In Go an error is an ordinary return value of the built-in error interface (anything with an Error() string method), checked with if err != nil. The errors package creates errors (errors.New) and inspects wrapped chains: errors.Is compares with a sentinel, errors.As extracts a specific type and errors.Join combines several. fmt.Errorf with %w adds context and keeps the original.

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

var ErrNotFound = errors.New("not found") // sentinel error

func load(id string) (int, error) {
    if id != "1" {
        return 0, fmt.Errorf("order %s: %w", id, ErrNotFound) // %w wraps
    }
    return 40, nil
}

func main() {
    _, err := load("7")
    if errors.Is(err, ErrNotFound) { // looks through wrapping
        fmt.Println("missing:", err)
    }
}

Most used: if err != nil, errors.New, fmt.Errorf("...: %w", err), errors.Is, errors.As. panic is reserved for programming bugs.

Assertions & invariants: node:assert, panic, assert!, <cassert>/static_assert

Go

Go has no assert, by design: the Go FAQ argues that assertions become a crutch for skipping proper error handling and reporting. Expected failures (bad input, missing files) are returned as error values. A broken invariant, meaning a bug, is reported with panic, which unwinds the goroutine and runs deferred calls; recover inside a deferred function stops the panic, which is only worth doing at a boundary such as a request handler or worker loop. An unrecovered panic crashes the whole program.

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

var errEmpty = errors.New("empty cart") // expected failure: returned, not panicked

func total(prices []int) (int, error) {
    if len(prices) == 0 {
        return 0, errEmpty
    }
    sum := 0
    for _, p := range prices {
        sum += mustNonNegative(p)
    }
    return sum, nil
}

// mustNonNegative panics: a negative price here means a bug upstream.
func mustNonNegative(n int) int {
    if n < 0 {
        panic(fmt.Sprintf("invariant violated: price %d", n))
    }
    return n
}

// safely turns a panic back into an error; use it at a boundary only.
func safely(f func()) (err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("recovered: %v", r)
        }
    }()
    f()
    return nil
}

func main() {
    if _, err := total(nil); errors.Is(err, errEmpty) {
        fmt.Println("expected:", err)
    }
    fmt.Println(total([]int{3, 4}))
    fmt.Println(safely(func() { total([]int{3, -1}) }))
}

Most used: if cond { panic(fmt.Sprintf(...)) }, default: panic("unreachable") in a switch, Must-style helpers (regexp.MustCompile, template.Must), defer func() { if r := recover(); r != nil { ... } }(), errors for everything expected.

recover only works when called directly in a deferred function of the panicking goroutine; a panic in another goroutine cannot be recovered here.

Since Go 1.21, panic(nil) panics with a *runtime.PanicNilError, so recover() never returns nil for a real panic.

Standard interfaces & traits: protocols, Stringer, derive, concepts

Go

Go interfaces are satisfied implicitly: any type with the right methods fits, with no implements keyword. A few small standard interfaces connect the whole library: fmt.Stringer (String() string) controls printing, error (Error() string) marks errors, io.Reader and io.Writer move bytes, and json.Marshaler customizes JSON. For generics, comparable, any and cmp.Ordered are the standard constraints.

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 (
    "cmp"
    "fmt"
    "io"
    "slices"
    "strings"
)

type Money struct{ Cents int }

func (m Money) String() string { // fmt.Stringer: used by %v and Println
    return fmt.Sprintf("$%d.%02d", m.Cents/100, m.Cents%100)
}

func Largest[T cmp.Ordered](values ...T) T { // a constraint from the cmp package
    return slices.Max(values)
}

func countBytes(r io.Reader) (int64, error) { // any io.Reader works
    return io.Copy(io.Discard, r)
}

func main() {
    prices := []Money{{500}, {1250}, {120}}
    slices.SortFunc(prices, func(a, b Money) int { return cmp.Compare(a.Cents, b.Cents) })
    fmt.Println(prices) // [$1.20 $5.00 $12.50]

    n, err := countBytes(strings.NewReader("hello"))
    fmt.Println(n, err, Largest(3, 9, 4), Largest("b", "a"))
}

Most used: String() string, Error() string, io.Reader and io.Writer, http.Handler, json.Marshaler, comparable, cmp.Ordered, any.

Functions as values: closures, func types, Fn traits, <functional>

Go

Functions are first-class values with types such as func(int) int; they can be stored, passed, returned and compared with nil. Function literals are closures over the surrounding variables, and methods can be used as values too (m.Method or Type.Method). There is no functional-utilities package: write small helpers yourself, and swap with multiple assignment.

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"

type Handler func(amount int) int // a named function type

func compose(steps ...Handler) Handler {
    return func(n int) int {
        for _, step := range steps {
            n = step(n)
        }
        return n
    }
}

func addFee(fee int) Handler {
    return func(n int) int { return n + fee } // the closure captures fee
}

func main() {
    handlers := map[string]Handler{
        "double": func(n int) int { return n * 2 },
        "tax":    func(n int) int { return n * 12 / 10 },
    }
    pipeline := compose(handlers["double"], handlers["tax"], addFee(5))
    fmt.Println(pipeline(10))

    a, b := 1, 2
    a, b = b, a // swap with multiple assignment
    fmt.Println(a, b)
}

Most used: func literals, named function types, adapters such as http.HandlerFunc, method values, variadic ...T parameters, a, b = b, a.

Math & random numbers: Math, math + math/rand, number methods, <cmath>/<random>

Go

math holds float64 functions and constants (Sqrt, Pow, Floor, Round, Abs, Inf, NaN, MaxInt64, Pi), and the built-in min and max (Go 1.21+) work on any ordered type. math/rand/v2 generates fast pseudo-random numbers (IntN, Float64, Shuffle) and seeds itself. crypto/rand is the secure source for tokens and keys. math/big handles arbitrary precision.

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/rand"
    "fmt"
    "math"
    mrand "math/rand/v2"
)

func main() {
    fmt.Println(math.Round(2.5), math.Floor(-1.5), math.Trunc(-1.5))
    fmt.Println(max(3, 9, 4), math.Abs(-7), math.Sqrt(16), math.Pow(2, 10))
    fmt.Println(math.MaxInt64, math.Inf(1), math.NaN())

    roll := mrand.IntN(6) + 1 // fine for simulations, not for secrets
    fmt.Println(roll, rand.Text()) // crypto/rand: secure random token (Go 1.24+)
}

Most used: math.Round, math.Floor, math.Abs, math.MaxInt64, min, max, rand.IntN (math/rand/v2), rand.Shuffle, crypto/rand.Text.

Integer & bit math: bitwise ops + Math.clz32, math/bits, integer methods, <bit>/<numeric>

Go

math/bits has the bit-level functions for unsigned integers, in sized forms (OnesCount8 to OnesCount64, plus OnesCount for uint): OnesCount (popcount), LeadingZeros, TrailingZeros, Len (bits needed), RotateLeft (a negative count rotates right), Reverse and ReverseBytes, and Add64, Sub64, Mul64 and Div64 for multi-word arithmetic with carries. Integer arithmetic wraps silently on overflow for both signed and unsigned types; only overflowing constant expressions are compile errors. The operators include &^ (AND NOT). There is no gcd for machine integers (big.Int.GCD covers big ones).

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"
    "math"
    "math/bits"
)

func isPow2(n uint) bool { return n != 0 && n&(n-1) == 0 }
func ceilDiv(a, b int) int  { return (a + b - 1) / b } // no built-in; a, b > 0

func main() {
    x := uint32(0b1011_0110)
    fmt.Println(bits.OnesCount32(x), bits.LeadingZeros32(x), bits.TrailingZeros32(x), bits.Len32(x))
    fmt.Printf("%08b %08b\n", bits.RotateLeft8(0b1000_0001, 1), bits.RotateLeft8(0b0000_0011, -1))
    fmt.Printf("%#x %08b\n", bits.ReverseBytes16(0x1234), uint8(0b1111_0110)&^0b0000_0110)

    sum, carry := bits.Add64(math.MaxUint64, 1, 0) // carry out of the top bit
    hi, lo := bits.Mul64(1<<63, 4)                  // the full 128-bit product as two words
    fmt.Println(sum, carry, hi, lo)

    var n int64 = math.MaxInt64
    n++ // wraps silently at run time; math.MaxInt64 + 1 as a constant would not compile
    fmt.Println(n == math.MinInt64)
    fmt.Println(isPow2(64), isPow2(96), ceilDiv(10, 3))
}

Most used: bits.OnesCount64, bits.LeadingZeros64, bits.TrailingZeros64, bits.Len, bits.RotateLeft64, bits.Add64, bits.Mul64, x &^ mask, math.MaxInt64, math.MaxUint32.

Shift counts are not masked: x << 64 is 0 and x >> 64 is 0 (or -1 for a negative signed x); a negative shift count panics at run time.

Converting between int sizes (int32(x)) truncates without a check; compare against math.MaxInt32 first when the value comes from outside.

Big numbers & decimals: BigInt, math/big, num-bigint, Boost.Multiprecision

Go

math/big provides arbitrary-precision integers (Int), exact fractions (Rat) and big floats (Float). To avoid allocations the API writes results into a receiver: z.Add(x, y) sets z to x + y and returns z, so expressions read new(big.Int).Add(a, b). There is no decimal type in the standard library; money is usually int64 cents or a library such as shopspring/decimal.

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"
    "math/big"
)

func main() {
    power := new(big.Int).Exp(big.NewInt(2), big.NewInt(100), nil) // 2^100
    fmt.Println(power)

    n, ok := new(big.Int).SetString("9007199254740993", 10)
    fmt.Println(n.Add(n, big.NewInt(1)), ok) // methods write into the receiver

    sum := new(big.Rat).Add(big.NewRat(1, 3), big.NewRat(1, 6)) // exact fractions
    fmt.Println(sum, sum.FloatString(4))                         // 1/2 0.5000

    a, b := 0.1, 0.2
    fmt.Println(a+b == 0.3) // false: float64 is binary floating point
}

Most used: big.NewInt, new(big.Int).SetString(text, 10), Add, Mul, Exp, Cmp, big.NewRat, FloatString, int64 cents for money.

Time & durations: Date + performance, time, std::time, <chrono>

Go

time covers instants (time.Time), durations (time.Duration, such as 50 * time.Millisecond), sleeping, timers and tickers, and time zones (time.LoadLocation). time.Now includes a monotonic reading, so time.Since and Sub measure correctly even if the wall clock changes. Formatting uses a reference date, Mon Jan 2 15:04:05 MST 2006, written in the layout you want.

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() {
    start := time.Now() // includes a monotonic reading for measuring

    now := time.Now().UTC()
    fmt.Println(now.Format(time.RFC3339)) // e.g. 2026-11-07T09:30:00Z
    fmt.Println(now.Unix())                // seconds since the epoch

    time.Sleep(50 * time.Millisecond)
    tomorrow := now.Add(24 * time.Hour)
    fmt.Println(tomorrow.Format("2006-01-02")) // layouts use this reference date

    fmt.Println("took", time.Since(start).Round(time.Millisecond))
}

Most used: time.Now, time.Since, time.Sleep, time.Duration, t.Add, t.Format, time.Parse, time.RFC3339, time.NewTicker, time.After.

Unicode & localization: Intl, unicode/utf8, char methods, <locale>/ICU

Go

Go strings hold UTF-8 bytes, so len counts bytes; ranging over a string decodes runes (Unicode code points), and []rune(text) converts the whole string. unicode classifies and converts single runes (IsLetter, IsSpace, ToUpper), and unicode/utf8 counts, validates and encodes. Grapheme clusters, normalization, collation and number or date localization are not in the standard library; golang.org/x/text provides them.

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"
    "strings"
    "unicode"
    "unicode/utf8"
)

func main() {
    word := "café👍🏽"

    fmt.Println(len(word), utf8.RuneCountInString(word)) // 13 bytes, 6 runes
    for i, r := range word { // range decodes UTF-8 into runes
        if i < 5 {
            fmt.Printf("%d:%c ", i, r)
        }
    }
    fmt.Println()

    fmt.Println(unicode.IsLetter('é'), unicode.IsUpper('É'), string(unicode.ToUpper('é')))
    fmt.Println(strings.ToUpper("straße"), strings.EqualFold("Go", "GO"))
    fmt.Println(utf8.ValidString("ok"), []rune("héllo")[1] == 'é')
}

Most used: for i, r := range s, utf8.RuneCountInString, []rune(s), unicode.IsLetter, unicode.IsSpace, strings.EqualFold, utf8.ValidString, golang.org/x/text.

Memory & smart pointers: GC, Box/Rc/Arc, <memory>

Go

Go is garbage collected, so there is no smart-pointer library. Pointers (*T and &x) are ordinary and safe: returning the address of a local value is fine, because the compiler moves it to the heap when needed. new(T) and make (for slices, maps and channels) allocate. runtime and runtime/debug expose collector statistics and tuning.

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"

type Order struct{ ID int }

func newOrder(id int) *Order {
    return &Order{ID: id} // safe: the compiler moves it to the heap
}

func main() {
    order := newOrder(7)
    clone := *order // copies the struct
    clone.ID = 8
    fmt.Println(order.ID, clone.ID) // 7 8
}

Most used: &T{...}, *p, new, make, runtime.ReadMemStats, the GOGC and GOMEMLIMIT settings, weak.Pointer (Go 1.24+) for caches, runtime.AddCleanup (Go 1.24, replaces SetFinalizer), unique.Make (Go 1.23) for interning.