SyntaxPilot
Courses/Go Programming/Lesson 78
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 78 of 89

Interview prep: language fundamentals

slice aliasing and append questionsnil map vs nil slicenil interface trapvalue vs pointer receivers and method setsdefer evaluation order puzzlesclosures in loops before and after Go 1.22string immutability and rune iterationinterface satisfactionerror wrapping questionsgenerics questions

These are the notes for Go episode 78, the first of three interview-prep episodes. An interview is like a driving test: you drive every day, but the examiner picks the odd cases on purpose. Each of the ten questions below is a "what does this print?" where the obvious answer is wrong. For each one: predict (write your answer down first), run (the real output is below), explain the mechanism, and state the rule in one line. Being able to say the rule is what passes the interview.

All outputs below are from real runs (Go 1.24.7, linux/amd64, 14 November 2026), through the same runner the video's compiler uses. The runner prints each command as $ command and prints the error stream (stderr) after the normal output.

Facts and sources

  • The Go specification (doc/go_spec.html in Go 1.24.7), "For statements with for clause": each iteration has its own separate declared variable; "Prior to Go 1.22, iterations share one set of variables instead of having their own separate variables."
  • The language version of a file comes from the go line in go.mod; a //go:build go1.21 constraint on a file sets that file's version (supported by Go 1.21 and later toolchains). That is how one module below shows both loop behaviours.
  • Every error message quoted below is copied from a real run of the Go 1.24.7 compiler or runtime.

How to answer a "what does this print?" question

  1. Read every line; spot the mechanism being tested (sharing, nil, copies, evaluation time, versions, bytes).
  2. Say your prediction and why, out loud.
  3. If unsure, explain both possibilities and what decides between them.
  4. Finish with the rule and the fix.

Q1 · Slice aliasing and append

Predict first: a := []int{1, 2, 3, 4}; b := a[:2]; b = append(b, 99); fmt.Println(a, b). The obvious guess, "a is untouched", is wrong.

main.go:

package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4}
    b := a[:2]        // b shares a's backing array
    b = append(b, 99) // room left in the array: no new array
    fmt.Println(a, b)

    c := []int{1, 2, 3}
    d := append(c, 4) // full: append makes a new array
    d[0] = 100
    fmt.Println(c, d)
}

Commands:

$ go run .

Output:

$ go run .
[1 2 99 4] [1 2 99]
[1 2 3] [100 2 3 4]

Why. From episode 14, a slice is a header: a pointer to a backing array (the real block of memory), a length (how many elements the slice shows) and a capacity (how many elements the array has from the slice's start). b := a[:2] shares a's array, with length 2 and capacity 4. append has room, so it writes 99 straight into slot 2, which is a[2]. Two slices that share one array are said to alias each other. c was full (len == cap), so append allocated a new, bigger array and copied; d no longer shares anything with c.

Fix: a full slice expression a[low:high:max] limits the capacity to max - low:

main.go:

package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4}
    b := a[:2:2]      // full slice expression: cap(b) is 2
    b = append(b, 99) // no room: a new array, a is safe
    fmt.Println(a, b)
    fmt.Println(len(b), cap(b))
}

Commands:

$ go run .

Output:

$ go run .
[1 2 3 4] [1 2 99]
3 4

Now append has no room and makes b its own array (length 3; the new capacity, 4, is chosen by the runtime's growth rule). slices.Clone(a[:2]) also gives an independent copy.

Rule: append may share memory or may not; never rely on either. Return the new slice and use it; cap the capacity when you hand out a sub-slice.

Q2 · nil map vs nil slice

nil means "no memory has been made yet": the zero value of slices, maps, pointers, channels, functions and interfaces.

main.go:

package main

import "fmt"

func main() {
    var s []int          // nil slice
    var m map[string]int // nil map
    fmt.Println(s == nil, len(s), m == nil, len(m))

    s = append(s, 1) // fine: append allocates
    fmt.Println(s)

    fmt.Println(m["chai"]) // reading a nil map: fine, zero value
    for k := range m {     // ranging: fine, no iterations
        fmt.Println(k)
    }
    m["chai"] = 10 // writing...
    fmt.Println(m)
}

Commands:

$ go run .

Output:

$ go run .
true 0 true 0
[1]
0
panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
    main.go:17 +0x24c
exit status 2
Operation nil slice nil map
len 0 0
read (s[0] / m[k]) panics: index out of range zero value
range no iterations no iterations
append(s, x) / m[k] = v works: append allocates panic: assignment to entry in nil map
delete(m, k) — does nothing

Why the difference: append returns a new slice header, so it can allocate an array and hand it back. A map write m[k] = v returns nothing; there is no way to give you a new map, so the map must already exist.

Fix: m := make(map[string]int) or m := map[string]int{}. In a struct, initialise maps in a constructor (NewX).

Rule: a nil slice is ready to use; a nil map is read-only.

Q3 · The nil interface trap

main.go:

package main

import "fmt"

type OrderError struct{ ID int }

func (e *OrderError) Error() string { return "order failed" }

func place(id int) error {
    var err *OrderError // nil pointer
    if id < 0 {
        err = &OrderError{ID: id}
    }
    return err // looks like "no error"...
}

func main() {
    err := place(42)
    if err != nil {
        fmt.Println("failed:", err)
        return
    }
    fmt.Println("placed")
}

Commands:

$ go run .

Output:

$ go run .
failed: order failed

A good order, reported as a failure.

Why. Episode 77 opened an interface up: it is two words, a type (or itab) and a value. return err converts the nil *OrderError into an error: the type word becomes *OrderError, only the value word is nil. err != nil compares the interface with a nil interface (both words empty), so it is true. Printing it calls Error() on the nil pointer, which works here because the method doesn't read any field.

Fix:

main.go:

package main

import "fmt"

type OrderError struct{ ID int }

func (e *OrderError) Error() string { return "order failed" }

func place(id int) error {
    if id < 0 {
        return &OrderError{ID: id}
    }
    return nil // a real nil interface: both words empty
}

func main() {
    err := place(42)
    if err != nil {
        fmt.Println("failed:", err)
        return
    }
    fmt.Println("placed")
}

Commands:

$ go run .

Output:

$ go run .
placed

Rule: a function that returns error must return nil literally on success, never a typed nil pointer variable.

Q4 · Value vs pointer receivers and method sets

The receiver is the value a method is called on: c in func (c Counter) IncValue(). A value receiver gets a copy; a pointer receiver gets the address of the original.

main.go:

package main

import "fmt"

type Counter struct{ n int }

func (c Counter) IncValue()    { c.n++ } // works on a copy
func (c *Counter) IncPointer() { c.n++ } // works on the original

type Incer interface{ IncPointer() }

func main() {
    c := Counter{}
    c.IncValue()
    c.IncValue()
    fmt.Println("after IncValue:", c.n)
    c.IncPointer() // Go writes (&c).IncPointer() for you
    fmt.Println("after IncPointer:", c.n)

    var i Incer = c // a Counter value in an Incer?
    i.IncPointer()
}

Commands:

$ go run .

Output:

$ go run .
# shop
./main.go:20:19: cannot use c (variable of struct type Counter) as Incer value in variable declaration: Counter does not implement Incer (method IncPointer has pointer receiver)

It doesn't compile. The fix, storing a pointer:

main.go:

package main

import "fmt"

type Counter struct{ n int }

func (c Counter) IncValue()    { c.n++ } // works on a copy
func (c *Counter) IncPointer() { c.n++ } // works on the original

type Incer interface{ IncPointer() }

func main() {
    c := Counter{}
    c.IncValue()
    c.IncValue()
    fmt.Println("after IncValue:", c.n)
    c.IncPointer() // Go writes (&c).IncPointer() for you
    fmt.Println("after IncPointer:", c.n)

    var i Incer = &c // a *Counter: its method set has IncPointer
    i.IncPointer()
    fmt.Println("after i.IncPointer:", c.n)
}

Commands:

$ go run .

Output:

$ go run .
after IncValue: 0
after IncPointer: 1
after i.IncPointer: 2

Why.

  • IncValue changes a copy, so n stays 0.
  • c.IncPointer() works on a variable because Go automatically takes its address: (&c).IncPointer() (episode 20).
  • The method set of a type is the set of methods you can call on a value of that type through an interface:
Type Method set
Counter methods with value receivers (IncValue)
*Counter methods with value and pointer receivers (IncValue, IncPointer)

An interface holds a copy of the value; Go cannot take the address of that hidden copy for you (and changing a copy would be pointless anyway), so a Counter does not satisfy Incer. A *Counter does, and changes reach the original: 2.

Rule: if any method has a pointer receiver, put a pointer (&c) in the interface. Keep receivers consistent for a type (all pointer, or all value).

Q5 · defer puzzles

Predict first: the obvious guesses are 0 1 2, x was 2, double: 3.

main.go:

package main

import "fmt"

func double() (n int) {
    defer func() { n *= 2 }() // runs after "return 3" sets n
    return 3
}

func main() {
    for i := 0; i < 3; i++ {
        defer fmt.Println("loop defer", i)
    }

    x := 1
    defer fmt.Println("x was", x) // x is evaluated NOW
    x = 2

    fmt.Println("double:", double())
}

Commands:

$ go run .

Output:

$ go run .
double: 6
x was 1
loop defer 2
loop defer 1
loop defer 0
Rule Shows up as
deferred calls run when the function returns, last in, first out (LIFO, like a stack of plates) 2 1 0, printed last, after main's other output
a deferred call's arguments are evaluated at the defer statement x was 1
return 3 first sets the named result n = 3, then defers run and may change it double: 6

The third rule is how a deferred function can add context to a returned error or turn a panic into an error with recover (episode 26):

main.go:

package main

import (
    "errors"
    "fmt"
)

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

var ErrOutOfStock = errors.New("out of stock")

func main() {
    fmt.Println(safeDivide(10, 2))
    fmt.Println(safeDivide(10, 0))
    e := fmt.Errorf("checkout: %w", fmt.Errorf("order 7: %w", ErrOutOfStock)) // wrapped twice
    fmt.Println(e, errors.Is(e, ErrOutOfStock))
}

Commands:

$ go run .

Output:

$ go run .
5 <nil>
0 safeDivide(10, 0): runtime error: integer divide by zero
checkout: order 7: out of stock true

Q6 · Closures in loops: before and after Go 1.22

A closure is a function value that uses variables from the code around it (episode 10). It captures the variable itself, not a copy of its value at that moment.

go.mod:

module shop

go 1.24

old.go:

//go:build go1.21

package main

import "fmt"

func oldLoop() { // this file is compiled with Go 1.21 rules
    var prints []func()
    for i := 0; i < 3; i++ {
        prints = append(prints, func() { fmt.Print(i, " ") })
    }
    for _, p := range prints {
        p()
    }
    fmt.Println("<- Go 1.21")
}

main.go:

package main

import "fmt"

func main() {
    oldLoop()
    var prints []func()
    for i := 0; i < 3; i++ { // Go 1.22+: a new i every iteration
        prints = append(prints, func() { fmt.Print(i, " ") })
    }
    for _, p := range prints {
        p()
    }
    fmt.Println("<- Go 1.22+")
}

Commands:

$ go run .

Output:

$ go run .
3 3 3 <- Go 1.21
0 1 2 <- Go 1.22+
  • Before Go 1.22: a for loop had one i, shared by every iteration. The three closures all saw its final value, 3.
  • Go 1.22 and later: each iteration has its own i, so the closures print 0, 1, 2. The Go spec: "Prior to Go 1.22, iterations share one set of variables instead of having their own separate variables."
  • The behaviour follows the language version: the go line in go.mod (here go 1.24), or a //go:build go1.21 line on one file.
  • The same applied to goroutines started in a loop (go func() { use(i) }()), a classic data race before 1.22.
  • Fix in old code: i := i as the first line inside the loop, or pass i as an argument.

Rule: since Go 1.22 each iteration gets a fresh loop variable; check the module's go version before answering.

Q7 · String immutability and rune iteration

main.go:

package main

import "fmt"

func main() {
    s := "chai"
    s[0] = 'C' // change one letter?
    fmt.Println(s)
}

Commands:

$ go run .

Output:

$ go run .
# shop
./main.go:7:5: cannot assign to s[0] (neither addressable nor a map index expression)

Strings are immutable: once created, their bytes never change. That is why strings can be shared, used as map keys and passed around without copying.

main.go:

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    s := "chai"
    b := []byte(s) // a copy we can change
    b[0] = 'C'
    fmt.Println(s, string(b))

    t := "चाय" // chai, in Hindi
    fmt.Println(len(t), utf8.RuneCountInString(t))
    fmt.Println(t[0]) // a byte, not a letter
    for i, r := range t {
        fmt.Printf("%d:%c ", i, r) // byte index and rune
    }
    fmt.Println()
}

Commands:

$ go run .

Output:

$ go run .
chai Chai
9 3
224
0:च 3:ा 6:य 
  • []byte(s) makes a copy you can change; s itself is untouched.
  • A string holds bytes, usually UTF-8: an encoding that stores each character in 1 to 4 bytes (English letters 1, Devanagari 3, most emoji 4).
  • len(t) counts bytes (9); utf8.RuneCountInString(t) counts runes (3). A rune is an int32 holding one Unicode code point.
  • t[0] is a single byte, 224 (the first byte of च).
  • range over a string decodes runes and gives each one's byte index: 0, 3, 6.
  • ा (the vowel sign "aa") is its own rune: a rune is not always one visible letter. Text that users see as one character can be several runes.

Rule: len and indexing are bytes; range gives runes. Change text through []byte or []rune, or build it with strings.Builder.

Q8 · Interface satisfaction and compile-time checks

Go interfaces are satisfied implicitly: there is no implements keyword; a type satisfies an interface if it has all the methods (episode 21). That's flexible, but a typo goes unnoticed until the type is used as that interface.

main.go:

package main

import "fmt"

type Payer interface {
    Pay(paise int) error
}

type UPI struct{ id string }

func (u *UPI) Paye(paise int) error { // a typo nobody noticed
    fmt.Println(u.id, "paid", paise)
    return nil
}

// compile-time check: does *UPI satisfy Payer?
var _ Payer = (*UPI)(nil)

func main() {
    fmt.Println("shop open")
}

Commands:

$ go run .

Output:

$ go run .
# shop
./main.go:17:15: cannot use (*UPI)(nil) (value of type *UPI) as Payer value in variable declaration: *UPI does not implement Payer (missing method Pay)

var _ Payer = (*UPI)(nil) assigns a nil *UPI to the blank identifier _ with type Payer. It creates nothing at run time; it only makes the compiler check that *UPI satisfies Payer. With the name fixed:

main.go:

package main

import "fmt"

type Payer interface {
    Pay(paise int) error
}

type UPI struct{ id string }

func (u *UPI) Pay(paise int) error { // typo fixed
    fmt.Println(u.id, "paid", paise)
    return nil
}

// compile-time check: does *UPI satisfy Payer?
var _ Payer = (*UPI)(nil)

func main() {
    fmt.Println("shop open")
}

Commands:

$ go run .

Output:

$ go run .
shop open

Rule: add a one-line compile-time check next to types that must satisfy an important interface (io.Writer, http.Handler, your own repository interfaces).

Q9 · Error wrapping

A sentinel error is one fixed error value that callers compare against, like io.EOF (episode 24). Wrapping means creating a new error that adds context and keeps a link to the original (episode 25).

main.go:

package main

import (
    "errors"
    "fmt"
)

var ErrOutOfStock = errors.New("out of stock") // a sentinel error

type PayError struct{ Code int }

func (e *PayError) Error() string { return fmt.Sprint("payment declined: ", e.Code) }

func reserve() error { return ErrOutOfStock }
func pay() error     { return &PayError{Code: 51} }

func main() {
    e1 := fmt.Errorf("order 7: %v", reserve()) // %v: text only
    e2 := fmt.Errorf("order 7: %w", reserve()) // %w: wraps
    fmt.Println(e1, "|", errors.Is(e1, ErrOutOfStock))
    fmt.Println(e2, "|", errors.Is(e2, ErrOutOfStock))
    fmt.Println(e2 == ErrOutOfStock, errors.Unwrap(e2) == ErrOutOfStock)

    e3 := fmt.Errorf("checkout: %w", pay())
    var pe *PayError
    if errors.As(e3, &pe) { // find a *PayError in the chain
        fmt.Println("code:", pe.Code)
    }
}

Commands:

$ go run .

Output:

$ go run .
order 7: out of stock | false
order 7: out of stock | true
false true
code: 51
Expression Result Why
fmt.Errorf("...: %v", err) + errors.Is false %v copies only the text; the link is lost
fmt.Errorf("...: %w", err) + errors.Is true %w wraps: Unwrap() returns the inner error
e2 == ErrOutOfStock false e2 is a different value (the wrapper)
errors.Unwrap(e2) == ErrOutOfStock true one step down the chain
errors.As(e3, &pe) finds code 51 walks the chain looking for a type, fills pe

errors.Is walks the whole chain, however many times it was wrapped (see checkout: order 7: out of stock true in the Q5 recover program above). fmt.Errorf can also take several %w verbs (Go 1.20+), making a tree that Is and As search.

Rule: wrap with %w; check with errors.Is for values and errors.As for types; never compare wrapped errors with == or by searching the message text.

Q10 · Generics

A type parameter is a placeholder for a type the caller chooses: T in func Index[T any](...). Its constraint (an interface) says which types are allowed (episodes 30 and 31).

main.go:

package main

import "fmt"

// Index returns where x is in s, or -1.
func Index[T any](s []T, x T) int {
    for i, v := range s {
        if v == x {
            return i
        }
    }
    return -1
}

func main() {
    fmt.Println(Index([]string{"chai", "vada"}, "vada"))
}

Commands:

$ go run .

Output:

$ go run .
# shop
./main.go:8:12: invalid operation: v == x (incomparable types in type set)

any allows every type, including slices, maps and functions, which can't be compared with ==, so the compiler refuses.

main.go:

package main

import (
    "cmp"
    "fmt"
)

// comparable: types that support == and !=
func Index[T comparable](s []T, x T) int {
    for i, v := range s {
        if v == x {
            return i
        }
    }
    return -1
}

// cmp.Ordered: types that support < <= > >=
func Max[T cmp.Ordered](a, b T) T {
    if a > b {
        return a
    }
    return b
}

func main() {
    fmt.Println(Index([]string{"chai", "vada"}, "vada"))
    fmt.Println(Max(3, 2.5))      // T is float64: 3 becomes 3.0
    fmt.Println(Max[int](40, 45)) // T written out
    fmt.Printf("%T\n", Max(3, 2.5))
}

Commands:

$ go run .

Output:

$ go run .
1
3
45
float64
  • comparable allows only types that support == and !=.
  • cmp.Ordered (package cmp, Go 1.21) allows types that support <, <=, >, >=: integers, floats and strings.
  • Type inference: in Max(3, 2.5) the compiler works out T from the arguments. The untyped constants 3 and 2.5 must share one type, so T is float64 and 3 becomes 3.0 (printed as 3). Max[int](40, 45) writes T explicitly.

main.go:

package main

import "fmt"

type Box[T any] struct{ v T }

func (b Box[T]) Map[U any](f func(T) U) Box[U] { // its own type parameter?
    return Box[U]{f(b.v)}
}

func main() {
    fmt.Println(Box[int]{2})
}

Commands:

$ go run .

Output:

$ go run .
# shop
./main.go:7:20: syntax error: method must have no type parameters

Methods can use their type's parameters (T of Box[T]) but cannot declare new ones. Write a generic function instead: func Map[T, U any](b Box[T], f func(T) U) Box[U].

Rule: pick the tightest constraint the body needs (any → comparable → cmp.Ordered → your own); no type parameters on methods.

The cheat sheet

# Question Rule
1 slice aliasing append may share the array: a[:n:n] or slices.Clone
2 nil map vs nil slice nil slice ready to use; nil map read-only, make it
3 nil interface return a literal nil error, never a typed nil pointer
4 method sets *T has pointer methods, T doesn't: store &c
5 defer LIFO; arguments evaluated now; can change named results
6 loop closures Go 1.22+: a new loop variable per iteration
7 strings immutable bytes; len = bytes; range = runes
8 satisfaction var _ I = (*T)(nil) checks at compile time
9 wrapping %w; errors.Is for values, errors.As for types
10 generics any can't ==: comparable, cmp.Ordered; no method type params

Mini project: an interview drill

  1. Create drill/ with one folder per question, each with a main.go that prints the answer. Write your prediction as a comment before running it.
  2. Turn the answers into a table-driven test (episode 40) that checks the real output.
  3. Make three new variants: inserting with append, defer + recover, %w twice.
  4. Practise explaining each answer out loud in 30 seconds.
Solution 2: the drill as a table-driven test

drill_test.go:

package drill

import (
    "errors"
    "fmt"
    "testing"
)

func alias() string {
    a := []int{1, 2, 3, 4}
    b := a[:2]
    b = append(b, 99)
    return fmt.Sprint(a, b)
}

func deferOrder() (s string) {
    for i := 0; i < 3; i++ {
        defer func() { s += fmt.Sprint(i) }()
    }
    return ""
}

var ErrOutOfStock = errors.New("out of stock")

func wrapped() bool {
    return errors.Is(fmt.Errorf("order 7: %w", ErrOutOfStock), ErrOutOfStock)
}

func TestDrill(t *testing.T) {
    tests := []struct {
        name, got, want string
    }{
        {"slice aliasing", alias(), "[1 2 99 4] [1 2 99]"},
        {"defer order", deferOrder(), "210"},
        {"errors.Is with %w", fmt.Sprint(wrapped()), "true"},
        {"runes", fmt.Sprint(len("चाय"), len([]rune("चाय"))), "9 3"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if tt.got != tt.want {
                t.Errorf("got %q, want %q", tt.got, tt.want)
            }
        })
    }
}

Commands:

$ go test -v .

Output:

$ go test -v .
=== RUN   TestDrill
=== RUN   TestDrill/slice_aliasing
=== RUN   TestDrill/defer_order
=== RUN   TestDrill/errors.Is_with_%w
=== RUN   TestDrill/runes
--- PASS: TestDrill (0.00s)
    --- PASS: TestDrill/slice_aliasing (0.00s)
    --- PASS: TestDrill/defer_order (0.00s)
    --- PASS: TestDrill/errors.Is_with_%w (0.00s)
    --- PASS: TestDrill/runes (0.00s)
PASS
ok      shop    0.003s

Note the defer test: the closures run in LIFO order and each captures its own i (Go 1.22+), so they append 2, 1, 0.

Solution 3: variants

Inserting with append overwrites the original array; slices.Insert does it correctly:

main.go:

package main

import (
    "fmt"
    "slices"
)

func main() {
    a := []int{1, 2, 4, 5}
    head := a[:2]
    b := append(head, 3)  // "insert 3 after 2"... into a's array
    fmt.Println(a, b)

    c := []int{1, 2, 4, 5}
    d := slices.Insert(c, 2, 3) // a correct insert
    fmt.Println(c, d)
}

Commands:

$ go run .

Output:

$ go run .
[1 2 3 5] [1 2 3]
[1 2 4 5] [1 2 3 4 5]

defer + recover and %w twice: see the safeDivide program in Q5.

Common mistakes (and the real messages)

Mistake Real message / symptom Why Fix
b := a[:2]; b = append(b, x) a changes: [1 2 99 4] shared backing array with spare capacity a[:2:2], slices.Clone
m[k] = v on a nil map panic: assignment to entry in nil map the map was never made make(map[K]V)
return err where err is a nil *T err != nil is true the interface's type word is set return nil
var i Incer = c with a pointer method Counter does not implement Incer (method IncPointer has pointer receiver) T's method set lacks pointer methods var i Incer = &c
expecting defer f(x) to see later changes to x prints the old value arguments are evaluated at the defer statement defer a closure if you need the latest value
goroutines/closures in loops in pre-1.22 modules 3 3 3 one shared loop variable i := i, or go 1.22 in go.mod
s[0] = 'C' cannot assign to s[0] (neither addressable nor a map index expression) strings are immutable []byte(s), change, string(b)
len(s) as "number of characters" 9 for "चाय" len counts bytes utf8.RuneCountInString
a misspelled method *UPI does not implement Payer (missing method Pay) implicit satisfaction fix the name, keep var _ I = (*T)(nil)
fmt.Errorf("%v", err) then errors.Is false %v keeps only text %w
v == x with [T any] invalid operation: v == x (incomparable types in type set) any includes uncomparable types [T comparable]
func (b Box[T]) Map[U any](...) syntax error: method must have no type parameters not allowed in Go a generic function

Practice

  1. s := []int{1, 2, 3}; t := s[1:]; t[0] = 20; fmt.Println(s) — what prints?
  2. Is var m map[string][]int; m["a"] = append(m["a"], 1) safe?
  3. func f() (err error) { defer func() { err = nil }(); return errors.New("x") } — what does f() return?
  4. Why does for i, r := range "héllo" print the index 3 after 1 for l?
  5. A type T has func (t T) A() and func (t *T) B(). Which of T and *T satisfies interface{ A(); B() }?
  6. Write a generic Keys[K comparable, V any](m map[K]V) []K.
Solutions

1. [1 20 3]: t shares s's array, no append involved.

2. No: reading m["a"] is fine (nil slice), and append works, but the assignment m["a"] = ... writes to a nil map and panics.

3. nil. return sets err to the new error, then the deferred closure overwrites the named result.

4. é is 2 bytes in UTF-8 (index 1 and 2), so the next rune, l, starts at byte 3.

5. Only *T: its method set has both A and B; T's has only A.

6.

func Keys[K comparable, V any](m map[K]V) []K {
    keys := make([]K, 0, len(m))
    for k := range m {
        keys = append(keys, k)
    }
    return keys // map order is random: sort if order matters (slices.Sort needs cmp.Ordered)
}

Go 1.23+ also has maps.Keys, which returns an iterator: slices.Collect(maps.Keys(m)).

Quick quiz

func main() {
    s := make([]int, 3, 10)
    t := append(s, 4)
    u := append(s, 5)
    fmt.Println(t[3], u[3])
}
  • A. 4 5
  • B. 5 5
  • C. 4 4
  • D. index out of range
Answer

B.

Output:

$ go run .
5 5

s has room (capacity 10), so both appends write into index 3 of the same backing array. u's append overwrites t's 4 with 5, and t and u share that slot.

Interview questions (with model answers)

  1. What is a slice and what does append do? A header (pointer, length, capacity) over a backing array. append writes in place if there is capacity, otherwise allocates a larger array, copies, and returns a header pointing at it; always use its return value.
  2. Difference between a nil slice and an empty slice? Both have length 0 and work with append and range; a nil slice == nil and encodes as JSON null, while []int{} is non-nil and encodes as [].
  3. Why does writing to a nil map panic but appending to a nil slice not? append returns a new slice it can allocate; a map assignment has nowhere to return a new map.
  4. When is an interface nil? Only when both its type and value words are empty; an interface holding a nil pointer is not nil.
  5. Value or pointer receiver? Pointer when the method changes the receiver, when the struct is large, or when it contains a lock; keep one style per type. A value of T does not satisfy an interface that needs a pointer method.
  6. When are deferred function arguments evaluated? At the defer statement. The call itself runs at function return, LIFO.
  7. What changed in Go 1.22 for loops? Each iteration has its own loop variable, which fixed closure and goroutine capture bugs; it depends on the module's go version.
  8. How do you iterate over characters in a string? for i, r := range s decodes UTF-8 runes; indexing gives bytes.
  9. %w vs %v in fmt.Errorf? %w wraps (keeps the error for errors.Is/As/Unwrap); %v only formats the text.
  10. any vs comparable? any allows every type but no operators beyond assignment; comparable allows ==/!=; cmp.Ordered allows ordering operators.

Glossary

Term Meaning Example
Slice header a slice's three fields: pointer, length, capacity b := a[:2]
Backing array the real array a slice points into [1 2 3 4]
Length how many elements a slice shows len(b) == 2
Capacity elements available in the array from the slice's start cap(b) == 4
Aliasing two slices sharing one backing array a and b in Q1
append adds elements, allocating a new array when full b = append(b, 99)
Full slice expression s[low:high:max], sets capacity to max-low a[:2:2]
slices.Clone an independent copy of a slice slices.Clone(a[:2])
nil the zero value meaning "nothing made yet" for slices, maps, pointers, channels, funcs, interfaces var m map[string]int
nil map a map variable with no map behind it: readable, not writable m["chai"] = 10 panics
Interface value two words: a type and a value var err error
Typed nil a nil pointer stored in an interface: the type word is set error((*OrderError)(nil))
Receiver the value a method is called on c in func (c Counter)
Value receiver the method gets a copy IncValue
Pointer receiver the method gets the address of the original IncPointer
Method set the methods callable through an interface for a type *Counter has both
defer schedule a call for when the function returns defer mu.Unlock()
LIFO last in, first out defers print 2, 1, 0
Named result a result with a name, settable by deferred code func double() (n int)
recover stops a panic inside a deferred function if r := recover(); r != nil
Closure a function value that captures surrounding variables func() { fmt.Print(i) }
Loop variable (Go 1.22) a new variable per iteration 0 1 2
Language version the Go version rules a file is compiled with go 1.24 in go.mod
Immutable cannot be changed after creation strings
Byte 8 bits; byte is uint8 t[0] == 224
UTF-8 text encoding using 1 to 4 bytes per character "चाय" is 9 bytes
Rune an int32 holding one Unicode code point 'च'
Code point the number Unicode gives a character U+091A for च
Implicit satisfaction a type satisfies an interface just by having its methods no implements
Compile-time check var _ I = (*T)(nil): the compiler proves *T satisfies I Q8
Blank identifier _ a name that discards a value var _ Payer = ...
Sentinel error a fixed error value callers compare against ErrOutOfStock, io.EOF
Wrapping a new error that keeps a link to the original fmt.Errorf("...: %w", err)
errors.Is is this error, or any it wraps, equal to a value? errors.Is(e2, ErrOutOfStock)
errors.As find an error of a type in the chain errors.As(e3, &pe)
errors.Unwrap one step down the chain returns ErrOutOfStock
Type parameter a placeholder for a type chosen by the caller T in Index[T]
Constraint an interface listing allowed types for a type parameter comparable
comparable types that support == and != strings, ints, structs of them
cmp.Ordered types that support <, >: integers, floats, strings Max[T cmp.Ordered]
Type inference the compiler works out type arguments from the call Max(3, 2.5) → float64
Untyped constant a constant like 3 whose type is decided by its use becomes 3.0 here

Summary

  • Slices share backing arrays; append may or may not copy. Cap the capacity with a[:n:n].
  • A nil slice is ready to use; a nil map panics on write.
  • An interface is nil only when both words are empty: return a literal nil.
  • Method sets: *T has pointer methods, T does not; value receivers change copies.
  • defer: LIFO, arguments evaluated immediately, named results can be changed.
  • Go 1.22+ gives each loop iteration its own variable.
  • Strings are immutable UTF-8 bytes; range gives runes with byte indexes.
  • Use var _ I = (*T)(nil) to catch interface typos at compile time.
  • Wrap errors with %w, check with errors.Is / errors.As.
  • Generics: the constraint decides the allowed operators; methods can't have their own type parameters.

Next episode: Interview prep: concurrency.