Goroutines, channels, interfaces, and the Go interview essentials.
Basics
What are Go's zero values?
Variables declared without initialization get a zero value: 0 for numbers, false for bool, "" for string, nil for pointers/slices/maps/channels/interfaces/functions.
var i int // 0
var b bool // false
var s string // ""
var p *int // nil
What is short variable declaration?
:= declares and initializes a new variable, inferring type. Only allowed inside functions; cannot redeclare in same scope unless at least one new var on left.
x := 42
name := "go"
x, y := 1, 2 // y new, OK
How do constants and iota work?
const declares compile-time constants. iota is an untyped counter reset to 0 in each const block, incrementing per line. Use for enums/bit flags.
const (
A = iota // 0
B // 1
C // 2
)
const (
Read = 1 << iota // 1
Write // 2
)
What are Go's basic types?
bool; string; int/int8/.../uint; byte (uint8); rune (int32); float32/64; complex64/128. int/uint are platform-sized. No implicit conversions.
var r rune = 'A' // 65
var b byte = 255
var f float64 = 3.14
Type definition vs type alias?
type Foo int creates a new distinct type with its own method set. type Foo = int is an alias (same type as int). Methods can be added only to named types you define, not to predeclared types or their aliases.
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", c) }
type Alias = int // same type as int
What is the difference between rune and byte?
byte is uint8 (raw bytes). rune is int32 (a Unicode code point). Indexing a string yields bytes; range yields runes.
s := "héllo"
fmt.Println(len(s)) // bytes (7)
for i, r := range s { fmt.Printf("%d %c\n", i, r) }
Why are strings immutable?
Strings are read-only byte slices. Indexing gives a byte; concatenation creates a new string. Use []byte or strings.Builder for mutation.
s := "ab"
// s[0] = 'x' // compile error
b := []byte(s); b[0] = 'x'; s = string(b)
What are untyped constants?
Untyped constants have no fixed type until used, allowing high precision and implicit conversion to compatible types. Typed constants behave like variables.
const x = 1 // untyped
var i int = x
var f float64 = x
const y int = 1 // typed
How do type conversions work?
Go requires explicit conversion: T(value). No implicit numeric conversions. Conversions may lose precision or truncate.
i := 42
f := float64(i)
n := int(3.99) // 3
// i = f // compile error
What is the blank identifier?
_ discards a value. Used to ignore return values, imports for side effects, or unused variables in loops.
_, err := os.ReadFile("f")
_ = err
import _ "net/http/pprof"
How does multiple assignment work?
Multiple values can be assigned in one statement; RHS expressions are evaluated before assignment, enabling swaps without temp.
a, b := 1, 2
a, b = b, a // swap
What is variable shadowing?
:= in an inner scope can shadow an outer variable with the same name, creating a new variable. Common source of bugs; vet warns in some cases.
x := 1
if true {
x := 2 // new x
fmt.Println(x) // 2
}
fmt.Println(x) // 1
Functions
How do multiple return values work?
Functions can return multiple values, conventionally (result, error). Callers must accept or explicitly discard with _.
func div(a, b int) (int, error) {
if b == 0 { return 0, errors.New("div by zero") }
return a / b, nil
}
What are named return values?
Naming return values declares variables initialized to zero. Naked return returns their current values. Use sparingly for clarity.
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // naked return
}
How do variadic functions work?
A final parameter ...T accepts zero or more args, collected into a slice. Pass an existing slice with s... .
func sum(nums ...int) int {
t := 0; for _, n := range nums { t += n }; return t
}
sum(1,2,3)
vals := []int{1,2}; sum(vals...)
What are closures?
Functions are first-class; a closure captures variables from its enclosing scope by reference. Useful for callbacks and factories.
func counter() func() int {
n := 0
return func() int { n++; return n }
}
How does defer work?
defer schedules a call to run when the surrounding function returns. Arguments are evaluated immediately; deferred calls run LIFO. Used for cleanup.
f, _ := os.Open("x")
defer f.Close()
// multiple defers run in reverse order
What are first-class functions?
Functions can be assigned to variables, passed as arguments, and returned. Function types describe signatures.
type Op func(int, int) int
func apply(op Op, a, b int) int { return op(a,b) }
What is a function type?
A named or anonymous signature: func(int, int) int. Used for callbacks, strategy patterns, and higher-order functions.
var f func(string) bool
f = func(s string) bool { return len(s) > 0 }
What are init functions?
init() runs automatically when a package is initialized, before main. Multiple init allowed; order is file order. Avoid side effects where possible.
func init() {
if err := loadConfig(); err != nil { log.Fatal(err) }
}
What are higher-order functions in Go?
Functions that take or return functions, enabling middleware, decorators, and functional pipelines.
func withLogging(fn http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL); fn.ServeHTTP(w, r)
})
}
How do methods differ from functions?
A method has a receiver: func (r Receiver) Method(). It is a function with the receiver as first argument; method values/expressions exist.
type T int
func (t T) Double() T { return t * 2 }
v := T(3); v.Double() // method value
What is a method value vs method expression?
Method value: v.Method binds receiver. Method expression: T.Method takes receiver as first arg. Both are first-class functions.
mv := v.Double // func() T
me := T.Double // func(T) T
How does recursion and stack work?
Go grows goroutine stacks dynamically, so deep recursion is possible but not free. Tail calls are not guaranteed optimized.
func fact(n int) int { if n <= 1 { return 1 }; return n * fact(n-1) }
Structs & Interfaces
How do you define a struct?
A composite type with named fields. Use struct tags for serialization/metadata. Fields can be anonymous (embedded).
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Age int `json:"age,omitempty"`
}
When should a method use a pointer receiver?
Use a pointer receiver to mutate the receiver or avoid copying large structs. Value receiver works on a copy. Keep receiver types consistent across a type's methods (method-set rules). Note: a field and a method cannot share a name—rename one (e.g. GetName()).
type User struct { Name string; Age int }
func (u *User) Birthday() { u.Age++ }
func (u User) GetName() string { return u.Name }
How do implicit interfaces work?
A type implements an interface by having its methods—no implements keyword. This enables decoupling and small interfaces (io.Reader).
type Reader interface { Read(p []byte) (int, error) }
type MyReader struct{}
func (m MyReader) Read(p []byte) (int, error) { return 0, nil }
How do interfaces compose?
Embed interfaces to build larger ones. Prefer small, focused interfaces (Go proverb: accept interfaces, return structs).
type ReadWriter interface {
Reader
Writer
}
How do type assertions and type switches work?
v.(Type) asserts a concrete type; use the comma-ok form to avoid panics. Type switch (switch v := v.(type)) branches on dynamic type.
if s, ok := v.(string); ok { fmt.Println(s) }
switch v := v.(type) {
case int: fmt.Println(v+1)
case string: fmt.Println(v)
default: fmt.Println("other")
}
What is embedding (composition)?
Embed a type in a struct to promote its methods and fields. Go's mechanism for reuse instead of inheritance.
type Base struct { ID string }
type User struct {
Base
Name string
}
u := User{Base: Base{ID:"1"}, Name:"Ann"}
u.ID // promoted
What is the nil interface gotcha?
An interface holding a nil concrete pointer is not nil itself. Checking `i == nil` returns false, causing unexpected method calls on nil.
var p *User = nil
var i interface{} = p
fmt.Println(i == nil) // false
// calling method on nil pointer may panic
What is the empty interface / any?
interface{} (any in Go 1.18+) holds any type. Use for generic containers, but prefer generics or concrete types for type safety.
func print(v any) { fmt.Println(v) }
What are method sets?
The set of methods callable on a value. Value receivers are in both T and *T; pointer receivers are only in *T. Addressability lets you call x.M() on a variable of type T, but it never makes T satisfy an interface requiring M().
type T struct{}
func (t *T) M() {}
type I interface { M() }
var x T
x.M() // OK: auto-addressing for the call
// var i I = x // compile error: T does not implement I
var p *T = &x
var i I = p // OK: *T implements I
How do struct tags work?
Backtick strings provide metadata read via reflect. Standard tags: json, xml, db, validate. Tags are conventional space-separated key:"value" pairs.
type User struct {
Name string `json:"name" validate:"required"`
}
What types are comparable?
Types are comparable if their values can be ==/!=. Structs are comparable if all fields are comparable; slices, maps, and functions are not.
type Point struct{ X, Y int } // comparable
p1 == p2 // OK
// slices/maps are not comparable
How do you define methods on named types?
Methods can be defined on any defined (non-alias) type declared in the same package, enabling domain-specific behavior. You cannot declare methods on a type alias (`type A = int`) or on predeclared types.
type Duration int64
func (d Duration) Seconds() float64 { return float64(d) / 1e9 }
Concurrency
What are goroutines?
Lightweight threads managed by the Go runtime (M:N scheduling). Start with `go fn()`. Thousands can run; main must wait for them.
go func() { fmt.Println("hi") }()
// use WaitGroup or channel to wait
What are channels?
Typed pipes for goroutine communication and synchronization. Unbuffered (synchronous) or buffered. Close to signal completion; range over channel.
ch := make(chan int, 10) // buffered
ch <- 42 // send
v := <-ch // receive
close(ch)
for v := range ch { _ = v }
Buffered vs unbuffered channels?
Unbuffered channels synchronize sender and receiver (rendezvous). Buffered channels allow sends up to capacity without a ready receiver; useful for decoupling and rate limiting.
unbuf := make(chan int) // sync
buf := make(chan int, 100) // async up to 100
How does select work?
select waits on multiple channel operations; picks a ready case at random. Use a default case for non-blocking checks OR a timeout case, not both (default would win immediately).
// timeout case (blocking until timeout)
select {
case v := <-ch1: fmt.Println(v)
case ch2 <- 42: fmt.Println("sent")
case <-time.After(time.Second): fmt.Println("timeout")
}
// non-blocking (no timeout)
select {
case v := <-ch1: fmt.Println(v)
default: fmt.Println("none ready")
}
What sync primitives exist?
sync.Mutex, sync.RWMutex, sync.WaitGroup, sync.Once, sync.Cond, sync.Map. sync/atomic for lock-free counters. Prefer channels for communication.
var mu sync.Mutex
mu.Lock(); counter++; mu.Unlock()
How does context work?
context.Context carries deadlines, cancellation, and request-scoped values. Pass as first parameter. Check ctx.Done() and ctx.Err(); never store in structs long-term.
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()
select { case <-ctx.Done(): return ctx.Err() }
What is sync.WaitGroup?
Counts goroutines; Add before launching, Done when finished, Wait blocks until zero. Must Add before go. Reuse only after Wait returns.
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func() { defer wg.Done(); work() }()
}
wg.Wait()
What is sync.Once?
Ensures a function runs exactly once even across goroutines. Used for lazy initialization and singleton setup.
var once sync.Once
once.Do(func() { initDB() })
How do you use sync/atomic?
Atomic operations on integers/pointers without locks. Use for counters/flags. Prefer for simple cases; mutex for complex invariants.
var counter int64
atomic.AddInt64(&counter, 1)
v := atomic.LoadInt64(&counter)
What is the race detector?
go test -race / go run -race instruments memory accesses to detect data races. Essential in CI; has overhead. A race is undefined behavior.
go test -race ./...
go build -race ./...
What causes goroutine leaks?
Goroutines blocked forever on channels with no sender/receiver, missing context cancellation, or unclosed channels. Use context and select with Done().
go func() {
select { case <-ctx.Done(): return; case <-ch: }
}()
What are channel directions?
chan<- T (send-only) and <-chan T (receive-only) restrict usage, improving API safety. The compiler rejects sends on receive-only channels and receives on send-only channels at compile time.
func producer(out chan<- int) { out <- 1 }
func consumer(in <-chan int) { <-in }
Error Handling
How does Go handle errors?
Errors are values implementing the error interface (Error() string). Return error as the last value; check with if err != nil. No exceptions.
func read(path string) ([]byte, error) {
data, err := os.ReadFile(path)
if err != nil { return nil, err }
return data, nil
}
How do you wrap errors?
Use fmt.Errorf with %w to wrap; preserves the chain. errors.Is checks identity through the chain; errors.As extracts a typed error.
return fmt.Errorf("read %s: %w", path, err)
if errors.Is(err, os.ErrNotExist) { ... }
var pe *os.PathError; errors.As(err, &pe)
What are sentinel errors?
Package-level error variables compared by identity (errors.Is). Use for expected, well-known failure conditions.
var ErrNotFound = errors.New("not found")
if errors.Is(err, ErrNotFound) { ... }
How do you define custom error types?
Any type implementing Error() string. Add fields for structured info; use errors.As to extract.
type ValidationError struct { Field string; Msg string }
func (e *ValidationError) Error() string { return e.Field + ": " + e.Msg }
How do panic and recover work?
panic stops normal execution; recover() in a deferred function catches it and resumes. Use for truly unrecoverable or programmer errors, not control flow.
func safe() {
defer func() { if r := recover(); r != nil { log.Println("recovered", r) } }()
panic("boom")
}
Why defer recover?
recover only works inside a deferred function. Defer runs on panic, allowing cleanup and conversion of panic to error if desired.
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
What is errors.Join (Go 1.20)?
Combines multiple errors into one; errors.Is/As check each. Useful when reporting several independent failures.
err := errors.Join(err1, err2)
if errors.Is(err, err1) { ... }
What is errors.Unwrap?
Returns the wrapped error (the one behind %w). Used to walk the chain manually; errors.Is/As do this automatically.
for e := err; e != nil; e = errors.Unwrap(e) { fmt.Println(e) }
How should errors be logged?
Log once at the boundary, not at every layer. Wrap with context as it propagates; avoid duplicate logging.
func getUser(id int) (*User, error) {
u, err := db.Find(id)
if err != nil { return nil, fmt.Errorf("getUser %d: %w", id, err) }
return u, nil
}
// in handler: log.Printf("request failed: %v", err)
What is the nil error gotcha?
Returning an interface holding a nil concrete error makes the interface non-nil. Return untyped nil to represent no error.
func f() error {
var e *MyErr = nil
return e // non-nil interface! bad
}
// return nil instead
What is fmt.Errorf vs errors.New?
errors.New for simple static errors. fmt.Errorf for formatted messages and wrapping with %w (Go 1.13+).
err := errors.New("not found")
err2 := fmt.Errorf("user %d: %w", id, err)
How do you handle errors in goroutines?
Goroutines cannot return errors to callers directly. Use channels, errgroup, or collect into a shared slice with mutex.
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return doWork(ctx) })
if err := g.Wait(); err != nil { ... }
Slices & Maps
What is a slice's internal structure?
A slice is a header: pointer to backing array, length, capacity. Slicing shares the backing array; aliasing bugs are common.
type sliceHeader struct { data *byte; len, cap int }
How does append work?
append adds elements; if capacity is insufficient it allocates a new backing array and copies. Always reassign: s = append(s, x).
s := []int{1,2}
s = append(s, 3,4)
// s may point to new array
What is slice aliasing?
Slicing shares the backing array, so writes through one slice affect others. Use copy or full slice expression s[lo:hi:cap] to limit.
a := []int{1,2,3,4}
b := a[1:3] // shares backing
b[0] = 99 // a becomes [1,99,3,4]
nil slice vs empty slice?
A nil slice has a nil data pointer and zero len/cap; an empty slice has a non-nil data pointer (possibly to zerobase) and len 0. Both len 0; json marshals nil to null and empty to [].
var s []int // nil
s2 := []int{} // empty non-nil
s3 := make([]int,0) // empty non-nil
How do you copy slices?
copy(dst, src) copies min(len(dst), len(src)) elements. Allocate dst with make([]T, len(src)).
src := []int{1,2,3}
dst := make([]int, len(src))
copy(dst, src)
How do maps work?
Hash tables. make(map[K]V) or literal. Zero value nil map is readable but writes panic. Keys must be comparable. Reading a nil map returns zero values; writing panics—always initialize before writing.
m := map[string]int{"a":1}
m["b"] = 2
v, ok := m["c"] // 0, false
How do you delete from a map?
delete(m, key) removes; no-op if absent. Iteration order is randomized; never rely on it.
delete(m, "a")
for k, v := range m { fmt.Println(k, v) } // random order
How do you check map key existence?
Comma-ok: v, ok := m[k]. ok is false if absent. Distinguish zero value from missing.
if v, ok := m["x"]; ok { fmt.Println(v) }
What is map concurrency safety?
Maps are not safe for concurrent use. Use sync.Mutex or sync.Map. Concurrent reads/writes cause fatal error (not just race).
var mu sync.Mutex
mu.Lock(); m[k]=v; mu.Unlock()
How does slice capacity grow?
Since Go 1.18, append doubles capacity up to 256, then tapers smoothly from 2x toward 1.25x; the result is rounded up to allocator size classes. Use make with a capacity hint to reduce allocations.
s := make([]int, 0, 1000) // preallocate
Array vs slice?
Arrays are fixed-size values [N]T; size is part of type. Slices are dynamic views. Arrays are comparable; slices are not.
var a [3]int = [3]int{1,2,3}
s := a[:] // slice over array
Pointers
How do address and dereference work?
& takes the address of an addressable value; * dereferences a pointer. Go has no pointer arithmetic (except unsafe).
x := 42
p := &x
fmt.Println(*p) // 42
*p = 7; fmt.Println(x) // 7
new vs make?
new(T) allocates zeroed memory and returns *T. make is only for slices, maps, channels, initializing their internals. Use make for those.
p := new(int) // *int, zero
s := make([]int, 5, 10)
m := make(map[string]int)
ch := make(chan int, 1)
What are nil pointers?
A nil pointer dereference panics. Check for nil before calling methods on pointer-typed values, especially interface nil gotcha.
var p *User
if p != nil { p.Name() }
What is escape analysis?
Compiler decides whether a variable lives on stack or heap. Taking address or returning pointer may escape to heap; affects performance.
go build -gcflags='-m' ./... // shows escapes
Why no pointer arithmetic?
Go disallows pointer arithmetic for safety. Use unsafe.Pointer or slices for byte-level manipulation when truly needed.
import "unsafe"
p := unsafe.Pointer(&x)
What values are addressable?
Variables, struct fields of addressable structs, slice/array elements, pointer dereferences. Composite literals are not addressable (`&T{}` is special syntax). Map values and function returns are not addressable.
m := map[string]int{"a":1}
// &m["a"] // compile error (not addressable)
u := &User{Name: "Ann"} // &T{} special case
_ = u
What is autoderef?
Go automatically dereferences pointers for method calls and field access: p.Field works even if p is *Struct.
p := &User{Name:"Ann"}
fmt.Println(p.Name) // auto-deref
Can you take address of interface?
Yes—you can take the address of an interface value; it yields *interface{...} and compiles. But a pointer to an interface is almost never what you want; prefer a pointer to the concrete type.
var iface any = 42
p := &iface // *any, compiles
_ = p
What is unsafe.Pointer?
unsafe.Pointer is a generic pointer that can convert to/from any pointer type and uintptr. Bypasses type safety; use sparingly.
up := unsafe.Pointer(&x)
ptr := (*int)(up)
Value vs pointer semantics in structs?
Structs are value types: assignment copies. Large structs should be passed by pointer to avoid copying.
a := BigStruct{}
b := a // copy
f(&a) // pass pointer
How does new behave with zero values?
new(T) returns *T pointing to a zero-valued T. For slices/maps/channels, use make to initialize internals; new gives nil.
sp := new([]int) // *[]int pointing to nil slice
// *sp = append(*sp, 1)
Packages & Modules
What is go.mod?
Module definition file: module path, Go version, dependencies. Created by `go mod init`. Run `go mod tidy` to sync.
module example.com/app
go 1.22
require (
github.com/foo/bar v1.2.3
)
How does visibility work?
Capitalized identifiers are exported (public); lowercase are package-private. Applies to funcs, types, fields, vars.
type User struct { Name string; age int } // age unexported
What are internal packages?
Packages under internal/ are only importable by code within the parent tree, enforcing encapsulation.
// module/internal/foo can be imported by module/... only
How does semantic versioning affect imports?
v2+ modules must include /v2 in module path and import path. Major version is part of the import.
module example.com/lib/v2
import "example.com/lib/v2/foo"
How do you add dependencies?
`go get pkg@version` adds/updates; `go mod tidy` removes unused and adds missing. Vendor with `go mod vendor`.
go get github.com/gin-gonic/gin@latest
go mod tidy
What is the replace directive?
replace redirects a module to a local path or fork, useful for development and monorepos.
replace example.com/lib => ../lib
What are workspaces (go.work)?
go.work coordinates multiple modules in a monorepo without replace directives. Use `go work init` and `go work use`.
go work init ./modA ./modB
What are build tags?
Build constraints select files for compilation: //go:build tag. Used for OS/arch-specific code and feature flags.
//go:build linux
package foo
What is package main?
package main defines an executable; must have func main(). Other packages are libraries.
package main
func main() { fmt.Println("hi") }
How is documentation generated?
godoc comments on exported declarations become documentation. First sentence is the summary. Use `go doc` and pkg.go.dev.
// User represents an authenticated user.
type User struct{}
How do imports group?
Convention: stdlib, then third-party, then local, separated by blank lines. goimports formats automatically.
import (
"fmt"
"github.com/foo/bar"
"example.com/app/internal/x"
)
Testing
How are tests structured?
Files *_test.go in same package. Test functions: func TestXxx(t *testing.T). Run with `go test ./...`.
// foo_test.go
func TestAdd(t *testing.T) {
if add(1,2) != 3 { t.Fatal("bad") }
}
What are table-driven tests?
Define a slice of test cases with inputs/expected, loop with t.Run subtests. The idiomatic Go testing pattern.
cases := []struct{ in, want int }{{1,2},{2,4}}
for _, c := range cases {
t.Run(fmt.Sprint(c.in), func(t *testing.T) {
if got := double(c.in); got != c.want { t.Errorf("got %d want %d", got, c.want) }
})
}
How do subtests work?
t.Run(name, fn) creates a named subtest, enabling filtering with -run and parallel execution with t.Parallel().
t.Run("case1", func(t *testing.T) { ... })
// go test -run TestFoo/case1
How do benchmarks work?
Functions BenchmarkXxx(b *testing.B) run code b.N times (Go 1.24+ prefers `for b.Loop() { ... }`). Use b.ResetTimer and report allocations with -benchmem.
func BenchmarkFoo(b *testing.B) {
for i := 0; i < b.N; i++ { Foo() }
// Go 1.24+: for b.Loop() { Foo() }
}
// go test -bench=. -benchmem
How do you measure coverage?
`go test -cover` shows percentage; `-coverprofile` generates data; `go tool cover -html` visualizes.
go test -coverprofile=cover.out ./...
go tool cover -html=cover.out
What is t.Helper?
Marking a function t.Helper() makes failures report the caller's line number, improving test diagnostics.
func assertEqual(t *testing.T, got, want int) {
t.Helper()
if got != want { t.Errorf("got %d want %d", got, want) }
}
What are example tests?
Functions ExampleXxx() with // Output: comments are compiled and run as tests, and appear in godoc.
func ExampleHello() {
fmt.Println("hello")
// Output: hello
}
What is fuzzing?
Go 1.18+ fuzz tests (FuzzXxx) generate inputs to find crashes/bugs. Run with `go test -fuzz`.
func FuzzParse(f *testing.F) {
f.Fuzz(func(t *testing.T, s string) { Parse(s) })
}
What is testify?
Popular third-party assertion library (require/assert). Not in stdlib; many teams use it for readable assertions, but stdlib is sufficient.
require.Equal(t, expected, actual)
How do you mock dependencies?
Define small interfaces; inject fakes/stubs in tests. Avoid heavy mocking frameworks; use hand-written fakes.
type repo interface { Get(id string) (User, error) }
type fakeRepo struct{}
What is t.Parallel?
Marks a test/subtest as parallel, allowing concurrent execution. Use carefully with shared state.
func TestFoo(t *testing.T) {
t.Parallel()
// ...
}
Common Gotchas
What is the init order within a package?
init functions run in lexical file-name order within a package. Avoid relying on subtle ordering; prefer explicit setup.
// files: a.go, b.go init in filename order
What is loop variable capture (pre-Go 1.22)?
In Go < 1.22, range (and 3-clause for) loop variables are reused across iterations; closures capturing them see the final value. Go 1.22 makes them per-iteration, but only for modules declaring `go 1.22` or later.
for _, v := range vals {
go func() { fmt.Println(v) }() // pre-1.22: all print last
}
// fix: v := v (old) or use Go 1.22
Why are unused imports/variables errors?
Go treats unused imports and local variables as compile errors to keep code clean. Use _ to discard or remove them.
import "fmt" // must use fmt or remove
What is slice append aliasing?
append may reuse backing array, mutating shared data. Full slice expression s[lo:hi:cap] prevents overwriting beyond length.
b := a[1:3:3] // cap limited to 2 extra
Why defer in loops is dangerous?
defer runs at function return, not block/iteration. Deferring in a loop accumulates calls, causing resource leaks. Wrap in a function.
for _, f := range files {
func() { fh, _ := os.Open(f); defer fh.Close(); ... }()
}
What leaks with time.After?
Pre-Go 1.23: time.After creates a timer that is not garbage-collected until it fires, leaking in hot loops. Since Go 1.23, unreferenced timers can be GC'd. Still prefer time.NewTimer with Stop for explicit control.
timer := time.NewTimer(time.Second)
defer timer.Stop()
select { case <-timer.C: ... }
Why must value/pointer receivers be consistent?
Mixing receiver types can make a type satisfy an interface with one receiver but not the other, and confuses method sets. Keep consistent.
// If one method uses *T, all should use *T
What is init order across packages?
Dependencies' init runs first (depth-first). Within a package, file order (lexical by filename). Avoid relying on subtle ordering.
// a imports b: b.init() runs before a.init()
Generics
What are generics (type parameters)?
Functions and types can be parameterized by type parameters in square brackets. Constraints restrict allowed types; instantiated at compile time.
func Min[T constraints.Ordered](a, b T) T {
if a < b { return a }
return b
}
What are type constraints?
A constraint is an interface describing allowed type sets. Use `any` for no constraint, `comparable` for ==/!=, or custom interfaces. Union constraints use `|`.
type Number interface { int | int64 | float64 }
func Sum[T Number](s []T) T { var t T; for _, v := range s { t += v }; return t }
What is `comparable` and `~T`?
`comparable` allows == and != (needed for map keys). `~T` in a constraint means 'types whose underlying type is T', so defined types qualify.
type MyInt int
func Contains[T comparable](s []T, v T) bool {
for _, x := range s { if x == v { return true } }
return false
}
// constraint: type Integer interface { ~int | ~int64 }
How do generics affect methods?
Methods cannot have their own type parameters (only functions and types can). Generic types' methods use the type's parameters.
type Stack[T any] struct { items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() T { v := s.items[len(s.items)-1]; s.items = s.items[:len(s.items)-1]; return v }
Modern Standard Library (1.21+)
What is log/slog?
Structured logging in stdlib (Go 1.21). slog.Logger with handlers (JSON/text), levels, attributes. Prefer over log for production.
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("user created", "id", 42)
What are the slices/maps packages?
Go 1.21+ slices and maps packages provide generic helpers: Sort, Contains, Clone, Collect, Keys, Values. Reduce boilerplate and improve correctness.
slices.Sort(nums)
fmt.Println(slices.Contains(nums, 3))
for k := range maps.Keys(m) { fmt.Println(k) }
What are range-over-func iterators (1.23)?
Functions yielding values can be ranged over directly: `for v := range seq`. Enables lazy pipelines and custom iteration without channels.
func Seq(n int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := 0; i < n; i++ { if !yield(i) { return } }
}
}
for v := range Seq(5) { fmt.Println(v) }
What are http.ServeMux patterns (1.22)?
Go 1.22 ServeMux supports method and path patterns like `GET /users/{id}`. Path values via r.PathValue. Covers many routing needs without third-party routers.
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
fmt.Fprintln(w, id)
})
Concurrency Patterns
What is sync.WaitGroup.Go (1.25)?
Go 1.25 adds WaitGroup.Go, which calls Add(1) and runs the func in a goroutine, calling Done automatically. Reduces boilerplate.
var wg sync.WaitGroup
wg.Go(func() { work() })
wg.Wait()
What is a worker pool pattern?
Fixed number of goroutines read jobs from a channel and write results. Use buffered channels and WaitGroup; cancel via context.
jobs := make(chan int, 100)
results := make(chan int, 100)
for w := 0; w < 4; w++ { go worker(jobs, results) }
What is a pipeline pattern?
Chain stages connected by channels; each stage transforms and forwards. Use context for cancellation and close channels to signal completion.
func gen(nums ...int) <-chan int { out := make(chan int); go func() { defer close(out); for _, n := range nums { out <- n } }(); return out }
func sq(in <-chan int) <-chan int { out := make(chan int); go func() { defer close(out); for n := range in { out <- n*n } }(); return out }
What's new in Go (1.22 → 1.25)
Go 1.22 loop-variable change?
Each loop iteration now has its own variable, so closures and goroutines capturing i/v no longer all see the last value. Also new in 1.22: for i := range 10.
for i := 0; i < 3; i++ {
go func() { fmt.Println(i) }() // pre-1.22: 3,3,3
} // 1.22+: 0,1,2
for i := range 10 { } // 1.22+: range over int
Enhanced http.ServeMux (1.22)?
Method and wildcard patterns: mux.HandleFunc("GET /users/{id}", h), then r.PathValue("id"). Removes the need for a router library in many services.
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
...
})
mux.HandleFunc("POST /users/{id}/items/{item}", h)
Range-over-func iterators (1.23)?
for v := range seq where seq is func(yield func(T) bool), typed as iter.Seq[T]. Stdlib helpers: slices.All, maps.Keys, slices.Collect.
func Seq(yield func(int) bool) {
for i := 0; i < 3; i++ {
if !yield(i) { return }
}
}
for v := range Seq { fmt.Println(v) }
// iter.Seq[T], slices.All, maps.Keys, slices.Collect
Go 1.24 highlights?
Generic type aliases, Swiss-table-based maps (faster), tool directives in go.mod, testing.B.Loop, os.Root (directory-confined file access), weak pointers, crypto/mlkem (post-quantum).
type Set[T comparable] = map[T]struct{} // generic type alias
tool golang.org/x/tools/cmd/stringer // go.mod tool directive
root, _ := os.OpenRoot("/data") // file access confined to dir
root.Open("../etc/passwd") // rejected
Go 1.25 highlights?
Container-aware GOMAXPROCS (respects cgroup CPU limits, which matters in Kubernetes), testing/synctest GA, sync.WaitGroup.Go(f), experimental Green Tea GC and encoding/json/v2 (behind GOEXPERIMENT).
// 1.25: GOMAXPROCS honours the cgroup CPU limit automatically (k8s)
var wg sync.WaitGroup
wg.Go(func() { work() }) // replaces Add(1) + defer Done()
wg.Wait()
// GOEXPERIMENT=greenteagc, GOEXPERIMENT=jsonv2