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.

Numbers & operators

Choose a numeric type

Go

Signed int8…int64 and unsigned uint8…uint64 have fixed widths; int/uint depend on the platform. float32/64 and complex64/128 are distinct types. byte aliases uint8; rune aliases int32.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
var count int64 = 24
var mask uint8 = 0xff
var ratio float64 = 1.5
var signal complex128 = 2 + 3i
var ready bool = true

Recognize limits and overflow

Go

A constant must fit its destination type. Runtime integer arithmetic has defined overflow behavior; it does not automatically signal an error. Choose a wider type or check the operation when range matters.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
var n uint8 = 255
n += 1 // wraps to 0

// var invalid uint8 = 256 // compile error

Read arithmetic, comparisons and bit operations

Go

Integer division truncates toward zero. ^ is bitwise XOR (or complement with one operand); &^ clears bits. Equality is limited to comparable types: slices, maps and functions are not generally comparable.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
quotient := 7 / 2 // 3
mask := uint8(0b1010)
enabled := mask&0b0010 != 0
cleared := mask &^ 0b0010

Detect integer overflow: safe integers, math/bits, checked_*, __builtin_add_overflow

Go

Beyond the limits in Recognize limits and overflow, this shows how to detect overflow by hand and with math/bits. Go defines integer overflow: signed and unsigned arithmetic wraps around (two's complement), with no panic and no error. Constant expressions are checked at compile time, so var x int8 = 128 does not compile, but x++ at run time silently wraps. There are no checked-arithmetic built-ins; math/bits returns the carry or borrow for unsigned 32- and 64-bit addition, subtraction and multiplication, and signed checks are written by hand.

Complete program

Complete program.

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

import (
    "errors"
    "fmt"
    "math"
    "math/bits"
)

var errOverflow = errors.New("integer overflow")

// addInt64 detects signed overflow: it happens only when both operands have
// the same sign and the result's sign differs.
func addInt64(a, b int64) (int64, error) {
    sum := a + b
    if (a > 0 && b > 0 && sum < 0) || (a < 0 && b < 0 && sum >= 0) {
        return 0, errOverflow
    }
    return sum, nil
}

// mulInt64 checks multiplication by dividing back.
func mulInt64(a, b int64) (int64, error) {
    if a == 0 || b == 0 {
        return 0, nil
    }
    p := a * b
    if p/b != a || (a == -1 && b == math.MinInt64) || (b == -1 && a == math.MinInt64) {
        return 0, errOverflow
    }
    return p, nil
}

func main() {
    // Plain arithmetic wraps silently (two's complement); no panic, no error.
    var u uint8 = 255
    u++
    var i int8 = math.MaxInt8
    i++
    fmt.Println("wrapped:", u, i) // 0 -128

    if _, err := addInt64(math.MaxInt64, 1); !errors.Is(err, errOverflow) {
        panic("expected overflow")
    }
    sum, _ := addInt64(40, 2)
    fmt.Println("checked add:", sum)

    if _, err := mulInt64(math.MaxInt64/2, 3); err == nil {
        panic("expected overflow")
    }

    // math/bits returns the carry (unsigned) so you can detect or chain it.
    lo, carry := bits.Add64(math.MaxUint64, 1, 0)
    fmt.Println("bits.Add64:", lo, "carry", carry) // 0 carry 1
    hi, low := bits.Mul64(math.MaxUint64, 2)
    fmt.Println("bits.Mul64 high word:", hi, "low:", low) // nonzero high word means it overflowed 64 bits
}

In practice: when values come from users, files or the network, check before or after the operation with a small helper (same-sign operands giving a different-sign sum means overflow; for multiplication, divide back). Use bits.Add64 / bits.Mul64 when you need the carry, for example in multi-word arithmetic. Pick int64 rather than int when the range matters.

The compiler may not assume overflow cannot happen, so x < x+1 is not always true in Go, unlike the optimizer assumptions in C and C++.

math.MinInt64 / -1 does not panic; it wraps to math.MinInt64. Check for it when you divide untrusted values.

Divide integers and take remainders: / and %, Math.trunc, rem_euclid, divide by zero

Go

Beyond the operator summary in Read arithmetic, comparisons and bit operations, this covers negative remainders, Euclidean modulo and what division by zero does. Integer division truncates toward zero and % takes the sign of the dividend, so -7 / 2 is -3 and -7 % 3 is -1. The two operands must have the same type; Go never converts int to float64 for you, so float division needs explicit conversions. Integer division by zero panics at run time (and is a compile error with a constant zero). Float division by zero follows IEEE 754 and yields +Inf, -Inf or NaN. There is no floor-division or Euclidean-modulo operator.

Complete program

Complete program.

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

import (
    "fmt"
    "math"
)

// mod returns the Euclidean (always non-negative) remainder for n > 0.
func mod(a, n int) int {
    return ((a % n) + n) % n
}

func safeDiv(a, b int) (q int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("%v", r)
        }
    }()
    return a / b, nil
}

func main() {
    // Integer division truncates toward zero; % takes the sign of the dividend.
    fmt.Println(7/2, -7/2, -7%3) // 3 -3 -1

    // Mixing needs an explicit conversion: Go never converts implicitly.
    a, b := 7, 2
    fmt.Println(float64(a) / float64(b)) // 3.5

    // Floor division and Euclidean modulo have to be written out.
    fmt.Println(int(math.Floor(float64(-7)/2)), mod(-7, 3), mod(-1, 24)) // -4 2 23

    // Integer divide by zero panics at run time (a constant 0 is a compile error).
    zero := 0
    _, err := safeDiv(1, zero)
    fmt.Println("int:", err) // runtime error: integer divide by zero

    // Float divide by zero follows IEEE 754: ±Inf or NaN, no panic.
    fz := 0.0
    fmt.Println(1/fz, -1/fz, fz/fz) // +Inf -Inf NaN

    // MinInt64 / -1 does not panic: the result wraps back to MinInt64.
    minusOne := -1
    fmt.Println(math.MinInt64/minusOne == math.MinInt64)
}

In practice: write ((a % n) + n) % n for a non-negative modulo, and use math.Floor on float64 values for floor division. Validate divisors from input and return an error instead of letting the panic escape.

The program recovers from the divide-by-zero panic only to print it; real code checks b == 0 before dividing.

For big.Int, Quo/Rem truncate like the operators, while Div/Mod are Euclidean.

Convert between numeric types: Math.trunc, T(x), as + TryFrom, static_cast

Go

Beyond the type list in Choose a numeric type, this covers what T(x) does when a value does not fit and how to check before converting. Go has no implicit numeric conversions: even int to int64 needs T(x). Converting between integer types never fails: the value is sign-extended or truncated to the low bits, so uint8(300) is 44. Converting a float to an integer truncates toward zero; if the result does not fit the target type, the result is implementation-dependent (the spec does not define it, and the compiler does not panic). Converting a large integer to float64 rounds to the nearest representable value.

Complete program

Complete program.

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

import (
    "errors"
    "fmt"
    "math"
)

// toInt32 is a checked narrowing conversion.
func toInt32(n int64) (int32, error) {
    if n < math.MinInt32 || n > math.MaxInt32 {
        return 0, errors.New("out of int32 range")
    }
    return int32(n), nil
}

// floatToInt64 rejects NaN, infinities and values that do not fit.
func floatToInt64(f float64) (int64, error) {
    if math.IsNaN(f) || f < math.MinInt64 || f >= math.MaxInt64 {
        return 0, fmt.Errorf("%v does not fit in int64", f)
    }
    return int64(f), nil // truncates toward zero
}

func main() {
    // Integer conversions between widths keep the low bits (wrap) with no error.
    big := 300
    fmt.Println(uint8(big), int8(big)) // 44 44
    neg := -1
    fmt.Println(uint32(neg)) // 4294967295

    // Float to int truncates toward zero.
    f := -2.7
    fmt.Println(int(f), int(math.Round(f))) // -2 -3

    // int to float can lose precision above 2^53.
    n := int64(1<<53 + 1)
    fmt.Println(int64(float64(n)) == n) // false

    v, err := toInt32(1 << 40)
    fmt.Println(v, err)
    w, err := floatToInt64(1e300)
    fmt.Println(w, err)
    x, _ := floatToInt64(-2.7)
    fmt.Println(x)
}

In practice: write small checked helpers for narrowing (compare against math.MinInt32 / math.MaxInt32 first) and for float-to-int (reject NaN, infinities and out-of-range values). Use math.Round, math.Floor or math.Ceil before the conversion when truncation is not what you want.

Constant conversions are checked: uint8(300) with a constant 300 is a compile error; the program uses a variable to show runtime wrapping.

Out-of-range float-to-int results differ between architectures (amd64 and arm64 give different values), so tests that pass on one machine can fail on another.

Compare floats and keep money in integer cents: EPSILON, math.IsNaN, total_cmp, std::signbit

Go

Beyond the type list in Choose a numeric type and the decimal libraries in Big numbers & decimals, this covers comparing computed floats, NaN, negative zero and keeping money in integer cents. float64 and float32 are IEEE 754 binary floats, with the same rounding as every other language: 0.1 + 0.2 on float64 values is 0.30000000000000004. Go's untyped constants are exact, so the constant expression 0.1 + 0.2 == 0.3 is true; the rounding appears once values are stored in float64 variables. NaN compares unequal to itself (math.IsNaN detects it), and a NaN map key can be inserted but never found. math.Copysign and math.Signbit expose negative zero.

Complete program

Complete program.

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

import (
    "fmt"
    "math"
)

func nearlyEqual(a, b float64) bool {
    const rel, abs = 1e-9, 1e-12
    return math.Abs(a-b) <= math.Max(rel*math.Max(math.Abs(a), math.Abs(b)), abs)
}

func main() {
    // Constants are exact; the rounding happens when values become float64 at run time.
    a, b := 0.1, 0.2
    fmt.Println(a+b, a+b == 0.3)          // 0.30000000000000004 false
    fmt.Println(nearlyEqual(a+b, 0.3))    // true
    fmt.Println(math.Nextafter(1, 2) - 1) // machine epsilon, 2.220446049250313e-16

    // NaN compares unequal to itself; use math.IsNaN.
    nan := math.NaN()
    fmt.Println(nan == nan, math.IsNaN(nan)) // false true
    // A NaN map key can be inserted but never looked up.
    m := map[float64]int{nan: 1}
    _, found := m[nan]
    fmt.Println(len(m), found) // 1 false

    // Negative zero equals zero but keeps its sign.
    negZero := math.Copysign(0, -1)
    fmt.Println(negZero == 0, math.Signbit(negZero), 1/negZero) // true true -Inf

    // Money in integer cents; round once.
    const priceCents int64 = 1999
    total := priceCents * 3
    tax := int64(math.Round(float64(total) * 825 / 10000))
    fmt.Printf("total: %d.%02d\n", (total+tax)/100, (total+tax)%100) // 64.92
}

In practice: compare with a relative plus absolute tolerance, use math.IsNaN for NaN checks, and keep money as int64 cents (or a decimal library) with one rounding step at the edge. Avoid floats as map keys.

shopspring/decimal (v1.6.0) is the usual decimal type for money in Go; math/big.Rat is exact but slower and has no rounding modes.

slices.Sort and sort.Float64s both order NaN values before all other values.

Parse and format numbers: Number + Intl.NumberFormat, strconv + fmt, parse + format!, from_chars + std::format

Go

Beyond the basic calls in Text ↔ number conversion and Printing & formatting, this covers parse errors and ranges, and output width, precision, rounding and separators. strconv parses strictly: strconv.Atoi(s) and strconv.ParseInt(s, base, bitSize) require the whole string to be a number, do not trim whitespace, and return a *strconv.NumError that wraps strconv.ErrSyntax or strconv.ErrRange. bitSize checks the range for you (ParseInt("300", 10, 8) fails), and base 0 accepts 0x, 0o, 0b prefixes and underscores. For output, fmt verbs control width and precision (%5d, %-5d, %05d, %.2f, %8.3f, %x) and strconv.FormatInt / FormatFloat avoid fmt's reflection.

Complete program

Complete program.

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

import (
    "errors"
    "fmt"
    "math"
    "strconv"
    "strings"
)

// group inserts thousands separators; the standard library has no locale formatting.
func group(n int64) string {
    s := strconv.FormatInt(n, 10)
    sign := ""
    if n < 0 {
        sign, s = "-", s[1:]
    }
    var b strings.Builder
    for i, r := range s {
        if i > 0 && (len(s)-i)%3 == 0 {
            b.WriteByte(',')
        }
        b.WriteRune(r)
    }
    return sign + b.String()
}

func main() {
    // Atoi is ParseInt(s, 10, 0): the whole string must be a base-10 integer.
    n, err := strconv.Atoi("42")
    fmt.Println(n, err) // 42 <nil>

    _, err = strconv.Atoi("12px")
    fmt.Println(err) // strconv.Atoi: parsing "12px": invalid syntax

    // ParseInt takes a base and a bit size; out-of-range values return ErrRange.
    _, err = strconv.ParseInt("300", 10, 8)
    fmt.Println(errors.Is(err, strconv.ErrRange)) // true
    hex, _ := strconv.ParseInt("ff", 16, 64)
    auto, _ := strconv.ParseInt("0x_ff", 0, 64) // base 0: prefix and underscores allowed
    fmt.Println(hex, auto)                      // 255 255

    // Whitespace is not trimmed for you.
    _, err = strconv.Atoi(" 42")
    fmt.Println(err != nil) // true
    f, _ := strconv.ParseFloat(strings.TrimSpace(" 3.14 "), 64)
    fmt.Println(f)

    // Formatting verbs: %d, %.2f, width and padding.
    fmt.Printf("[%5d] [%-5d] [%05d] [%.2f] [%8.3f] [%x]\n", 42, 42, 42, 3.14159, 3.14159, 255)
    fmt.Println(strconv.FormatFloat(1234.5, 'f', 2, 64), group(-1234567))

    // Rounding to 2 decimals: %.2f rounds an exact tie (0.125 is exact in binary)
    // to even, while math.Round rounds half away from zero.
    fmt.Printf("%.2f %.0f\n", 0.125, 2.5)    // 0.12 2
    fmt.Println(math.Round(0.125*100) / 100) // 0.13
}

In practice: use strconv for input, check errors.Is(err, strconv.ErrRange) when the difference matters, and strings.TrimSpace first if your input may have whitespace. The standard library has no thousands separators or locale formatting; golang.org/x/text/message provides them, or write a small helper. When rounding to 2 decimals, %.2f and FormatFloat round an exact tie such as 0.125 to even (0.12) while math.Round(x*100)/100 rounds it away from zero (0.13), so choose one rule for money and apply it to integer cents.

strconv.Atoi parses into int, which is 64 bits on common platforms but 32 bits on 32-bit targets; use ParseInt with an explicit bitSize when the range matters.

golang.org/x/text/message (message.NewPrinter(language.English).Sprintf("%d", n)) formats with locale-aware separators.

Use integers wider than 64 bits: BigInt, math/big, u128, unsigned __int128

Go

Beyond the overview in Big numbers & decimals, this shows the math/big API in use: receivers, parsing, comparison and the two kinds of division. The standard library's math/big provides arbitrary-precision integers (big.Int), exact rationals (big.Rat) and big floats (big.Float). Values are pointers and methods write into the receiver to avoid allocations: z.Mul(x, y) sets z = x * y and returns z. Comparison uses Cmp (== compares pointers), Quo/Rem truncate like the operators while Div/Mod are Euclidean, and Exp does modular exponentiation.

Complete program

Complete program.

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

import (
    "fmt"
    "math/big"
)

func main() {
    // big.Int methods write into the receiver: z.Mul(x, y) sets z = x*y and returns z.
    f := big.NewInt(1)
    for i := int64(2); i <= 30; i++ {
        f.Mul(f, big.NewInt(i))
    }
    fmt.Println("30! =", f) // 265252859812191058636308480000000

    // Parse from text; ok is false on bad input.
    n, ok := new(big.Int).SetString("123456789012345678901234567890", 10)
    if !ok {
        panic("bad number")
    }
    n.Add(n, big.NewInt(1))
    fmt.Println(n)

    // Modular exponentiation without building 2^100.
    r := new(big.Int).Exp(big.NewInt(2), big.NewInt(100), big.NewInt(1_000_007))
    fmt.Println(r) // 698635

    // Quo truncates toward zero; Div is Euclidean.
    a, b := big.NewInt(-7), big.NewInt(2)
    fmt.Println(new(big.Int).Quo(a, b), new(big.Int).Div(a, b)) // -3 -4

    // Cmp, not ==, compares values (== compares pointers).
    x, y := big.NewInt(10), big.NewInt(10)
    fmt.Println(x == y, x.Cmp(y) == 0, f.IsInt64()) // false true false

    // big.Rat holds exact fractions.
    third := big.NewRat(1, 3)
    sum := new(big.Rat).Add(third, third)
    fmt.Println(sum, sum.FloatString(4)) // 2/3 0.6667
}

In practice: reuse a result variable inside loops (f.Mul(f, x)), parse with SetString and check its ok result, and convert back with IsInt64 / Int64 when the value is known to fit. Do not copy big.Int values by dereferencing; pass *big.Int.

Go has no 128-bit integer type; math/bits.Mul64 and Add64 give the high and low words when two 64-bit words are enough.

big.Int operations allocate as numbers grow; on hot paths prefer fixed-size types and check for overflow.