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.

Time & randomness

Record wall-clock time for an event

Go

time.Now supplies a time value; format UTC explicitly when your interchange format requires it.

Fragment

Import time. time.Time can also carry a monotonic component for supported in-process elapsed comparisons.

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

recordedAt := time.Now().UTC().Format(time.RFC3339Nano)
epochMillis := time.Now().UnixMilli()

Measure elapsed time with a monotonic clock

Go

time.Since uses the monotonic reading carried by a compatible time.Now value when available.

Fragment

Import time; elapsed is a time.Duration.

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

start := time.Now()
work()
elapsed := time.Since(start)

Choose a random value for ordinary simulation

Go

rand/v2 supplies general-purpose pseudorandom generation. IntN returns a value in [0,n).

Fragment

Go 1.22+. Import math/rand/v2. It is not crypto/rand.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import "math/rand/v2"

die := rand.IntN(6) + 1

Represent durations and add them to times: Temporal.Duration, time.Duration, std::time::Duration, std::chrono

Go

time.Duration is an int64 count of nanoseconds with typed constants (time.Second, time.Millisecond), so 30 * time.Second reads naturally and prints as 30s. A variable integer has to be converted first: time.Duration(n) * time.Second. Hours and Seconds return float64; Milliseconds returns int64; ParseDuration reads "1h15m30s"; Round and Truncate change precision. Time.Add and Time.Sub move between instants and durations.

Complete program

Complete program.

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

import (
    "fmt"
    "time"
)

func main() {
    // time.Duration is an int64 count of nanoseconds with unit constants.
    timeout := 30 * time.Second
    ttl := 8*time.Hour + 30*time.Minute
    fmt.Println(timeout, ttl) // String() prints 30s 8h30m0s

    // A variable count must be converted before multiplying.
    retries := 3
    backoff := time.Duration(retries) * 250 * time.Millisecond
    if backoff != 750*time.Millisecond {
        panic(backoff)
    }

    // Conversions out: Hours/Seconds return float64, Milliseconds returns int64.
    if ttl.Hours() != 8.5 || ttl.Milliseconds() != 30_600_000 {
        panic("conversion")
    }

    // Parse config strings such as "1h15m" or "250ms".
    d, err := time.ParseDuration("1h15m30.5s")
    if err != nil {
        panic(err)
    }
    fmt.Println(d, d.Round(time.Minute), d.Truncate(time.Hour))

    // Instant arithmetic: Add a Duration, Sub two Times to get one.
    issued := time.Date(2026, time.November, 8, 9, 0, 0, 0, time.UTC)
    expires := issued.Add(ttl)
    if expires.Sub(issued) != ttl || expires.Format(time.RFC3339) != "2026-11-08T17:30:00Z" {
        panic(expires)
    }

    // Calendar arithmetic is a different operation: AddDate(0, 1, 0) means "one month later".
    fmt.Println(expires, issued.AddDate(0, 1, 0).Format(time.DateOnly))

    // Durations can be negative, and overflow at about 292 years.
    fmt.Println(issued.Sub(expires), time.Duration(1<<63-1))
}

In practice: take time.Duration in APIs instead of an int with a unit in its name, parse config with time.ParseDuration, and use AddDate for calendar steps such as "one month later".

time.Duration(5) is 5 nanoseconds. time.Sleep(5) is the classic mistake; go vet does not catch it.

Durations overflow at about 292 years; Sub between distant times saturates to the minimum or maximum Duration.

ParseDuration has no unit for days ("d"); use hours.

Format and parse timestamps: Temporal.Instant, time.Parse layouts, jiff, std::chrono::parse

Go

Go formats and parses with a layout written as the reference time Mon Jan 2 15:04:05 MST 2006 (1 2 3 4 5 6 -0700), instead of %Y-style codes. time.RFC3339, time.DateOnly and time.DateTime are predefined layouts. time.Parse returns an error for invalid input, keeps the parsed offset, and treats a layout with no zone as UTC; time.ParseInLocation names the zone instead.

Complete program

Complete program.

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

import (
    "fmt"
    "time"
)

func main() {
    // Layouts are written as the reference time Mon Jan 2 15:04:05 MST 2006 (1 2 3 4 5 6 -7).
    t := time.Date(2026, time.November, 8, 14, 5, 9, 0, time.UTC)
    fmt.Println(t.Format(time.RFC3339))       // 2026-11-08T14:05:09Z
    fmt.Println(t.Format("2006-01-02 15:04")) // custom layout
    fmt.Println(t.Format("Mon, 02 Jan 2006")) // Sun, 08 Nov 2026
    fmt.Println(t.Format(time.DateOnly), t.Format(time.Kitchen))

    // Parse RFC 3339 input; the offset is kept and the instant compares equal.
    p, err := time.Parse(time.RFC3339, "2026-11-08T15:05:09+01:00")
    if err != nil {
        panic(err)
    }
    if !p.Equal(t) {
        panic(p)
    }
    fmt.Println(p, "->", p.UTC())

    // Fractional seconds: RFC3339Nano formats them; RFC3339 parsing accepts them too.
    if _, err := time.Parse(time.RFC3339, "2026-11-08T14:05:09.123Z"); err != nil {
        panic(err)
    }

    // A layout without a zone parses as UTC; ParseInLocation names the zone instead.
    local, _ := time.Parse("2006-01-02 15:04", "2026-11-08 10:00")
    fmt.Println(local.Location()) // UTC

    // Invalid input returns an error (no rollover).
    if _, err := time.Parse(time.RFC3339, "2026-02-30T10:00:00Z"); err == nil {
        panic("expected an error")
    } else {
        fmt.Println("error:", err)
    }

    // The classic bug is a layout with the wrong digits: "2006-02-01" means year-day-month.
    // go vet reports it ("2006-02-01 should be 2006-01-02").
}

In practice: use time.RFC3339 (or RFC3339Nano) for interchange, compare parsed times with Equal rather than ==, and write custom layouts by copying the reference date. go vet catches the common mistake of swapped month and day digits.

Use t.Equal(u), not t == u: == also compares the location and the monotonic reading.

time.Parse with an abbreviation like EST does not know its offset unless it matches the local zone; it fabricates a zero-offset location with that name.

Parse range-checks fields (an hour of 24 or 30 February is an error), but the RFC3339 layout still accepts some inputs the RFC does not, such as an offset of +24:00.

Convert between UTC, local time and time zones: Temporal.ZonedDateTime, time.LoadLocation, jiff, zoned_time

Go

time.LoadLocation("America/New_York") loads an IANA zone, t.In(loc) shows the same instant in that zone, and time.Date(..., loc) builds a wall time there with the right offset for that day. Zone data comes from the OS (/usr/share/zoneinfo), $ZONEINFO, or the time/tzdata package embedded in the binary. time.UTC and time.Local are predefined; Local comes from TZ or the OS.

Complete program

Complete program. Embeds time/tzdata, so it runs on hosts without zone files.

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

import (
    "fmt"
    "time"
    _ "time/tzdata" // embed the IANA database (~450 KB) for hosts without /usr/share/zoneinfo
)

func main() {
    newYork, err := time.LoadLocation("America/New_York")
    if err != nil {
        panic(err)
    }

    // A time.Time is an instant plus a location; In changes only how it is displayed.
    winter := time.Date(2026, time.January, 15, 17, 0, 0, 0, time.UTC)
    summer := time.Date(2026, time.July, 15, 17, 0, 0, 0, time.UTC)
    fmt.Println(winter.In(newYork).Format(time.RFC3339)) // 2026-01-15T12:00:00-05:00
    fmt.Println(summer.In(newYork).Format(time.RFC3339)) // 2026-07-15T13:00:00-04:00 (DST)

    // Build a wall-clock time in a zone: 09:00 in New York, whatever the offset that day.
    meeting := time.Date(2026, time.March, 9, 9, 0, 0, 0, newYork)
    fmt.Println(meeting.UTC().Format(time.RFC3339)) // 13:00Z: DST began on 8 March

    // DST-safe "add one day": AddDate steps the wall clock; Add(24 * time.Hour) does not.
    saturday := time.Date(2026, time.March, 7, 9, 0, 0, 0, newYork)
    sunday := saturday.AddDate(0, 0, 1)
    if sunday.Hour() != 9 || sunday.Sub(saturday) != 23*time.Hour || saturday.Add(24*time.Hour).Hour() != 10 {
        panic("AddDate must keep 09:00 across the DST change")
    }

    // Same instant, different wall times.
    kolkata, _ := time.LoadLocation("Asia/Kolkata")
    if !winter.In(kolkata).Equal(winter) {
        panic("In must not change the instant")
    }
    name, offset := winter.In(kolkata).Zone()
    fmt.Println(name, offset/60, "minutes") // IST 330 minutes

    // 02:30 on 8 March does not exist in New York (clocks jump 02:00 -> 03:00).
    // time.Date still returns a time, using one of the two offsets; which one is not guaranteed.
    gap := time.Date(2026, time.March, 8, 2, 30, 0, 0, newYork)
    if gap.Hour() == 2 {
        panic("a wall time in the gap cannot survive")
    }
    fmt.Println(gap.Format("15:04 MST"))

    // Unknown names are errors; time.Local is the process zone (from TZ or the OS).
    if _, err := time.LoadLocation("Mars/Olympus"); err == nil {
        panic("expected an error")
    }
    fmt.Println("local:", time.Local)
}

In practice: keep times in UTC internally, load each Location once at startup, and import _ "time/tzdata" in programs that run in minimal containers without zoneinfo. For "same time tomorrow", use t.AddDate(0, 0, 1), which steps the wall clock in t's location; t.Add(24 * time.Hour) is exact time and lands an hour off across a DST change. Wall times in a DST gap or overlap are ambiguous; time.Date picks an offset and does not report it.

time/tzdata adds about 450 KB; alternatively build with -tags timetzdata.

In does not change the instant: winter.In(loc).Equal(winter) is true.

time.FixedZone("X", -5*3600) is a fixed offset with no DST, useful only for parsed offsets.

Generate reproducible random numbers: seeded PRNGs, rand.NewPCG, StdRng, std::mt19937

Go

math/rand/v2 (Go 1.22+) separates sources from the Rand methods. The top-level functions (rand.IntN, rand.Shuffle) use a randomly seeded generator that cannot be reseeded. For a reproducible sequence, own one: rand.New(rand.NewPCG(seed1, seed2)) (or rand.NewChaCha8(seed)), then call IntN, Float64, Perm, Shuffle and NormFloat64 on it.

Complete program

Complete program (Go 1.22+).

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

import (
    "fmt"
    "math/rand/v2"
    "slices"
)

func rolls(r *rand.Rand, n int) []int {
    out := make([]int, n)
    for i := range out {
        out[i] = r.IntN(6) + 1 // [1, 6]
    }
    return out
}

func main() {
    // The top-level functions (rand.IntN, rand.Shuffle) are randomly seeded and cannot be reseeded.
    // For repeatable runs, own a generator: PCG takes two uint64 seed words.
    const seed1, seed2 = 42, 1024
    a := rand.New(rand.NewPCG(seed1, seed2))
    b := rand.New(rand.NewPCG(seed1, seed2))
    first, second := rolls(a, 5), rolls(b, 5)
    if !slices.Equal(first, second) {
        panic("same seed must give the same sequence")
    }

    names := []string{"ann", "bo", "cy", "di"}
    r := rand.New(rand.NewPCG(seed1, seed2))
    r.Shuffle(len(names), func(i, j int) { names[i], names[j] = names[j], names[i] })

    // Other draws: a permutation, a float in [0, 1), standard normal and exponential values.
    fmt.Printf("rolls=%v order=%v perm=%v\n", first, names, r.Perm(4))
    fmt.Printf("float=%.3f normal=%.3f exp=%.3f\n", r.Float64(), r.NormFloat64(), r.ExpFloat64())
}

In practice: pass a *rand.Rand into code that needs randomness, seed it from a flag or test parameter, and log the seed. PCG is the fast default for simulations; ChaCha8 is also seedable and is cryptographically strong.

The old math/rand package's rand.Seed is deprecated (a no-op since Go 1.24 unless GODEBUG randseednop=0); use v2 with an explicit source.

A *rand.Rand is not safe for concurrent use; give each goroutine its own, seeded from the parent.

Shuffle and Perm consume values from the generator, so adding a call earlier in a test changes everything drawn after it; use one generator per independent stream.

Generate secure random tokens: crypto.getRandomValues, crypto/rand, getrandom, OS CSPRNGs

Go

crypto/rand reads the OS generator. rand.Text (Go 1.24+) returns a 26-character base32 string with at least 128 bits of randomness, ready to use as a token; rand.Read fills a byte slice; rand.Int returns an unbiased big.Int below a bound. Since Go 1.24, Read never returns an error: if the OS source fails, the program crashes rather than continue with weak randomness.

Complete program

Complete program (Go 1.24+ for rand.Text).

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

import (
    "crypto/rand"
    "crypto/subtle"
    "encoding/base64"
    "encoding/hex"
    "fmt"
    "math/big"
)

func main() {
    // rand.Text (Go 1.24+): 26 base32 characters, at least 128 bits of entropy.
    token := rand.Text()
    if len(token) != 26 {
        panic(token)
    }

    // Raw bytes from the OS CSPRNG. Since Go 1.24, Read never returns an error
    // (the program crashes instead if the OS source fails).
    key := make([]byte, 32)
    rand.Read(key)
    fmt.Println("key:", hex.EncodeToString(key)[:16]+"...")
    fmt.Println("url token:", base64.RawURLEncoding.EncodeToString(key))

    // An unbiased integer in [0, 1_000_000) for a one-time code.
    n, err := rand.Int(rand.Reader, big.NewInt(1_000_000))
    if err != nil {
        panic(err)
    }
    code := fmt.Sprintf("%06d", n.Int64())

    // Compare secrets in constant time.
    if subtle.ConstantTimeCompare([]byte(token), []byte(token)) != 1 {
        panic("compare")
    }
    fmt.Println("token:", token, "code:", code)
}

In practice: use rand.Text for tokens and IDs, rand.Read plus base64.RawURLEncoding for raw keys, and crypto/subtle.ConstantTimeCompare to check secrets. Do not use math/rand for anything security-related.

Before Go 1.24, check the error from rand.Read; code that ignores it is still common in older projects.

math/rand/v2 ChaCha8 is cryptographically strong but seedable; for secrets prefer crypto/rand, which is never seeded by you.

ConstantTimeCompare returns 0 immediately for different lengths, which leaks only the length.