System Design

G14

Standard library tour

These are the packages you use every day. Each one has one idiom to know and one trap that costs a production bug. The outputs and costs below come from real runs.

Not startedSaved in this browser only.
  1. 1Check the package before you write a loop. Most small helpers arrived between Go 1.21 and 1.27.
  2. 2A scanner, a buffered writer and a decoder report errors late. Check Err, Flush and Close.
  3. 3A time.Time from time.Now holds two clocks. Compare with Equal, and format in UTC.
  4. 4A path from a client goes through os.Root. String checks on the path miss symlinks.
G14
    A

    The trap

    one long line, exit code 0
    count the lines in a loggo
    package main
    
    import (
      "bufio"
      "fmt"
      "strings"
    )
    
    func main() {
      long := strings.Repeat("x", 70_000)1
      input := "first\n" + long + "\nthird\n"
    
      sc := bufio.NewScanner(strings.NewReader(input))
      lines := 0
      for sc.Scan()2 {
        lines++
      }
      fmt.Println("lines:", lines)3
    }
    1. 1Longer than the scanner limit of 64 KB.
    2. 2Returns false at the long line, as it does at the end of the input.
    3. 3The program prints a count and exits 0. Nothing shows that it stopped early.
    programrecorded outputstatus
    As shownlines: 12 lines lost
    Print sc.Err()lines: 1 err: bufio.Scanner: token too longYou see the failure
    sc.Buffer with 1 MB, print sc.Err()lines: 3 err: <nil>All lines
    • The input has 3 lines. The first program counts 1.
    • A loop on Scan ends on end of input and on any error. Only Err tells the two apart.
    • The same pattern applies to rows.Next in database/sql and to a Decoder loop.
    • Line-based logs and CSV exports reach 64 KB in production, and rarely in a test.

    A Scanner stops at a line over 64 KB and returns false. I set a larger Buffer and I always check Err.

    B

    Reach for this

    what people hand-write, and what to use
    the jobwhat people hand-writeuse thissince
    Find an elementA for loop with a flagslices.Contains, slices.IndexFunc1.21
    Remove duplicatesA map of seen valuesslices.Sort, then slices.Compact1.21
    Sorted map keysAppend to a slice, then sort itslices.Sorted(maps.Keys(m))1.23
    Sort by several fieldsNested if statementscmp.Or(cmp.Compare(...), ...)1.22
    First value that is setif x == "" { x = def }cmp.Or(x, def)1.22
    Copy a map, clear a mapA loop over the keysmaps.Clone, clear(m)1.21
    Split at the first separatorstrings.Index and two slicesstrings.Cut1.18
    Split at the last separatorstrings.LastIndex and two slicesstrings.CutLast1.27
    Remove a known prefixHasPrefix, then s[n:]strings.CutPrefix1.20
    Loop over lines or fieldsstrings.Split, which allocates a slicestrings.Lines, strings.FieldsSeq1.24
    A date layout"2006-01-02" typed by handtime.DateOnly, time.DateTime1.20
    A path that stays in a folderHasPrefix(path, base)os.Root1.24
    Structured logs with levelsA wrapper around log.Printflog/slog1.21
    Match an error typevar e *T, then errors.As(err, &e)errors.AsType[*T](err)1.26
    A UUIDA third-party moduleuuid.New, uuid.NewV71.27
    Lazy setup, one timeA mutex and a boolsync.OnceValue (see G11)1.21
    Start and wait for goroutinesAdd, go, defer Donewg.Go (see G11)1.25

    Before I write a helper, I check slices, maps, strings and cmp. In a 45-minute build, each helper I skip saves a test too.

    C

    slices and maps

    the idiom and the trap
    rulestatus
    Assign the result: s = slices.Delete(s, i, j)Approved
    Sort before Compact or BinarySearchApproved
    slices.Clone before you change a slice you receivedApproved
    Keep a second slice of the array after Delete, Compact or InsertIt sees zeros or moved data
    Use maps.Keys as a sliceIt is an iterator
    Depend on the order of a map rangeThe order is random
    Use slices.SortFunc when equal rows must keep their orderUse SortStableFunc
    Use == on slices or mapsUse slices.Equal, maps.Equal

    cmp.Compare and slices.Sort order NaN before every other float. The < operator does not.

    Delete and Compact change the array in place. I use the slice they return, and I forget every other slice of that array.

    D

    Sort by several fields

    tested
    sortgo
    // SortPeople orders by team, then oldest first, then name.
    func SortPeople(people []Person) {
      slices.SortFunc1(people, func(a, b Person) int {
        return cmp.Or(2
          cmp.Compare(a.Team, b.Team),
          cmp.Compare(b.Age, a.Age)3,
          cmp.Compare(a.Name, b.Name),
        )
      })
    }
    1. 1The function returns negative, zero or positive. It is not stable.
    2. 2A plain function: Go evaluates every comparison before the call. A costly key belongs in an if statement.
    3. 3b before a: oldest first.
    wordsgo
    // TopWords returns the n most used words, most used first.
    func TopWords(text string, n int) []WordCount {
      counts := map[string]int{}
      for w := range strings.FieldsSeq1(strings.ToLower(text)) {
        counts[w]++
      }
      out := make([]WordCount, 0, len(counts))
      for _, w := range slices.Sorted(maps.Keys(counts))2 {
        out = append(out, WordCount{w, counts[w]})
      }
      slices.SortStableFunc3(out, func(a, b WordCount) int {
        return cmp.Compare(b.Count, a.Count)
      })
      return out[:min(n, len(out))]
    }
    1. 1Iterates without a result slice.
    2. 2Sorted keys remove the random map order.
    3. 3Stable: words with equal counts keep the sorted order, so the output is the same on each run.

    cmp.Or returns the first comparison that is not zero, so each sort key is one line. To reverse a key, I swap the arguments.

    E

    sort or slices

    measured: 1,000 structs of 40 bytes
    calltimeallocsstatus
    sort.Slice(s, less)76.2 µs3Existing code
    sort.Sort(byAge(s))50.4 µs1Needs 3 methods
    slices.SortFunc(s, f)66.5 µs0Approved
    • sort.Slice takes any, then swaps elements through reflection.
    • slices.SortFunc is generic, so the compiler checks the element type.
    • sort.Sort passes indexes. SortFunc copies two rows per comparison, so its gain depends on the row size.
    • For a large struct, sort pointers or use indexes. Measure before you change it.

    New code uses slices.SortFunc. It is typed, and it has no allocations. The sort package remains for existing code.

    F

    strings, strconv, bytes

    the idiom and the trap
    rulewhystatus
    Builder or Join for many parts959 ns against 9.4 µs for 100 parts.Approved
    strconv over fmt for one number19.3 ns against 63.5 ns.Approved
    Pass a bit size to ParseInt and ParseUintIt rejects a value that does not fit.Approved
    Use errors.Is with ErrRange, ErrSyntaxThe error wraps them.Approved
    TrimLeft to remove a prefixIt takes a set of characters.Use TrimPrefix
    len(s) to count charactersIt counts bytes. Use utf8.RuneCountInString.Not approved
    Keep buf.Bytes() past the next writeIt aliases the buffer.Use bytes.Clone
    Split("", ",") as an empty listIt returns one empty string.Check len(s)

    Strings are immutable, so += in a loop copies everything. I use a Builder or Join, and strconv for numbers on a hot path.

    G

    Cut and parse

    tested
    cutgo
    // ParseHeader splits "Key: value" at the first colon.
    func ParseHeader(line string) (key, value string, err error) {
      key, value, ok := strings.Cut(line, ":")1
      if !ok {
        return "", "", fmt.Errorf("%w4: %q", ErrBadHeader, line)
      }
      return strings.TrimSpace(key), strings.TrimSpace(value), nil
    }
    
    // SplitExt splits "a.tar.gz" at the last dot, into "a.tar" and "gz".
    func SplitExt(name string) (base, ext string) {
      base, ext, ok := strings.CutLast(name, ".")2
      if !ok {
        return name, ""
      }
      return base, ext
    }
    
    // ParsePort reads a TCP port. The bit size rejects 70000.
    func ParsePort(s string) (uint16, error) {
      n, err := strconv.ParseUint(s, 10, 16)3
      if err != nil {
        return 0, fmt.Errorf("port %q: %w", s, err)
      }
      return uint16(n), nil
    }
    1. 1Splits at the first colon, so a colon in the value stays there.
    2. 2Go 1.27.
    3. 3Base 10, 16 bits. It rejects 70000 and -1.
    4. 4Wraps the error, so errors.Is finds strconv.ErrRange.

    Cut replaces Index and two slices, and it returns found as a bool, so the not-found case is one branch.

    H

    The model: time.Time

    package time, Go 1.27
    t := time.Now()walldate and time; NTP can move itmonotonic (ext)only counts forward; this processloc *Locationtell the timeFormat, YearAddDatemeasure timeSub, SinceBefore, AfterEqual, CompareDrops the monotonic reading:In, UTC, Local, Round, Truncate, AddDate, MarshalJSON, MarshalTextKeeps it: Add. A value from Date, Parse or Unix never has one.
    • The wall clock tells the time. The monotonic clock measures it.
    • A comparison uses the monotonic reading only when both values have one.
    • On some systems the monotonic clock stops while the machine sleeps.

    time.Now holds a wall reading and a monotonic reading. Time.Since uses the monotonic one, so an NTP step cannot make it negative.

    I

    time: rules

    the idiom and the trap
    rulewhystatus
    time.Since(start) for elapsed timeIt uses the monotonic reading.Approved
    Multiply by the unit: 5 * time.SecondA bare 5 is 5 ns.Approved
    Equal to compare two times== also compares the zone pointer and the monotonic reading.Approved
    Time as a map keyThe key holds the same three fields.Use UnixNano or Round(0).UTC()
    AddDate(0, 1, 0) for "next month"January 31 becomes March 3 in 2026.Clamp the day yourself
    Add(24 * time.Hour) for "tomorrow"A day with a clock change has 23 or 25 hours.Use AddDate for dates
    A literal Z in a layoutIt prints Z in any zone, with local digits.Use RFC3339

    The reference date is Mon Jan 2 15:04:05 MST 2006: month 1, day 2, hour 3 (15), minute 4, second 5, year 6, zone offset -7.

    A Duration is an int64 of nanoseconds. Layouts use the reference date, and I store and send UTC.

    J

    See it: layouts and zones

    recorded: one moment in each layout
    zone

    t.Format

    2026-03-07T14:35:03+05:30

    Parses back without the 0.25 s.

    the moment

    2026-03-07T09:05:03.25Z

    • Pick a layout and a zone. The result shows the text that Format wrote.
    • The second line is what a reader gets from that text alone. The reader has no other information about the zone.
    • RFC3339 drops the fraction, and RFC3339Nano keeps it. In this list, only those two keep the zone offset.

    I send RFC3339 in UTC. A layout with no zone, or with a literal Z, gives a reader the wrong moment.

    K

    time.Now in tests

    tested
    expirygo
    // Valid reports whether the token has time left.
    func (t Token) Valid() bool {
      return time.Now().Before(t.Expires)1
    }
    
    // Issue makes a token that lives for ttl.
    func Issue(value string, ttl time.Duration) Token {
      return Token{Value: value, Expires: time.Now().Add(ttl)}
    }
    
    // Timed returns how long f took, on the monotonic clock.
    func Timed(f func()) time.Duration {
      start := time.Now()
      f()
      return time.Since(start)2
    }
    
    // Stamp formats a moment for an API: UTC, fixed layout.
    func Stamp(t time.Time) string {
      return t.UTC().Format(time.RFC3339)3
    }
    1. 1Plain time.Now. The code has no clock parameter.
    2. 2Monotonic, also for a run that crosses a clock change.
    3. 3One zone and one layout for every API response.
    test the expirygo
    func TestTokenExpires(t *testing.T) {
      synctest.Test1(t, func(t *testing.T) {
        tok := Issue("abc", time.Hour)
        time.Sleep(time.Hour - time.Nanosecond)2
        if !tok.Valid() {
          t.Fatal("expired too early")
        }
        time.Sleep(time.Nanosecond)3
        if tok.Valid() {
          t.Fatal("still valid at the expiry")
        }
      })
    }
    1. 1The bubble clock starts at midnight UTC on 2000-01-01.
    2. 2Every goroutine in the bubble is blocked, so the clock jumps at once.
    3. 3The test checks the exact boundary. A real clock cannot do this.

    I do not inject a clock interface for this. In a synctest bubble, time.Now and time.Sleep use a fake clock, so the test takes no real time.

    L

    io and bufio

    the idiom and the trap
    rulestatus
    io.Copy to stream, with a LimitReader on input you do not trustApproved
    bufio.Writer for many small writes: 160 ns against 3.2 µs per lineApproved
    Return the error from Flush, and from Close on a file you wroteApproved
    Check Scanner.Err after every Scan loopApproved
    Read returns n > 0 and an error together. Use the n bytes firstApproved
    io.ReadAll on a body or file with no limitMemory follows the input
    defer f.Close() on a written file, error ignoredA failed write is lost
    Exit with data in a bufio.WriterThe bytes are lost
    linesgo
    // CountLines counts lines of up to limit bytes each.
    func CountLines(r io.Reader, limit int) (int, error) {
      sc := bufio.NewScanner(r)
      sc.Buffer(make([]byte, 0, 64*1024), limit)1
      lines := 0
      for sc.Scan() {
        lines++
      }
      if err := sc.Err()2; err != nil {
        return lines, fmt.Errorf("line %d: %w", lines+1, err)
      }
      return lines, nil
    }
    1. 1Start at 64 KB. The buffer grows up to limit.
    2. 2The fix from panel A.
    copygo
    // Save copies r to w, stops at limit bytes, and returns the
    // SHA-256 of what it wrote.
    func Save(w io.Writer, r io.Reader, limit int64) (string, error) {
      h := sha256.New()
      src := io.LimitReader(r, limit+1)1
      n, err := io.Copy(io.MultiWriter(w, h)2, src)
      if err != nil {
        return "", fmt.Errorf("copy: %w", err)
      }
      if n > limit {
        return "", fmt.Errorf("input over %d bytes", limit)
      }
      return hex.EncodeToString(h.Sum(nil)), nil
    }
    1. 1One byte more than the limit, so the code can tell at the limit from over it.
    2. 2Every byte goes to the file and to the hash, with no second read.

    I compose readers and writers instead of loading a file. Copy streams, LimitReader bounds it, and MultiWriter hashes it on the way.

    M

    os and path/filepath

    the idiom and the trap
    rulewhystatus
    filepath for OS paths, path for URLsfilepath uses the OS separator. path always uses a slash.Approved
    WalkDir, not WalkWalk calls Lstat on every file.Approved
    errors.Is(err, fs.ErrNotExist)It sees through the wrapped path error.Approved
    Temp file in the target folder, then RenameRename replaces the file in one step on one filesystem.Approved
    Join(base, clientPath) as a safety check ../.. leaves base after the clean.Not approved
    HasPrefix(path, base)A symlink inside base leaves it.Not approved
    os.WriteFile for a file that readers openA reader can see a partial file.Use a rename

    filepath.Join cleans the path, so it does not protect anything. A client path needs IsLocal or, better, os.Root.

    N

    Replace a file in one step

    tested
    atomicgo
    // WriteLines replaces path in one step. A reader sees the old
    // file or the new file, never a partial one.
    func WriteLines(path string, lines []string) (err error) {
      dir := filepath.Dir(path)
      f, err := os.CreateTemp(dir, ".tmp-*")1
      if err != nil {
        return fmt.Errorf("create temp: %w", err)
      }
      defer func() {
        if err != nil {
          err = errors.Join(err, os.Remove(f.Name())2)
        }
      }()
      w := bufio.NewWriter(f)
      for _, l := range lines {
        if _, err := fmt.Fprintln(w, l); err != nil {
          return errors.Join(fmt.Errorf("write: %w", err), f.Close()5)
        }
      }
      if err := w.Flush()3; err != nil {
        return errors.Join(fmt.Errorf("flush: %w", err), f.Close())
      }
      if err := f.Sync()4; err != nil {
        return errors.Join(fmt.Errorf("sync: %w", err), f.Close())
      }
      if err := f.Close(); err != nil {
        return fmt.Errorf("close: %w", err)
      }
      if err := os.Rename(f.Name(), path); err != nil {
        return fmt.Errorf("rename: %w", err)
      }
      return nil
    }
    1. 1The same folder, so Rename stays on one filesystem.
    2. 2On any failure the temp file goes, and the old file stays.
    3. 3Without it the last 4 KB stays in memory.
    4. 4Puts the bytes on disk before the rename makes them visible.
    5. 5Close can report a failed write, so its error counts here.

    I write to a temp file in the same folder, sync it, then rename it. A reader sees the old file or the new one.

    O

    Stay inside a folder: os.Root

    since Go 1.24, ReadFile since Go 1.25
    rootgo
    // ReadUpload reads a file by a name the client chose. The
    // root refuses a path or a symlink that leaves dir.
    func ReadUpload(dir, name string) ([]byte, error) {
      root, err := os.OpenRoot(dir)1
      if err != nil {
        return nil, fmt.Errorf("open root: %w", err)
      }
      defer root.Close()
      b, err := root.ReadFile(name)2
      if err != nil {
        return nil, fmt.Errorf("read upload: %w", err)
      }
      return b, nil
    }
    1. 1Holds the folder open. Later paths resolve against it, step by step.
    2. 2The kernel call runs relative to the open folder, so a rename race cannot redirect it.
    name from the clientos.ReadFileroot.ReadFile
    okRead "hi"Read "hi"
    ../secretRead "key"Refused
    linkRead "key"Refused
    • The row "link" is a symlink inside the folder that points outside it. A string check on the name passes it.
    • An open root costs about the same as os.ReadFile: 23.6 µs against 24.4 µs.
    • Opening the root for each call costs 42.6 µs. A server keeps one root open.
    • Root.FS gives an fs.FS for http.FileServerFS or templates.

    os.Root is opened on a folder, and each path resolves from there. A dot-dot path or a symlink that leaves the folder fails.

    P

    log/slog

    tested
    sloggo
    // Secret logs as a fixed text, whatever it holds.
    type Secret string
    
    // LogValue is called by every handler.
    func (Secret) LogValue() slog.Value1 {
      return slog.StringValue("[redacted]")
    }
    
    type requestIDKey struct{}
    
    // WithRequestID stores the ID that every log line will carry.
    func WithRequestID(ctx context.Context, id string) context.Context {
      return context.WithValue(ctx, requestIDKey{}, id)
    }
    
    // contextHandler copies the request ID from ctx to the record.
    type contextHandler struct{ slog.Handler }2
    
    func (h contextHandler) Handle(
      ctx context.Context, r slog.Record,
    ) error {
      if id, ok := ctx.Value(requestIDKey{}).(string); ok {
        r.AddAttrs(slog.String("request_id", id))3
      }
      return h.Handler.Handle(ctx, r)
    }
    
    // NewLogger writes JSON lines at the level in lvl, which a
    // running program can change.
    func NewLogger(w io.Writer, lvl *slog.LevelVar4) *slog.Logger {
      opts := &slog.HandlerOptions{Level: lvl}
      return slog.New(contextHandler{slog.NewJSONHandler(w, opts)})
    }
    1. 1Every handler calls LogValue, so one type rule covers all call sites.
    2. 2Embedding keeps Enabled, WithAttrs and WithGroup. Only Handle changes.
    3. 3Reads the ID from the ctx of InfoContext. Plain Info passes a background context.
    4. 4Set changes the level while the program runs, with no restart.
    rulestatus
    Use InfoContext, and pass the request ctxApproved
    Use log.With for fields of one request or jobApproved
    Let the level gate the cost: 11.9 ns off, 754 ns onApproved
    Use slog.DiscardHandler in tests that do not read logsApproved
    Build a costly value before a Debug callUse LogValuer
    Key and value lists with a missing value!BADKEY, see the drill
    Log a struct that holds a passwordUse LogValuer
    Log inside a tight loop at InfoUse a metric

    A disabled line costs a level check and the arguments. In this benchmark neither case allocates.

    Every line carries a request ID from the context. A secret type logs as redacted, whichever call site logs it.

    Q

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.20strings and bytes CutPrefix, CutSuffix. time.DateTime, DateOnly, TimeOnly, Time.Compare. filepath.IsLocal. errors.Join.Named layouts replace typed ones.
    1.21Packages slices, maps, cmp and log/slog. Built-in min, max and clear.Most small helpers are no longer needed.
    1.22cmp.Or. slices.Concat. Delete, DeleteFunc, Compact, CompactFunc and Replace zero the freed tail. Insert always panics on a bad index.A second slice of the array sees zeros.
    1.23Iterators: slices.Sorted, Collect, Chunk, All, Values; maps.Keys, Values, All. slices.Repeat. os.CopyFS. filepath.Localize.maps.Keys returns an iterator, not a slice.
    1.24os.Root. strings and bytes Lines, SplitSeq, FieldsSeq. slog.DiscardHandler. testing.B.Loop.Paths from clients have a safe API.
    1.25Root adds ReadFile, WriteFile, MkdirAll, Rename, RemoveAll and more. testing/synctest. slog.GroupAttrs and Record.Source.Root now covers the usual file calls.
    1.26io.ReadAll uses less memory. bytes.Buffer.Peek. slog.NewMultiHandler. errors.AsType.One logger can write to two handlers.
    1.27strings.CutLast and bytes.CutLast. New package uuid. go test runs the stdversion vet check. encoding/json/v2 (see G15).UUIDs need no third-party module.
    R

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildThe prompt asks for a list in a fixed order.slices.SortFunc with cmp.Or. Add the ID as the last key, so the order is total and the test is stable.
    buildA store is a map, and a test compares results.slices.Sorted(maps.Keys(m)). Map order changes between runs and fails a test only sometimes.
    buildA rule depends on the current time.Call time.Now, and test inside synctest.Test. The test is exact and instant.
    buildThe service must read a file of records.bufio.Scanner with Buffer and Err, or a json.Decoder (see G15).
    talk"How do you store timestamps?"UTC in the database, RFC3339 on the wire, local zone only at display time.
    talk"How do you log in production?"slog with a JSON handler, a request ID from the context, and a LevelVar I can change at run time.
    talk"A client names a file. What can go wrong?"Path traversal, by dot-dot or by symlink. os.Root refuses both.
    talk"Why not sort.Slice?"It works. SortFunc has a typed function and no allocations. For code that runs, I keep it until a change touches it.

    I use the standard library first. I add a dependency only when I can name what the standard library cannot do.

    S

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. Predict the output.

      package main
      
      import (
        "fmt"
        "time"
      )
      
      func main() {
        t := time.Date(2026, 3, 7, 9, 5, 0, 0, time.UTC)
        fmt.Println(t.Format("YYYY-MM-DD"))
        fmt.Println(t.Format("2006-01-02"))
        swapped := "2006-02-01"
        fmt.Println(t.Format(swapped))
      }
    2. Predict the output.

      package main
      
      import (
        "fmt"
        "time"
      )
      
      func main() {
        a := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
        india := time.FixedZone("IST", 5*3600+1800)
        b := a.In(india)
        fmt.Println(a == b, a.Equal(b))
      
        now := time.Now()
        wall := now.Round(0)
        fmt.Println(now == wall, now.Equal(wall))
      }
    3. Predict the output.

      package main
      
      import (
        "fmt"
        "time"
      )
      
      func main() {
        jan31 := time.Date(2026, 1, 31, 0, 0, 0, 0, time.UTC)
        fmt.Println(jan31.AddDate(0, 1, 0).Format(time.DateOnly))
      }
    4. Predict the output.

      package main
      
      import (
        "fmt"
        "time"
      )
      
      func main() {
        seconds := 30
        fmt.Println(time.Duration(seconds))
        fmt.Println(time.Duration(seconds) * time.Second)
      
        d := 90 * time.Minute
        fmt.Println(d, d.Hours(), int(d.Hours()))
      }
    5. Predict the output.

      package main
      
      import (
        "fmt"
        "strings"
      )
      
      func main() {
        fmt.Printf("%q\n", strings.Split("", ","))
        fmt.Printf("%q\n", strings.Split("a,,b", ","))
        fmt.Printf("%q\n", strings.Fields(""))
        fmt.Printf("%q\n", strings.Fields("  a   b "))
      }
    6. Predict the output.

      package main
      
      import (
        "fmt"
        "strings"
      )
      
      func main() {
        fmt.Println(strings.TrimLeft("abacus", "ab"))
        fmt.Println(strings.TrimPrefix("abacus", "ab"))
        fmt.Println(strings.TrimSuffix("report.go.go", ".go"))
        fmt.Println(strings.TrimRight("report.go.go", ".go"))
      }
    7. Predict the output.

      package main
      
      import (
        "errors"
        "fmt"
        "strconv"
      )
      
      func main() {
        n, err := strconv.ParseInt("300", 10, 8)
        fmt.Println(n, err)
        fmt.Println(errors.Is(err, strconv.ErrRange))
      
        fmt.Println(string(rune(65)), strconv.Itoa(65))
      }
    8. Predict the output.

      package main
      
      import (
        "fmt"
        "slices"
      )
      
      func main() {
        a := []int{1, 2, 1, 2, 2}
        fmt.Println(slices.Compact(a))
      
        b := []int{1, 2, 1, 2, 2}
        slices.Sort(b)
        fmt.Println(slices.Compact(b))
      }
    9. Predict the output.

      package main
      
      import (
        "fmt"
        "slices"
      )
      
      func main() {
        a := []int{1, 2, 3, 4}
        b := slices.Delete(a, 1, 2)
        fmt.Println(a, len(a))
        fmt.Println(b, len(b))
      }
    10. Predict the output.

      package main
      
      import (
        "bytes"
        "fmt"
      )
      
      func main() {
        var buf bytes.Buffer
        buf.WriteString("first")
        saved := buf.Bytes()
        copied := bytes.Clone(saved)
      
        buf.Reset()
        buf.WriteString("SECOND")
        fmt.Println(string(saved), string(copied))
      }
    11. Predict the output. The program has two print calls.

      package main
      
      import (
        "bufio"
        "fmt"
        "os"
      )
      
      func main() {
        w := bufio.NewWriter(os.Stdout)
        fmt.Fprintln(w, "written to the buffer")
        fmt.Println("buffered bytes:", w.Buffered())
      }
    12. Predict the output. The time attribute is removed for a stable result.

      package main
      
      import (
        "log/slog"
        "os"
      )
      
      func main() {
        h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
          ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
            if a.Key == slog.TimeKey {
              return slog.Attr{}
            }
            return a
          },
        })
        log := slog.New(h)
        args := []any{"user", 7, "orphan"}
        log.Info("saved", args...)
        log.Debug("hidden")
      }
    T

    Numbers to say

    measured with testing.B
    sort 1,000
    66.5 µs with 0 allocations; sort.Slice 76.2 µs with 3.
    concat 100
    762 ns Join; 959 ns Builder; 9.4 µs with +=.
    one int
    11.6 ns AppendInt; 19.3 ns Itoa; 63.5 ns Sprintf.
    time.Now
    65.7 ns, with no allocation.
    slog line
    754 ns as JSON; 11.9 ns below the level.
    file write
    3.2 µs per line; 160 ns with bufio.
    ratio
    bufio makes small writes about 20 times cheaper.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs of 1 s, on a busy machine. Use these as orders of magnitude.