Skip to content

Functions: Multiple Returns, Variadics, Closures, Recursion, Function Types ​

"Function literals are closures: they may refer to variables declared in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible." — The Go Programming Language Specification, section "Function literals"

Summary: A Go function is a value with a type; every argument is copied, a function can return several results, and a function literal that mentions an outer variable carries that variable with it. Focus: Declarations and parameters, pass by value (pointers, slice headers, maps, channels), multiple and named results with defer, variadics and ..., closures and loop variables, function types and adapters such as HandlerFunc, method values and expressions, recursion and stack growth, functional options, inlining and escape analysis, vet's printf checks, and the PHP closure comparison. Learning goal: Predict what a call copies, what a closure keeps alive, and what a deep recursion costs, then use function values to build adapters, middleware chains, iterators and options APIs without surprises.

This page owns the mechanics of functions as the language defines them. Pointers and the memory model are in Pointers & Memory Model Basics; slices, maps and their aliasing are in Arrays, Slices & Maps; the error value and panic/recover are in Errors, Wrapping, Panic, Recover & Defer; loops are in Control Flow; type parameters are in Generics. The HTTP middleware catalogue (CORS, logging, recovery) belongs to Middlewares; here you only see the function-type mechanism that makes a chain possible. Goroutine lifetimes are in Goroutines & Channels.

Page map ​

If you are looking forGo to
One-minute tables of parameters, results and closuresEverything in one minute
Why functions are values in GoWhy it exists
Spec, Effective Go, Go 1.22 loop change, Go 1.23 iteratorsWhere it comes from
func name(params) results, grouped parametersDeclarations and parameters
What a call copies: pointers, slices, maps, channelsPass by value
(int, error), _, forwarding f(g())Multiple return values
Named results, naked return, defer changing a resultNamed results and defer
...int, xs..., nil versus emptyVariadic functions
type HandlerFunc func(...), method on a func typeFunction types and adapters
Captured variables, counters, generatorsClosures
Per-iteration loop variables (Go 1.22)Loop variables
iter.Seq, memoisationGenerators, iterators, memoisation
map/filter, callbacksHigher-order functions
x.M versus T.MMethod values and expressions
Tail calls, stack growth, stack overflowRecursion
WithTimeout(...) constructorsFunctional options
-gcflags=-m, "moved to heap", "can inline"Inlining and escape analysis
init, deferred closures in loops, panics in goroutinesinit, defer in loops, goroutine panics
go vet and printf wrappersvet and printf wrappers
Closures in PHPFor PHP/Laravel developers
Fixes with codeSolving the classic problems
Which tool for which needChoosing
Monolith to distributed systemIn architecture
Reproduce the outputsLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The call. Each row is unpacked in the concept catalogue.

Thing you pass or returnWhat the callee receivesCaller sees a change?Typical trap
int, string, bool, float64A copyNoExpecting f(x) to modify x
Struct or array valueA copy of every field or elementNoCopying a large struct in a hot path
Pointer *TA copy of the pointer (same target)Yes, through *pReassigning p inside changes only the local copy
SliceA copy of the 3-word header (pointer, len, cap)Element writes yes; append length noappend in the callee not visible to the caller
MapA copy of a reference to the mapYesConcurrent writes without a lock
ChannelA copy of a reference to the channelYes (shared queue)Sending on a nil or closed channel
Function valueA copy of the function value (code plus captured variables)Captured variables yesClosures sharing one variable
Interface valueA copy of (type, data) pairDepends on the dynamic valueStoring a pointer or a value

The results.

FormExampleWhen to use
One resultfunc Len(s string) intPure computation
Value and errorfunc Open(name string) (*File, error)Anything that can fail; check err first
Value and okfunc (m Map) Get(k string) (v T, ok bool)Lookups where absence is normal
Named resultsfunc Parse(s string) (n int, err error)Documenting two same-typed results, or editing the result in defer
Naked returnreturnVery short functions only
Forwardingf(g())g's results exactly match f's parameters

The closure.

QuestionAnswer
What does a func literal capture?The variables it mentions, by reference, not their values
How long do they live?As long as the closure is reachable; the compiler moves them to the heap if needed
Do two closures from one call share state?Yes, if they captured the same variable
Do two calls of the outer function share state?No, each call makes new variables
Loop variable in Go 1.22+?One new variable per iteration
Loop variable before Go 1.22 (go 1.21 in go.mod)?One variable for the whole loop

Why it exists ​

Programs need to name a computation, reuse it, hand it to something else, and keep a little state next to it. Most languages grew several tools for that (functions, lambdas, objects with one method, callbacks). Go keeps one: a function is an ordinary value with a type, can be assigned, passed and returned, and a function literal can close over the variables around it. Methods, interfaces and goroutines are built on top of that single idea. The cost is that you must always know what a call copies and what a closure keeps alive; both are explicit and cheap to learn, and both are where bugs live.

Fewer concepts, explicit copiesMore concepts, implicit behaviour
One kind of argument passing: by valueBy reference, by value, by name, by need
Functions are values; no separate "callback" typeSeparate lambda, delegate, functor types
Multiple results instead of exceptions for ordinary failureExceptions unwinding through every frame
No tail-call elimination: stack depth is honestGuaranteed tail calls hide depth, hide frames in traces
Closures capture variables, so shared state is visible in the codeCapture by value only: safe, but state cannot be shared

The analogy we reuse on this page: a recipe card in a kitchen. The function is the recipe card. Calling it hands the cook a photocopy of the ingredient list (pass by value); if the list says "the pantry on the left", the photocopy still points at the real pantry (a pointer, a map). A closure is a recipe card clipped to a bag of leftovers: wherever the card goes, the bag goes with it, and two cards clipped to the same bag share the leftovers. A recursive recipe says "to make this, first make a smaller one"; every pending step needs its own counter space (a stack frame), and the kitchen cannot have a billion counters.

Three common misunderstandings, up front ​

  1. "Go passes slices, maps and channels by reference." Go passes everything by value. A slice, map or channel value is a small header that contains a reference, so copying it still reaches the same data. That is why append in the callee is not seen by the caller (it changes only the copied header) while s[0] = 1 is.
  2. "A closure captures the value of the variable when it is created." It captures the variable itself. If the variable changes later, the closure sees the new value. Go 1.22 made loops create a fresh variable per iteration, which removed the best-known version of this bug but not the principle.
  3. "Recursion is free because the stack grows automatically." The stack grows by copying, up to a hard limit (1 GB on 64-bit). Past it the process dies with fatal error: stack overflow, which recover cannot catch. Go does not turn tail calls into jumps.

Where it comes from ​

The language specification defines function declarations, function literals and function types, call semantics ("The return parameters of the function are passed back to the caller when the function returns"), ... parameters and method values. It is the final word on what is guaranteed: for instance, if f is variadic with a final parameter p of type ...T, then "within f the type of p is equivalent to type []T", and "if f is invoked with no actual arguments for p, the value passed to p is nil".

Effective Go teaches the idioms: multiple return values, named results ("The return or result "parameters" of a Go function can be given names"), defer, and the adapter trick that lets any function be an http.Handler: "The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers." That type is the template for every function-type adapter in the standard library and in your code.

Go 1.22 changed for loops: "In Go 1.22, each iteration of the loop creates new variables, to avoid accidental sharing bugs." The change is gated by the go line in go.mod, so a module that says go 1.21 keeps the old semantics. The Go blog preview explained why: the old behaviour caused real production bugs, and static checkers like loopclosure had to "opt for false negatives". Go 1.23 added range-over-func iterators and the iter package, which turn a closure into the thing a for range loop can drive ("Range over Function Types").

Dave Cheney's "Functional options for friendly APIs" (dotGo, 2014) popularised the options pattern that is now everywhere in Go libraries, and the Go Code Review Comments wiki records the conventions around named results (they "will be repetitive in godoc"; prefer unnamed unless they add meaning). The compiler documentation and the GC guide describe inlining and escape analysis: "values placed on the heap because the compiler cannot determine their lifetime are said to escape to the heap".

The concept catalogue ​

Every block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, per-product behaviour, and the fix in Go. The Go snippets live under docs/snippets/go/functions-closures/go/ and are tested with go test -race.

Declarations and parameters Must-know ​

In plain words: a function has a name, a list of typed parameters, and zero or more results. Calling it runs its body with the arguments you passed.

Common misunderstanding: "Parameters are the same as the caller's variables." A parameter is a new local variable initialised from the argument. Changing it never changes the caller's variable.

Definition: func name(p1, p2 T1, p3 T2) (r1 R1, r2 R2) { ... }. Consecutive parameters of the same type may share one type name. Parameters and results are all local variables of the function. Function declarations live at package level; function literals (func(x int) int { return x * 2 }) can appear anywhere an expression can. _ as a parameter name discards the argument. Calling a nil function value panics at run time.

text
1  caller:  total := add(2, 3)        // arguments evaluated left to right
2  runtime: new frame for add; a := 2; b := 3   (copies)
3  add:     return a + b              // result copied back to the caller
4  caller:  total == 5; the frame of add is gone (unless a closure kept something alive)

Real scenario: a handler func(w http.ResponseWriter, r *http.Request) is declared once and used as a value in a router; a test passes a fake function instead of a real dependency; a main passes os.Args[1:] to a function that parses them.

PropertyGoNote
OverloadingNot supportedOne name per package scope; use different names or options
Default argumentsNot supportedVariadic options or an options struct
Named argumentsNot supportedA parameter struct gives the same readability
Nested named functionsNot supportedAssign a function literal to a variable
Generic functionsfunc Map[T, U any](...)See Generics
ComparisonOnly with nilFunction values cannot be map keys or compared

Fix / how to use it: group same-typed parameters (func Pow(base, exp int) int), keep parameter lists short (more than four is a hint to use a struct), and put context.Context first when you have one. See Context.

Pass by value: pointers, slices, maps, channels Must-know ​

In plain words: every call copies its arguments. If the thing copied is a pointer, a slice header, a map or a channel, the copy still leads to the same underlying data.

Common misunderstanding: "Slices and maps are passed by reference, so append inside a function grows the caller's slice." Only the header is copied. append returns a new header; if you do not return it and assign it, the caller never sees the new length.

Definition: an argument of type T is assigned to the parameter, exactly like p = arg. A struct copies every field. A pointer copies the address. A slice copies (ptr, len, cap). A map and a channel are references to runtime structures, and the value copied is the reference. A function value copies the code pointer and the closure environment pointer.

text
     caller                         callee AppendInside(s, 9)
1    s = {ptr:A, len:1, cap:4}
2    call ->                        s' = {ptr:A, len:1, cap:4}     // copy of the header
3                                   s' = append(s', 9)             // within cap: writes A[1] = 9
4                                   s' = {ptr:A, len:2, cap:4}     // only the copy changed
5    <- return s'
6    s still {ptr:A, len:1}         // caller sees len 1 unless it assigns the result
Every argument is a copy; a slice copy still points at the same arraycaller frames: ptr, len 1, cap 4callee frame: AppendInside(s, 9)s (copy): ptr, len 2, cap 4backing arrays[0] = v is visible to bothappend within cap writes here tooThe caller still sees len 1: only its own header decides what it can read.slice header(3 words)slice header(its own copy)79__copy

Real scenario: a Normalize(names []string) that sorts in place surprises a caller who still needs the original order; a function that adds to a map[string]int parameter works, while one that tries m = make(map...) inside does not; a worker receives a chan<- Result and the producer and consumer share the queue.

ArgumentCallee can change what the caller sees viaCannot change
Counter (struct)NothingEverything (it is a copy)
*Counterc.N++Which Counter the caller's pointer targets
[]ints[i] = v (shared array)len, cap, or the array if append reallocates
map[string]intm[k] = v, delete(m, k)Which map the caller's variable holds
chan intSending, receiving, closingWhich channel the caller's variable holds
func()Calling it (may mutate captured variables)Which function the caller holds

Fix / how to use it: pass a pointer when the callee must mutate a struct or when the struct is large and copying shows up in profiles; return a new slice header when the callee appends; document when a function keeps or mutates a slice or map argument.

go
// Package params shows that Go passes every argument by value, and what
// "by value" copies for pointers, slices, maps and channels.
package params

// Counter is a plain struct: passing it copies all fields.
type Counter struct{ N int }

// IncrementValue receives a copy; the caller never sees the change.
func IncrementValue(c Counter) { c.N++ }

// IncrementPointer receives a copy of the pointer; both copies point at the
// same Counter, so the caller sees the change.
func IncrementPointer(c *Counter) { c.N++ }

// ReassignPointer shows that assigning to the parameter itself changes only
// the local copy of the pointer.
func ReassignPointer(c *Counter) { c = &Counter{N: 100}; _ = c }

// SetFirst writes through the slice header's data pointer: visible to callers.
func SetFirst(s []int, v int) {
	if len(s) > 0 {
		s[0] = v
	}
}

// AppendInside appends to a local copy of the slice header; the caller's
// length does not change.
func AppendInside(s []int, v int) []int {
	s = append(s, v)
	return s
}

// PutKey mutates a map through its header; the caller sees the new key.
func PutKey(m map[string]int, k string, v int) { m[k] = v }

// SendOne sends on a channel; a channel value is a reference to shared state.
func SendOne(ch chan<- int, v int) { ch <- v }
go
package params

import "testing"

func TestByValue(t *testing.T) {
	c := Counter{}
	IncrementValue(c)
	if c.N != 0 {
		t.Fatalf("value copy changed caller: %d", c.N)
	}
	IncrementPointer(&c)
	if c.N != 1 {
		t.Fatalf("pointer did not change caller: %d", c.N)
	}
	p := &c
	ReassignPointer(p)
	if p.N != 1 {
		t.Fatalf("reassigning the parameter leaked out: %d", p.N)
	}
}

func TestSliceHeaderCopy(t *testing.T) {
	s := make([]int, 1, 4)
	SetFirst(s, 7)
	if s[0] != 7 {
		t.Fatal("element write must be visible")
	}
	grown := AppendInside(s, 9)
	if len(s) != 1 || len(grown) != 2 {
		t.Fatalf("len(s)=%d len(grown)=%d", len(s), len(grown))
	}
	// Capacity was 4, so the append reused the caller's array.
	if s[:2][1] != 9 {
		t.Fatal("append within capacity should write into the shared array")
	}
}

func TestMapAndChannel(t *testing.T) {
	m := map[string]int{}
	PutKey(m, "a", 1)
	if m["a"] != 1 {
		t.Fatal("map write must be visible")
	}
	ch := make(chan int, 1)
	SendOne(ch, 5)
	if <-ch != 5 {
		t.Fatal("channel value lost")
	}
}

Multiple return values Must-know ​

In plain words: a function can hand back several values at once. The convention is (result, error): you get the value and a way to know whether it is valid.

Common misunderstanding: "I can ignore the second result when I am sure it cannot fail." The compiler lets you write v, _ := f(), but the discard hides a real failure. In production code, discard only when the function documents that the error is always nil.

Definition: the result list (T1, T2, ...) is part of the function's type. The caller receives all results or none: a, b := f(). A call f(g()) is allowed when g's results match f's parameters one for one (also for a variadic f). The blank identifier _ drops a result. If a function has results, every path must end in a return with values (or a naked return for named results).

text
1  v, err := strconv.Atoi("12a")     // v = 0, err = &NumError{Func:"Atoi", Num:"12a", Err: strconv.ErrSyntax}
2  if err != nil { return err }      // handle the failure before touching v
3  use(v)                            // v is meaningful only when err == nil

Real scenario: os.Open returns (*File, error); a map lookup form v, ok := m[k] is the "comma ok" idiom for absence; http.Get returns (*Response, error); a repository method returns (User, bool) for "not found is normal" and (User, error) for "storage may fail".

Return shapeMeaning of the extra valueExample in the standard library
(T, error)Failure, check firstos.ReadFile
(T, bool)Presencemap index, sync.Map.Load, type assertion v, ok := x.(T)
(n int, err error)Count plus error; both may be setio.Reader.Read: "n > 0 and err != nil" is legal
(T1, T2)Two real resultsstrings.Cut, math.Modf
error onlySuccess or failure, no valueos.Remove

Fix / how to use it: always check the error, wrap with context using fmt.Errorf("...: %w", err), and never use the value when err != nil unless the function documents otherwise (io.Reader does). Details on error values are in Errors, Wrapping, Panic, Recover & Defer.

go
// Package results covers multiple return values, named results, naked
// returns and how defer interacts with named results.
package results

import (
	"errors"
	"fmt"
	"strconv"
)

// ErrDivideByZero is a sentinel the caller can test with errors.Is.
var ErrDivideByZero = errors.New("divide by zero")

// Divide returns a value and an error: the idiomatic "(T, error)" pair.
func Divide(a, b int) (int, error) {
	if b == 0 {
		return 0, ErrDivideByZero
	}
	return a / b, nil
}

// MinMax returns two results of the same kind; names document which is which.
func MinMax(xs []int) (lo, hi int, ok bool) {
	if len(xs) == 0 {
		return // naked return: lo=0, hi=0, ok=false
	}
	lo, hi = xs[0], xs[0]
	for _, x := range xs[1:] {
		lo = min(lo, x)
		hi = max(hi, x)
	}
	return lo, hi, true
}

// ParsePort wraps the error with context using a deferred closure that
// reads and writes the named result err.
func ParsePort(s string) (port int, err error) {
	defer func() {
		if err != nil {
			err = fmt.Errorf("parse port %q: %w", s, err)
		}
	}()
	port, err = strconv.Atoi(s)
	if err != nil {
		return 0, err
	}
	if port < 1 || port > 65535 {
		return 0, errors.New("out of range")
	}
	return port, nil
}

// Shadowed shows the classic bug: err declared in an inner scope hides the
// named result, so the deferred check sees nil.
func Shadowed() (err error) {
	defer func() {
		if err != nil {
			err = fmt.Errorf("wrapped: %w", err)
		}
	}()
	if true {
		_, err := strconv.Atoi("x") // new variable, shadows the result
		if err != nil {
			return err // this DOES assign to the result, see test
		}
	}
	return nil
}

// DeferDoubles returns 4: a deferred closure changes the named result after
// the return statement has set it to 2.
func DeferDoubles() (n int) {
	defer func() { n *= 2 }()
	return 2
}

// DeferArgsEvaluatedNow prints 0, not 1: arguments of a deferred call are
// evaluated when the defer statement runs.
func DeferArgsEvaluatedNow() (printed int) {
	i := 0
	defer func(v int) { printed = v }(i)
	i++
	return 0
}

Named results, naked return and defer Important ​

In plain words: you can give the results names. They become variables that start at their zero values, and return on its own returns their current values. A defer can read and change them after the return statement ran.

Common misunderstanding: "defer runs after the function has returned, so it cannot change what the caller gets." Deferred functions run after the return statement sets the results and before the function actually returns. If the results are named, a deferred closure can modify them.

Definition: with named results the function has variables n and err in scope from the start. return x, y assigns x and y to them and then runs deferred calls; a naked return skips the assignment. The compiler rejects a naked return where a named result is shadowed ("result parameter err not in scope at return"). Arguments of a deferred call are evaluated at the defer statement; the function body of a deferred closure is evaluated later.

text
1  func DeferDoubles() (n int) {
2      defer func() { n *= 2 }()    // registered; closure captures n
3      return 2                      // sets n = 2, then runs deferred calls
4  }                                 // deferred closure: n = 4 ; caller receives 4

Real scenario: a repository method that wraps every error with the operation name once, in a deferred closure, instead of in each of ten return statements; defer tx.Rollback() combined with a named err to roll back only if the function failed; a Close error captured from defer f.Close() into the returned err for writers.

TechniqueBenefitCost
Named results for documentation (lo, hi int)Tells the reader which int is whichNone
Naked return in a 5-line functionShortIn long functions the reader must scroll to see what is returned; Code Review Comments discourage it
Deferred closure editing errOne place for wrapping and cleanupThe err must be the named result, not a shadow
if err := f(); err != nilScope-limited errorShadows the named err if you also return naked

Fix / how to use it: use named results for documentation or for a deferred edit, not as a style; never mix naked returns with long bodies; let the compiler catch the naked-return case, and review for := inside if blocks that hide err (the separate shadow analyzer is not in vet's default set).

Variadic functions and the spread operator Must-know ​

In plain words: func Sum(nums ...int) accepts any number of int arguments. Inside, nums is an ordinary slice. At the call site, Sum(xs...) expands an existing slice into the arguments (the spread operator is the trailing ...).

Common misunderstanding: "f(xs...) copies the slice into separate arguments." It does not: it passes xs itself as the variadic parameter ("no new slice is created"), so the callee shares the caller's backing array and can modify it.

Definition: only the final parameter may be variadic. With no arguments for it, the parameter is nil. With individual arguments, a new slice is created for the call. With s..., s is passed unchanged, and s must be assignable to []T; a []string cannot be spread into ...any (compile error: cannot use xs (variable of type []string) as []any value in argument).

text
1  Sum()              // nums == nil, len 0
2  Sum(1, 2, 3)       // nums == []int{1,2,3}, a fresh slice
3  Sum(xs...)         // nums is xs itself: same ptr, len, cap
4  Sum(xs[0], xs[1])  // fresh slice again: writes inside do not reach xs

Real scenario: fmt.Println(args ...any), append(s, elems...), errors.Join(errs ...error), slog.Info(msg, args ...any), functional options New(addr, opts ...Option), and exec.Command(name, arg ...string) where you spread a prepared []string.

Callnums in calleenums == nilWrites visible to caller
f()nil sliceYesNot applicable
f(a, b)New sliceNoNo
f(xs...) with xs == nilxs (nil)YesNot applicable
f([]int{}...)Empty non-nil sliceNoYes (same array)
f(xs...)xsNoYes

Fix / how to use it: do not mutate a variadic slice you did not create unless you document it; to keep a callee from aliasing, pass slices.Clone(xs)...; a []string needs a conversion loop before ...any (vals := make([]any, len(xs))).

go
// Package variadic shows ...T parameters and the ... spread at call sites.
package variadic

import "strings"

// Sum accepts zero or more ints; inside, nums has type []int.
func Sum(nums ...int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}

// IsNil reports whether the variadic slice is nil (no arguments given).
func IsNil(nums ...int) bool { return nums == nil }

// Zero overwrites the first element of whatever slice it receives.
func Zero(nums ...int) {
	if len(nums) > 0 {
		nums[0] = 0
	}
}

// Join builds "prefix: a, b, c" with a fixed parameter before the variadic one.
func Join(prefix string, parts ...string) string {
	return prefix + ": " + strings.Join(parts, ", ")
}

// Describe takes ...any; a []string cannot be spread into it.
func Describe(vals ...any) int { return len(vals) }

Function types, method on a func type (HandlerFunc) and adapters Must-know ​

In plain words: a function can be stored in a variable, passed to other functions, returned from them, and given a named type. You can attach methods to that named type, which lets a plain function satisfy an interface.

Common misunderstanding: "Methods only belong to structs." A method can be declared on any named type you define in your package, including type HandlerFunc func(...). That is how http.HandlerFunc(f) turns a function into an http.Handler.

Definition: type HandlerFunc func(req string) string declares a function type. func (f HandlerFunc) Serve(req string) string { return f(req) } gives it a method. HandlerFunc(fn) is a conversion, not a wrapper allocation: the value is the function itself. A function type is comparable only to nil. A Middleware is func(Handler) Handler: a function that takes a handler and returns a better one.

text
1  base := HandlerFunc(func(req string) string { return "got " + req })   // adapter conversion
2  h := Chain(base, Tag("a"), Tag("b"), Upper)    // builds Tag(a)(Tag(b)(Upper(base)))
3  h.Serve("x")  -> Tag a -> Tag b -> Upper -> base
4  base returns "got x"; Upper: "GOT X"; Tag b: "[b GOT X b]"; Tag a: "[a [b GOT X b] a]"
Function types as adapters: Handler(Middleware(Middleware(base)))Tag("a")Tag("b")Upperbase handlerreq "x""[a [b GOT X b] a]"Each layer is a closure holding next; HandlerFunc(f) is a conversion, not a wrapper object.

Real scenario: http.HandlerFunc, sort.Slice(x, less func(i, j int) bool), slices.SortFunc, strings.Map(mapping func(rune) rune, s), http.RoundTripper stubs in tests via a RoundTripFunc adapter, and testing helpers that take a func(t *testing.T).

PatternFunction typeWhat it replaces
Adaptertype HandlerFunc func(...) with a methodA struct with one method just to satisfy an interface
Callbackfunc(Event) parameterAn observer interface
Strategytype Less func(a, b T) boolA comparator class
Middlewarefunc(Handler) HandlerInheritance or decorators
Optiontype Option func(*Server) errorA config struct with many optional fields
Hook for testsA package variable var now = time.NowA clock interface

Fix / how to use it: define a function type when the signature has a name in your domain; add one method that calls the function; chain with a helper like Chain so the first middleware listed is the outermost.

go
// Package functypes shows function types, methods on function types,
// adapters, middleware chains, method values and method expressions.
package functypes

import (
	"fmt"
	"strings"
)

// Handler is an interface with one method, like net/http.Handler.
type Handler interface {
	Serve(req string) string
}

// HandlerFunc is a function type with a method: the adapter that lets any
// function with this signature be a Handler (same trick as http.HandlerFunc).
type HandlerFunc func(req string) string

// Serve calls f.
func (f HandlerFunc) Serve(req string) string { return f(req) }

// Middleware wraps a Handler and returns a Handler.
type Middleware func(Handler) Handler

// Chain applies middlewares so the first one listed is the outermost.
func Chain(h Handler, mws ...Middleware) Handler {
	for i := len(mws) - 1; i >= 0; i-- {
		h = mws[i](h)
	}
	return h
}

// Upper uppercases the response.
func Upper(next Handler) Handler {
	return HandlerFunc(func(req string) string {
		return strings.ToUpper(next.Serve(req))
	})
}

// Tag returns a Middleware that wraps the response in [name ... name].
func Tag(name string) Middleware {
	return func(next Handler) Handler {
		return HandlerFunc(func(req string) string {
			return fmt.Sprintf("[%s %s %s]", name, next.Serve(req), name)
		})
	}
}

// Greeter has a value receiver and a pointer receiver for method-value demos.
type Greeter struct{ Name string }

// Hello uses a value receiver.
func (g Greeter) Hello() string { return "hello " + g.Name }

// Rename uses a pointer receiver.
func (g *Greeter) Rename(n string) { g.Name = n }

// MapSlice is a higher-order function: it takes and returns functions/slices.
func MapSlice[T, U any](xs []T, f func(T) U) []U {
	out := make([]U, 0, len(xs))
	for _, x := range xs {
		out = append(out, f(x))
	}
	return out
}

// Filter keeps the elements for which keep returns true.
func Filter[T any](xs []T, keep func(T) bool) []T {
	var out []T
	for _, x := range xs {
		if keep(x) {
			out = append(out, x)
		}
	}
	return out
}

Closures and captured variables Must-know ​

In plain words: a function literal that uses a variable from the surrounding function remembers that variable. Each time the outer function runs, a fresh variable is created, and the closure keeps it alive.

Common misunderstanding: "Two closures returned from the same call are independent." They are independent only if they captured different variables. Two closures that mention the same n read and write the same n.

Definition: a closure is the pair (code, environment). The environment holds the captured variables by reference. A captured variable lives as long as any closure that references it. When the closure outlives the frame, the compiler moves the variable to the heap (moved to heap: total in -gcflags=-m). Closures can capture their own function's parameters and named results.

text
1  a := Counter()         // new variable n=0 allocated on the heap; closure A points at it
2  b := Counter()         // another n=0; closure B points at it
3  a(); a(); a()          // n_A = 3
4  b()                    // n_B = 1   (independent environment)
5  // Counter's frame is gone; n_A and n_B live until A and B are unreachable
A closure is code plus pointers to the variables it capturedstack: mainclosure valuesheap: captured variablesa := Counter()b := Counter()func literal code+ &nfunc literal code+ &nn = 3n = 1Counter's frame is gone after it returns; n "moved to heap" because the closure outlives it.Same code, two environments: calling a() never changes b().

Real scenario: a rate limiter that returns an Allow() function holding its token count; a test helper that returns a cleanup func(); a sync.Once wrapper; http.HandlerFunc created inside a constructor so the handler keeps the dependencies (db, logger) in scope; defer func() { ... }() reading the surrounding variables.

Captured variableWhere it livesSafe for concurrent use?
Local int never sharedStack if the closure does not escape, else heapSingle goroutine only
Variable read by a goroutine you startHeapNot safe if written after start; use a channel, sync or atomic
Struct field via captured pointerThe struct's locationAs safe as the struct
Parameter of the outer functionHeap (if closure escapes)Same rules
Loop variable in Go 1.22+One per iterationEach iteration is independent

Fix / how to use it: keep closures small; when a closure must share state across goroutines, guard it with a mutex or make it an atomic type, then run go test -race. See Race Conditions, the Race Detector, Deadlocks.

go
// Package closures shows captured variables, loop variables, generators and
// memoisation.
package closures

import "sync"

// Counter returns a function that closes over n; each call to Counter makes a
// new, independent n.
func Counter() func() int {
	n := 0
	return func() int {
		n++
		return n
	}
}

// Funcs returns three closures created in a loop. With Go 1.22 loop semantics
// (go.mod says go 1.24) every iteration has its own i, so they return 0, 1, 2.
func Funcs() []func() int {
	var fs []func() int
	for i := range 3 {
		fs = append(fs, func() int { return i })
	}
	return fs
}

// SharedFuncs reproduces the pre-1.22 behaviour explicitly: one variable
// declared outside the loop, shared by all closures. All return 3.
func SharedFuncs() []func() int {
	var fs []func() int
	var i int
	for i = 0; i < 3; i++ {
		fs = append(fs, func() int { return i })
	}
	return fs
}

// Fibonacci is a generator: state lives in the captured a and b.
func Fibonacci() func() int {
	a, b := 0, 1
	return func() int {
		v := a
		a, b = b, a+b
		return v
	}
}

// Memoize wraps f with a cache guarded by a mutex. The map and mutex are
// captured variables shared by every call of the returned function.
func Memoize(f func(int) int) func(int) int {
	var mu sync.Mutex
	cache := map[int]int{}
	return func(n int) int {
		mu.Lock()
		if v, ok := cache[n]; ok {
			mu.Unlock()
			return v
		}
		mu.Unlock()
		v := f(n) // computed outside the lock: two goroutines may both compute
		mu.Lock()
		cache[n] = v
		mu.Unlock()
		return v
	}
}

// DeferInLoop returns the values printed by deferred closures in a loop;
// they run last-in first-out and each sees its own iteration variable.
func DeferInLoop() []int {
	var out []int
	func() {
		for i := range 3 {
			defer func() { out = append(out, i) }()
		}
	}()
	return out
}

Loop variables and goroutines Must-know ​

In plain words: before Go 1.22, a for i := 0; ... loop had one i for the whole loop, so closures created inside it all saw the final value. In Go 1.22 and later, each iteration has its own i.

Common misunderstanding: "This was fixed, so I can ignore it." The fix applies only when the module's go.mod says go 1.22 or newer; a module with go 1.21 still has the old behaviour, and shared variables declared outside the loop are still shared.

Definition: the spec now says "Each iteration has its own separate declared variable (or variables)." The new variable for the next iteration is initialised from the previous one's value at the end of the post statement. The loopclosure analyzer of go vet reports references to loop variables from inside goroutines and deferred closures on older semantics, and since Go 1.22 vet "no longer reports references to loop variables from within a function literal that ... would not be a problem".

text
     go.mod: go 1.21                         go.mod: go 1.22 (or newer)
1    for i := 0; i < 3; i++ {                for i := 0; i < 3; i++ {
2        fs = append(fs, func() { print(i) })    fs = append(fs, func() { print(i) })
3    }                                       }
4    run each f  ->  3 3 3                   run each f  ->  0 1 2

Real scenario: the classic for _, v := range values { go func() { use(v) }() } that printed the last value several times; a table-driven test with t.Parallel() in each subtest that ran the last case n times; a defer inside a loop closing the wrong file.

Situationgo 1.21 in go.modgo 1.22+ in go.mod
Closure in for i := ...Shares one iOne i per iteration
Closure in for _, v := rangeShares one vOne v per iteration
Variable declared before the loopSharedShared
v := v shadow copyRequired for safetyRedundant, harmless
go vet loopclosureReports capture in go/deferDoes not report the now-safe cases

Fix / how to use it: keep go in go.mod current; in older modules add v := v as the first line of the body or pass v as an argument (go func(v T) { ... }(v)). The lab shows both outputs from the same program.

Generators, iterators and memoisation Important ​

In plain words: a closure can remember where it stopped and give you the next value each time you call it (a generator). Go 1.23 lets for range drive such a function directly. A memoisation wrapper uses a captured map to remember results of an expensive function.

Common misunderstanding: "Memoisation with a captured map is automatically safe." A plain map is not safe for concurrent use; two goroutines calling the memoised function race on the map. Lock it, or accept that two goroutines may compute the same value and guard only the map access (as the snippet does).

Definition: a generator is a function that returns a function; state lives in captured variables (a, b := 0, 1 for Fibonacci). A range-over-func iterator is a function of type iter.Seq[V] = func(yield func(V) bool); yield returns false when the loop body breaks, and the iterator must stop. Memoisation wraps f with a cache keyed by the arguments; it is valid only for pure functions.

text
1  next := Fibonacci()          // a=0, b=1 captured
2  next() -> 0   (a,b = 1,1)
3  next() -> 1   (a,b = 1,2)
4  next() -> 1   (a,b = 2,3)
5  for v := range Take(Filter(Count(1e9), even), 4) { ... }
6  // loop body is passed as yield; Count stops when yield returns false: 4 values computed, not 1e9

Real scenario: an ID generator in tests; bufio.Scanner-style for scanner.Scan() loops replaced by iter.Seq; slices.Values, maps.Keys returning iterators in Go 1.23; a pagination iterator that fetches page after page lazily; an in-process cache of parsed templates or compiled regexps.

TechniqueState lives inConcurrency
Generator closureCaptured variablesNot safe; one consumer or add a mutex
iter.Seq pipelineThe iterator's local variables and the loop bodySingle goroutine; for parallelism use channels
Memoise with map and sync.MutexCaptured mapSafe; may compute twice
sync.Once / singleflight for one computationThe primitiveSafe; once per key with singleflight
Cache in RedisA serverShared across processes (Redis)

Fix / how to use it: prefer iter.Seq over a channel plus goroutine when the producer is cheap; always check yield's result; unbounded memo maps leak, so cap them or use an expiring cache. See sync & atomic for the lock types.

go
// Package iterators shows range-over-func (Go 1.23): a function of type
// iter.Seq is a closure the for loop body is passed into.
package iterators

import "iter"

// Count yields 0..n-1. The loop body becomes the yield function; returning
// false from yield means "the caller broke out of the loop".
func Count(n int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for i := range n {
			if !yield(i) {
				return
			}
		}
	}
}

// Filter wraps another sequence: higher-order functions compose iterators.
func Filter[T any](seq iter.Seq[T], keep func(T) bool) iter.Seq[T] {
	return func(yield func(T) bool) {
		for v := range seq {
			if keep(v) && !yield(v) {
				return
			}
		}
	}
}

// Take stops after n values.
func Take[T any](seq iter.Seq[T], n int) iter.Seq[T] {
	return func(yield func(T) bool) {
		if n <= 0 {
			return
		}
		i := 0
		for v := range seq {
			if !yield(v) {
				return
			}
			i++
			if i == n {
				return
			}
		}
	}
}

Higher-order functions Important ​

In plain words: a higher-order function takes a function as a parameter or returns one. sort.Slice takes a comparison function; Chain takes middlewares and returns a handler.

Common misunderstanding: "Go lacks map and filter, so functional style is unidiomatic." Go has them as generic helpers you can write in ten lines, and the standard library's slices, maps and iter packages use function arguments throughout. The idiom is: use a plain for loop unless the callback makes the code shorter and clearer.

Definition: with generics, func MapSlice[T, U any](xs []T, f func(T) U) []U works for any element types. The callback runs synchronously in the caller's goroutine unless you start a goroutine. An error from the callback must be returned explicitly: func(T) (U, error).

text
1  MapSlice([]int{1,2,3,4}, strconv.Itoa)            -> ["1","2","3","4"]
2  Filter([]int{1,2,3,4}, func(n int) bool {n%2==0}) -> [2 4]
3  slices.SortFunc(people, func(a, b Person) int { return cmp.Compare(a.Age, b.Age) })

Real scenario: slices.IndexFunc, slices.SortFunc, sort.Slice, strings.FieldsFunc, http.HandlerFunc wrappers, retry helpers Retry(n, func() error), and transaction helpers WithTx(ctx, func(tx *Tx) error).

HelperSignature ideaAllocation note
Mapfunc(T) U over []TOne output slice; preallocate with make([]U, 0, len(xs))
Filterfunc(T) boolOutput grows with append
Reducefunc(acc A, x T) ANo allocation
Retryfunc() errorClosure may capture variables
WithTxfunc(*Tx) errorCallback decides commit or rollback

Fix / how to use it: keep callbacks small; do not hide control flow inside deep callback chains (a plain loop is easier to debug); document whether the callback may be called concurrently or more than once.

Method values and method expressions Important ​

In plain words: x.M (without parentheses) is a function that remembers x; T.M is a function that takes the receiver as its first argument.

Common misunderstanding: "A method value stays up to date with the variable." The receiver is evaluated and saved when the method value is created. With a value receiver that means a copy; with a pointer receiver it means the pointer, so later changes are visible.

Definition: if x has static type T and M is in T's method set, x.M is a method value: "The expression x is evaluated and saved during the evaluation of the method value". T.M is a method expression: a function with the receiver as its first parameter, for example Greeter.Hello has type func(Greeter) string and (*Greeter).Rename has type func(*Greeter, string).

text
1  g := Greeter{Name: "ada"}
2  hello := g.Hello            // value receiver: copy of g saved now
3  rename := g.Rename          // pointer receiver: &g saved
4  rename("bob")               // g.Name = "bob"
5  hello()                     // "hello ada"  (copy)    g.Hello() // "hello bob"

Real scenario: go srv.Serve() and defer mu.Unlock() are method calls, not values; http.HandleFunc("/", app.index) passes a method value so the handler keeps app; sort.Slice(x, byAge.Less); a method expression (*Repo).Save used in a table of operations.

FormTypeReceiver captured
g.Hello (value receiver)func() stringA copy at evaluation time
g.Rename (pointer receiver)func(string)&g at evaluation time
Greeter.Hellofunc(Greeter) stringNone; supply it per call
(*Greeter).Renamefunc(*Greeter, string)None; supply it per call

Fix / how to use it: prefer pointer receivers for types with state when you plan to hand out method values; use method expressions in dispatch tables; do not store a value-receiver method value expecting it to track later changes.

Recursion, tail calls and stack growth Must-know ​

In plain words: a function that calls itself solves a problem by solving a smaller one. Each pending call needs its own stack frame, so very deep recursion uses a lot of memory.

Common misunderstanding: "If I write the recursion in tail form, Go turns it into a loop." It does not. The spec does not promise tail-call elimination and the gc compiler does not do it: SumTail(1_000_000, 0) works only because goroutine stacks grow, and a billion levels ends in fatal error: stack overflow.

Definition: every call allocates a frame on the goroutine's stack. A goroutine starts with a small stack (the runtime source sets a 2 KB minimum, stackMin = 2048) and grows by allocating a larger stack and copying frames, adjusting pointers into the old stack. The maximum is 1 000 000 000 bytes on 64-bit systems (250 000 000 on 32-bit), settable with runtime/debug.SetMaxStack. Exceeding it is a fatal error, not a panic: recover cannot catch it and deferred functions do not run.

text
1  f(0) -> f(1) -> f(2) -> ... each call pushes a frame on the goroutine stack
2  stack full  -> runtime allocates a stack of twice the size, copies the frames
3  ... at 1 000 000 000 bytes:
4  runtime: goroutine stack exceeds 1000000000-byte limit
5  fatal error: stack overflow     (exit status 2, no recover, no deferred calls)
Recursion depth is stack memory; Go never turns a tail call into a jump2 KB minimum startstack full: growcopied to a bigger stackSumTail(3, 0)SumTail(2, 3)SumTail(1, 5)SumTail(0, 6)allocate 2x, copy frames,fix pointers into the stackframes ... frames ... framesfree space for deeper callsAt 1 000 000 000 bytes: "runtime: goroutine stack exceeds 1000000000-byte limit" then "fatal error: stack overflow" (not recoverable).Fix: a loop, or an explicit slice used as a stack.

Real scenario: a tree walk over a deeply nested JSON document or a degenerate linked structure (the Depth test builds a 100 000-deep chain); a recursive-descent parser on untrusted input where an attacker sends 10 million opening brackets; naive Fib(50) taking minutes because of exponential calls rather than depth; a directory walker following a symlink cycle.

TechniqueDepth limitTimeUse when
Plain recursionGoroutine stack (1 GB default)As writtenDepth is bounded by the data's shape, e.g. balanced trees
LoopNoneSame or betterThe recursion was linear (SumTail)
Explicit stack (slice)Heap memorySimilarDeep or attacker-controlled depth
MemoisationSame as recursionFrom exponential to linearOverlapping subproblems (FibMemo)
Depth counter parameterYou chooseSameParsers: fail with an error at depth 1000

Fix / how to use it: pass a depth limit for untrusted input and return an error when it is hit; convert linear recursion to a loop; use an explicit stack for deep traversals; memoise overlapping subproblems.

go
// Package recursion shows recursion, the absence of tail-call elimination,
// stack growth, and converting recursion to a loop or explicit stack.
package recursion

// Factorial is plain recursion; each call needs its own stack frame.
func Factorial(n uint64) uint64 {
	if n <= 1 {
		return 1
	}
	return n * Factorial(n-1)
}

// SumTail is written in tail form (the recursive call is the last action),
// but the gc compiler does not turn it into a jump: the stack still grows.
func SumTail(n, acc int) int {
	if n == 0 {
		return acc
	}
	return SumTail(n-1, acc+n)
}

// SumLoop is the loop the compiler will not write for you.
func SumLoop(n int) int {
	acc := 0
	for i := 1; i <= n; i++ {
		acc += i
	}
	return acc
}

// Node is a binary tree node.
type Node struct {
	Val         int
	Left, Right *Node
}

// Depth is naturally recursive: the call structure mirrors the data.
func Depth(n *Node) int {
	if n == nil {
		return 0
	}
	return 1 + max(Depth(n.Left), Depth(n.Right))
}

// DepthIter does the same with an explicit stack on the heap, so depth is
// limited by memory, not by the goroutine stack limit.
func DepthIter(root *Node) int {
	type item struct {
		n *Node
		d int
	}
	if root == nil {
		return 0
	}
	stack := []item{{root, 1}}
	best := 0
	for len(stack) > 0 {
		it := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		best = max(best, it.d)
		if it.n.Left != nil {
			stack = append(stack, item{it.n.Left, it.d + 1})
		}
		if it.n.Right != nil {
			stack = append(stack, item{it.n.Right, it.d + 1})
		}
	}
	return best
}

// Fib is the classic exponential-time recursion (about 1.6^n calls).
func Fib(n int) int {
	if n < 2 {
		return n
	}
	return Fib(n-1) + Fib(n-2)
}

// FibMemo adds a cache passed by the caller; it is a closure-free memo.
func FibMemo(n int, memo map[int]int) int {
	if n < 2 {
		return n
	}
	if v, ok := memo[n]; ok {
		return v
	}
	v := FibMemo(n-1, memo) + FibMemo(n-2, memo)
	memo[n] = v
	return v
}

Functional options Important ​

In plain words: a constructor takes the required arguments and then any number of small option functions that each change one setting. New(addr, WithTimeout(2*time.Second)).

Common misunderstanding: "Options are just a fancy config struct." A struct forces callers to pass nil or a zero value for defaults and lets them set fields you never meant to export. Variadic options keep the default case a one-liner ("the invocation for the default behaviour becomes as concise as possible") and let each option validate its own input and return an error.

Definition: type Option func(*Server) error; constructors such as WithTimeout(d) return an Option closure that captures d; New(addr string, opts ...Option) (*Server, error) applies defaults, then each option in order. Later options override earlier ones. The struct keeps its fields unexported, so the options are the only way to configure it, and the set can grow without breaking callers.

text
1  New("127.0.0.1:8080")                                   // defaults: timeout 30s, maxConn 100
2  New("127.0.0.1:8080", WithTimeout(time.Second))         // override one
3  New("127.0.0.1:8080", WithMaxConn(0))                   // option returns error: maxConn must be at least 1

Real scenario: grpc.NewServer(grpc.Creds(...), grpc.MaxRecvMsgSize(...)), zap.New(core, zap.AddCaller()), redis.NewClient(&redis.Options{...}) as the contrasting struct style, and your own client libraries that need to add settings without breaking callers.

ApproachDefaultsValidationExtensible without breakingReadability at call site
Positional parametersMust pass allAt the endNo (signature changes)Poor beyond three
Config structZero values onlyAfter constructionYes (new field)Good, but every field is public
Builder with methodsBuilder holds themAt Build()YesGood, verbose
Functional optionsSet before options runPer optionYesGood; defaults are free

Fix / how to use it: keep options for configuration, not for required arguments; make options return error if validation matters; expose a getter if callers need to read the final settings; document the order in which options apply.

go
// Package options implements the functional options pattern
// (Dave Cheney, "Functional options for friendly APIs").
package options

import (
	"errors"
	"time"
)

// Server is the thing being configured; fields are unexported.
type Server struct {
	addr    string
	timeout time.Duration
	maxConn int
}

// Option mutates a Server under construction and may reject bad input.
type Option func(*Server) error

// WithTimeout sets the per-request timeout.
func WithTimeout(d time.Duration) Option {
	return func(s *Server) error {
		if d <= 0 {
			return errors.New("timeout must be positive")
		}
		s.timeout = d
		return nil
	}
}

// WithMaxConn sets the connection limit.
func WithMaxConn(n int) Option {
	return func(s *Server) error {
		if n < 1 {
			return errors.New("maxConn must be at least 1")
		}
		s.maxConn = n
		return nil
	}
}

// New applies defaults first, then each option in order. Zero options is the
// common case and needs no nil or placeholder argument.
func New(addr string, opts ...Option) (*Server, error) {
	s := &Server{addr: addr, timeout: 30 * time.Second, maxConn: 100}
	for _, opt := range opts {
		if err := opt(s); err != nil {
			return nil, err
		}
	}
	return s, nil
}

// Addr, Timeout and MaxConn expose the settings.
func (s *Server) Addr() string           { return s.addr }
func (s *Server) Timeout() time.Duration { return s.timeout }
func (s *Server) MaxConn() int           { return s.maxConn }

Inlining and escape analysis Important ​

In plain words: the compiler may paste a small function into its caller (inlining) and decides for each variable whether it can stay on the stack or must go to the heap (escape analysis). You can ask it what it decided.

Common misunderstanding: "Returning a pointer to a local variable is a bug, as in C." In Go it is fine: the compiler sees that the variable outlives the call and moves it to the heap (moved to heap: p). The cost is one allocation, visible in profiles, not a crash.

Definition: go build -gcflags=-m prints optimisation decisions (-m=2 adds reasons). can inline AddInlined means the function body is within the inliner's budget (80 nodes in cmd/compile/internal/inline/inl.go at Go 1.27; the number can change between releases). moved to heap: total or func literal escapes to heap means an allocation. does not escape means the value can stay on the stack. The GC guide explains why it matters: values that escape are what the garbage collector must track. //go:noinline prevents inlining so a demonstration stays visible.

text
1  $ go build -gcflags=-m ./escape
2  escape/escape.go:9:6: can inline AddInlined
3  escape/escape.go:16:2: moved to heap: p                 // NewPointer returns &p
4  escape/escape.go:31:2: moved to heap: total             // closure from Adder outlives the frame
5  escape/escape.go:32:9: func literal escapes to heap
6  escape/escape.go:42:22: f does not escape               // Apply only calls f
7  escape/escape.go:51:12: func literal does not escape    // closure passed to Apply stays on the stack

Real scenario: a hot function allocating 1 million small objects per second because a helper returns pointers; a benchmark showing 0 allocs/op after a callback parameter stopped escaping; a profile where a method value stored in a struct field forces its receiver to the heap.

PatternTypically escapes?Why
Return &localYesMust outlive the frame
Closure returned from a functionYes (captured variables)Environment outlives the frame
Closure passed to a function that only calls itNoCallee's parameter does not escape
Value sent on a channel or stored in an interface held elsewhereOften yesLifetime unknown to the compiler
fmt.Println(x) argumentOften yesBoxed into any
Small leaf functionInlinedWithin budget, no loops or calls beyond limits in older releases

Fix / how to use it: do not optimise first; measure with go test -bench . -benchmem and read -gcflags=-m for the hot path; reduce allocations by returning values rather than pointers for small types, by passing callbacks that do not escape, and by pre-sizing slices. The test TestAllocations shows AllocsPerRun agreeing with the compiler output. See Testing & Benchmarking.

go
// Package escape has tiny functions whose compiler decisions can be read with
// go build -gcflags=-m (and -m=2 for reasons).
package escape

// Point is a small value type.
type Point struct{ X, Y int }

// AddInlined is small enough for the compiler to inline into callers.
func AddInlined(a, b int) int { return a + b }

// NewPointer returns the address of a local: the Point must outlive the call,
// so it escapes to the heap.
//
//go:noinline
func NewPointer(x, y int) *Point {
	p := Point{x, y}
	return &p
}

// NewValue returns a copy: nothing escapes, the Point can live in registers
// or on the caller's stack.
//
//go:noinline
func NewValue(x, y int) Point { return Point{x, y} }

// Adder returns a closure that captures total by reference: total escapes
// because the closure outlives Adder's frame.
//
//go:noinline
func Adder() func(int) int {
	total := 0
	return func(n int) int {
		total += n
		return total
	}
}

// Apply calls f on each element; f does not escape, so closures passed here
// can stay on the stack.
//
//go:noinline
func Apply(xs []int, f func(int)) {
	for _, x := range xs {
		f(x)
	}
}

// SumWithClosure passes a capturing closure to Apply without heap allocation.
func SumWithClosure(xs []int) int {
	sum := 0
	Apply(xs, func(x int) { sum += x })
	return sum
}

init functions, defer in loops and panics in goroutines Good to know ​

In plain words: init is a special function that runs automatically before main; defer runs when the surrounding function ends, not when the loop iteration ends; and a panic in a goroutine kills the whole program.

Common misunderstanding: "recover in main protects me from a panic in any goroutine." recover works only inside a deferred function in the goroutine that panicked. A panic in another goroutine terminates the process with exit status 2.

Definition: a package may declare several func init(); they take no arguments and return nothing, "cannot be referred to from anywhere in a program", and run after the package-level variables are initialised, in the order they appear in the source. defer pushes a call that runs when the function returns (last in, first out); in a loop the calls pile up until the function ends. An unrecovered panic in any goroutine prints panic: ... plus the goroutine's stack and exits the program.

text
1  go func() { panic("boom in goroutine") }()
2  main:  time.Sleep(100ms); defer fmt.Println("main deferred") never runs
3  output: panic: boom in goroutine
4          goroutine 18 [running]:
5          main.main.func1() ... exit status 2

Real scenario: an init registering a database driver (import _ "github.com/lib/pq"); for _, name := range files { f, _ := os.Open(name); defer f.Close() } holding thousands of descriptors until the function ends; a worker goroutine panicking on a nil pointer and taking the HTTP server down; a recover wrapper at the top of each goroutine that logs and restarts the worker.

ItemRuleCommon fix
initSeveral allowed per package; order = file order presented to the compiler, then source orderPrefer explicit constructors; keep init for registration
defer in a loopRuns at function endExtract the loop body into a function or close explicitly
defer argumentsEvaluated at the defer statementUse a closure to read the latest value
Panic in a goroutineNot caught by other goroutinesRecover inside the goroutine's top-level deferred function
os.ExitSkips deferred callsReturn from main after cleanup

Fix / how to use it: wrap goroutine bodies in a helper that recovers and reports; close resources inside a small function per iteration; keep package init free of I/O. Panic and recovery semantics are in Errors, Wrapping, Panic, Recover & Defer; goroutine lifetime is in Goroutines & Channels.

go vet and printf wrappers Good to know ​

In plain words: go vet knows the format verbs of fmt.Printf. If you write your own Logf(format string, args ...any) that forwards to fmt.Sprintf, vet learns that your function is a printf wrapper and checks every call to it.

Common misunderstanding: "vet checks only the standard library." It infers wrappers: a function whose last parameters are format string, args ...any and that passes them straight to a known printf-like function becomes one. If you transform the format first (for example format + "\n"), the inference stops and mistakes go undetected.

Definition: the printf analyzer reports calls with the wrong verb for the argument type or the wrong number of arguments. Names ending in f are a hint, not a requirement. go test runs a small subset of vet checks automatically, including printf.

text
1  func logf(format string, args ...any) { fmt.Printf(format, args...) }
2  logf("user %d", "ada")     -> main.go:8:13: vet.logf format %d has arg "ada" of wrong type string
3  logf("two %s %s", "a")     -> main.go:9:15: vet.logf format %s reads arg #2, but call has 1 arg

Real scenario: a structured logger wrapper shipped with a typo that logged %!d(string=ada) in production for months; a CI step go vet ./... that now fails the build; a custom error constructor Errorf that vet checks because it forwards to fmt.Errorf.

MistakeRuntime output without vetvet message (Go 1.27 run)
Wrong verbuser %!d(string=ada)format %d has arg "ada" of wrong type string
Too few argumentsa %!s(MISSING)format %s reads arg #2, but call has 1 arg
Too many argumentshi%!(EXTRA string=extra)call has arguments but no formatting directives
Non-constant format stringUnsafe if user-controllednon-constant format string in call to ...

Fix / how to use it: run go vet ./... in CI and locally; keep the wrapper's format and args untouched; if you need a newline or prefix, add it to the output, not to the format.

go
// Package vetwrap shows a printf-style wrapper that go vet recognises: it
// forwards format and args... to fmt.Sprintf, so vet checks its callers.
package vetwrap

import (
	"fmt"
	"strings"
)

// Logger collects lines.
type Logger struct{ lines []string }

// Logf is detected by vet as a printf wrapper because it passes format and
// args... straight to fmt.Sprintf.
func (l *Logger) Logf(format string, args ...any) {
	l.lines = append(l.lines, fmt.Sprintf(format, args...))
}

// String joins the collected lines.
func (l *Logger) String() string { return strings.Join(l.lines, "\n") }

Go ​

Example ​

The snippets under docs/snippets/go/functions-closures/go/ are one module with ten small packages. A single test run exercises them all:

bash
cd docs/snippets/go/functions-closures/go
gofmt -l . && go vet ./... && go test -race ./...
mod
module academy/functions-closures

go 1.24
go
package closures

import (
	"slices"
	"sync"
	"sync/atomic"
	"testing"
)

func TestCounterIndependent(t *testing.T) {
	a, b := Counter(), Counter()
	a()
	a()
	if a() != 3 || b() != 1 {
		t.Fatal("each Counter() call must own its n")
	}
}

func collect(fs []func() int) []int {
	var out []int
	for _, f := range fs {
		out = append(out, f())
	}
	return out
}

func TestLoopVariables(t *testing.T) {
	if got := collect(Funcs()); !slices.Equal(got, []int{0, 1, 2}) {
		t.Fatalf("per-iteration: %v", got)
	}
	if got := collect(SharedFuncs()); !slices.Equal(got, []int{3, 3, 3}) {
		t.Fatalf("shared: %v", got)
	}
}

func TestFibonacci(t *testing.T) {
	next := Fibonacci()
	var got []int
	for range 8 {
		got = append(got, next())
	}
	if !slices.Equal(got, []int{0, 1, 1, 2, 3, 5, 8, 13}) {
		t.Fatal(got)
	}
}

func TestMemoize(t *testing.T) {
	var calls atomic.Int32
	slow := func(n int) int { calls.Add(1); return n * n }
	sq := Memoize(slow)
	sq(4)
	sq(4)
	sq(4)
	if calls.Load() != 1 {
		t.Fatalf("slow called %d times", calls.Load())
	}
	var wg sync.WaitGroup
	for i := range 20 {
		wg.Add(1)
		go func() { defer wg.Done(); sq(i % 5) }()
	}
	wg.Wait() // run with -race: the captured map is guarded by mu
}

func TestDeferInLoop(t *testing.T) {
	if got := DeferInLoop(); !slices.Equal(got, []int{2, 1, 0}) {
		t.Fatal(got)
	}
}

The Go angle ​

Go has one kind of function value, and almost everything else is built on it. http.HandlerFunc, sort.Slice, slices.SortFunc, sync.OnceFunc, context.AfterFunc and testing.T.Cleanup all take or return plain functions; defer and go accept a function call; method values give you callbacks that remember their receiver. The language keeps a few deliberate gaps: no overloading, no default arguments, no tail-call elimination, and no way to compare functions. Each gap pushes you towards a visible alternative: distinct names, options, loops, and explicit state.

For PHP/Laravel developers ​

PHP closures, arrow functions and the callable type map onto Go function values, with different capture rules.

PHPGoDifference
function ($x) use ($y) { ... }func(x int) int { return x + y }PHP captures by value at creation unless use (&$y); Go always captures the variable itself
fn($x) => $x + $y (arrow function)func(x int) int { return x + y }PHP arrow functions capture by value automatically; Go has no arrow syntax
callable typefunc(string) string or a named function typeGo types state the exact signature; PHP callable also accepts strings and arrays
strlen(...) first-class callable syntax (PHP 8.1)strings.ToUpper as a valueIn Go every function name already is a value
array_map($fn, $items)MapSlice(items, fn)Go needs generics or a loop; there is no built-in map
Variadic function f(...$xs)func f(xs ...T)Same idea; f(...$arr) is f(arr...); Go has no named-argument spread
static function / $this bindingmethod value obj.MethodGo binds the receiver when you evaluate the method value
Exceptions(T, error) resultsSee errors
php
<?php
$y = 1;
$byValue = function ($x) use ($y) { return $x + $y; };   // y copied now
$byRef   = function ($x) use (&$y) { return $x + $y; };  // y shared
$arrow   = fn($x) => $x + $y;                            // y copied at creation
$y = 100;
echo $byValue(1), ' ', $byRef(1), ' ', $arrow(1);        // 2 101 2

The Go equivalent of $byValue needs an explicit copy (y2 := y before the literal); the default Go closure behaves like $byRef. PHP passes scalars and arrays by value and objects as handles (the handle is copied, the object shared), which is the same shape as Go passing a pointer or a map. In Laravel, Route::get('/', function () {...}), Collection::map(fn ($x) => ...) and middleware function ($request, Closure $next) all correspond to the function-type patterns above; the Go middleware chain is func(Handler) Handler where Laravel has $next($request).

Mechanics ​

What the compiler and runtime do with a call ​

StepDescriptionObservable through
1. EvaluateFunction value and arguments are evaluated in the usual order (operands left to right)Side effects order in tests
2. CopyArguments are assigned to the parametersMutating a parameter does not change the caller
3. FrameA frame holds parameters, locals and results; registers are used when the ABI allowsruntime.Callers, panic traces
4. InlineSmall functions are pasted into the caller-gcflags=-m "can inline", -gcflags=-l disables
5. DeferDeferred calls record their evaluated argumentsRun LIFO at return
6. ReturnResults are copied to the caller; named results are visible to deferred closuresDeferDoubles

Exact messages ​

SituationMessage
Too few values returnednot enough return values followed by have (number) and want (int, error)
Value not useddeclared and not used: v
Result unused (vet unusedresult)result of fmt.Sprintf call not used
Naked return with shadowed resultresult parameter err not in scope at return (the compiler adds inner declaration of var err error)
Spread type mismatchcannot use xs (variable of type []string) as []any value in argument to f
Variadic not lastcan only use ... with final parameter
Missing returnmissing return
Nil function callpanic: runtime error: invalid memory address or nil pointer dereference
Stack exhaustedruntime: goroutine stack exceeds 1000000000-byte limit then fatal error: stack overflow
Panic in goroutinepanic: boom in goroutine then goroutine 18 [running]: and exit status 2
Index error inside a callbackpanic: runtime error: index out of range [3] with length 3

Flags and settings ​

KnobEffect
go build -gcflags=-mPrint inlining and escape decisions
go build -gcflags='-m=2'Add the reason for each decision
go build -gcflags=-lDisable inlining
go build -gcflags='-N -l'Disable optimisation and inlining for debuggers
//go:noinlinePrevent inlining of one function
go vet ./...Run printf, loopclosure, unusedresult and other analyzers
debug.SetMaxStack(n)Change the goroutine stack limit
GOTRACEBACK=allPrint all goroutines on a fatal panic
go.mod: go 1.22Per-iteration loop variables
go test -raceDetect unsynchronised access to captured variables

Unsafe use of a captured variable across goroutines ​

text
1  count := 0
2  for range 100 { go func() { count++ }() }     // 100 goroutines write one captured variable
3  go test -race ->  WARNING: DATA RACE
4                    Write at 0x00c000012345 by goroutine 8: main.main.func1()

The closure shares count; the race detector reports it. Use atomic.Int64 or a mutex.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
append in a callee is lostReturn the slices = Add(s, v)ExplicitCallers must assign
Callee must mutate a structPointer parameterfunc (c *Counter) Inc()No copyNil pointer risk
Ignored errorsCheck and wrapif err != nil { return fmt.Errorf("op: %w", err) }Context in messagesRepetition
Error wrapping repeated in every returnDeferred closure on a named errSee ParsePortOne placeNeeds named result, no shadowing
Closures all print the last valuePer-iteration variablesgo 1.22 in go.mod, or v := vSafeOld modules need the line
Shared mutable state in closuresLock or atomicsync.Mutex / atomic.Int64Race-freeContention
Expensive pure function called repeatedlyMemoiseMemoize(f)SpeedMemory growth, key choice
Deep recursionExplicit stack or depth limitDepthIter, depth parameterNo overflowMore code
Many optional settingsFunctional optionsNew(addr, WithX())Extensible APIMore types
Function must satisfy an interfaceAdapter function typeHandlerFunc(f)No structOne extra type
Allocation in a hot pathRead -gcflags=-m; avoid escapeReturn values, non-escaping callbacksFewer allocsReadability trade-off
printf typo in a wrappergo vetKeep format, args... untouchedCompile-time-ish checkOnly inferred wrappers

Error wrapping with a deferred closure ​

go
func ParsePort(s string) (port int, err error) {
	defer func() {
		if err != nil {
			err = fmt.Errorf("parse port %q: %w", s, err)
		}
	}()
	port, err = strconv.Atoi(s)
	// ...
}

The results_test.go test shows the caller receiving parse port "http": strconv.Atoi: parsing "http": invalid syntax.

go
package results

import (
	"errors"
	"strings"
	"testing"
)

func TestDivide(t *testing.T) {
	if _, err := Divide(1, 0); !errors.Is(err, ErrDivideByZero) {
		t.Fatalf("want ErrDivideByZero, got %v", err)
	}
	if q, err := Divide(9, 3); err != nil || q != 3 {
		t.Fatalf("got %d, %v", q, err)
	}
}

func TestMinMax(t *testing.T) {
	if _, _, ok := MinMax(nil); ok {
		t.Fatal("empty slice must report ok=false")
	}
	lo, hi, ok := MinMax([]int{3, -1, 8})
	if lo != -1 || hi != 8 || !ok {
		t.Fatalf("got %d %d %v", lo, hi, ok)
	}
}

func TestParsePortWrapsViaDefer(t *testing.T) {
	_, err := ParsePort("http")
	if err == nil || !strings.HasPrefix(err.Error(), `parse port "http": `) {
		t.Fatalf("unexpected error: %v", err)
	}
	if p, err := ParsePort("8080"); err != nil || p != 8080 {
		t.Fatalf("got %d, %v", p, err)
	}
}

func TestShadowedStillReturnsError(t *testing.T) {
	// "return err" assigns to the named result, so the deferred closure runs
	// with err set. (A naked "return" in the inner scope would not compile:
	// "result parameter err not in scope at return".)
	err := Shadowed()
	if err == nil || !strings.HasPrefix(err.Error(), "wrapped: ") {
		t.Fatalf("got %v", err)
	}
}

func TestDeferAndNamedResult(t *testing.T) {
	if got := DeferDoubles(); got != 4 {
		t.Fatalf("got %d, want 4", got)
	}
	if got := DeferArgsEvaluatedNow(); got != 0 {
		t.Fatalf("got %d, want 0", got)
	}
}

A retry helper that takes a function ​

go
// Retry runs fn up to attempts times, sleeping with a doubling delay.
func Retry(ctx context.Context, attempts int, delay time.Duration, fn func(context.Context) error) error {
	var err error
	for i := range attempts {
		if err = fn(ctx); err == nil {
			return nil
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(delay << i):
		}
	}
	return fmt.Errorf("after %d attempts: %w", attempts, err)
}

The callback is a closure that captures the request being retried, so the helper does not need to know what it does. Whether retrying is safe is a design question: see idempotency in Idempotent Consumers.

Where state belongs in a memoised function ​

A process-local memo disappears on restart and is not shared between replicas. When the cached value must survive or be shared, move it to a table (or Redis) and keep the function a thin wrapper:

sql
CREATE TABLE memo_cache (
    fn_name   text        NOT NULL,
    arg_hash  bytea       NOT NULL,
    result    jsonb       NOT NULL,
    expires_at timestamptz NOT NULL,
    PRIMARY KEY (fn_name, arg_hash)
);
-- lookup used by the wrapper closure
SELECT result FROM memo_cache
WHERE fn_name = $1 AND arg_hash = $2 AND expires_at > now();

Choosing ​

NeedUseWhyAvoid
A named piece of logicTop-level functionEasy to test and readA closure for everything
State next to one functionClosureCaptured variables are privateA global variable
State plus several operationsStruct with methodsClear API, testableA bag of closures
Plug a function into an interfaceFunction type with a methodOne-line adapterA struct with one method
Many optional settingsFunctional optionsDefaults free, extensibleBoolean parameters
A few fixed settingsConfig structSimple, serialisableOptions for three fields
Lazy sequenceiter.SeqNo goroutine, no channelA goroutine per generator
Linear recursionLoopNo stack growthTail-recursive style
Tree recursion with bounded depthRecursionMirrors the dataExplicit stack unless depth is hostile
Untrusted depthDepth limit or explicit stackPrevents fatal error: stack overflowUnbounded recursion
Hot path allocationMeasure then reduce escapesData over guessesPremature micro-optimisation
A callback needing cancellationPass context.ContextStandardA custom stop flag

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

Functions are the unit of reuse. Handlers are functions registered on a router; dependencies reach them through closures created in constructors (func (a *App) index(w, r) used as a method value). A middleware chain is Chain(h, Logging, Recover). Example: main builds app := NewApp(db, logger) and registers mux.HandleFunc("GET /items", app.listItems); the method value carries app, and the handler needs no global variable. Keep recursion bounded and pass context.Context first in every function that does I/O.

Modular monolith / multiple databases ​

Modules expose small function-typed seams instead of importing each other: type PriceLookup func(ctx context.Context, sku string) (Money, error) is a dependency the orders module receives from the catalogue module. The seam is one function value, easy to fake in tests and easy to replace later by an RPC client with the same signature. Option functions configure each module (orders.New(db, orders.WithClock(clock))); closures keep the module's private state out of package-level variables. The cost is that the type is a contract: change its signature and every adapter must follow.

Microservices ​

A function signature does not survive a network boundary. A func(ctx, id) (User, error) becomes an RPC with a timeout, a retry policy, a wire format and a failure mode that includes "unknown". The function-type seam from the modular monolith is what makes the move cheap: the orders module keeps calling PriceLookup, and a gRPC-backed implementation replaces the in-process one. Middleware as func(Handler) Handler becomes interceptors (tracing, auth, metrics) applied uniformly. Closures that hold request-scoped state must not be shared across requests: a handler created per request is fine, a handler that captures a mutable variable is a data race under concurrent load. Example flow: gateway handler -> Chain(h, Auth, Trace) -> PriceLookup (gRPC client) -> timeout from ctx -> errors.Is(err, context.DeadlineExceeded).

Distributed data (replicas, caches, multi-region) ​

A memoised function is a cache with no invalidation. In one process it is a captured map; across replicas each process has its own copy, so two instances can answer differently after the data changes. Use a TTL, key versioning, or a shared cache (see Redis) when the answer must be consistent; use singleflight to avoid a thundering herd when a hot key expires; and treat any function that reads a replica as eventually consistent (see Replication, Read Replicas & Failover). A closure that captured a database handle created before a failover keeps using the old connection pool: construct handles through a function that resolves the current primary, not once at start-up.

Scaling path ​

ScaleWhat changes for functionsExample
1x: a few requests per secondClarity first; plain functions and closuresHandlers as method values
10x: hundreds of requests per secondAllocation and lock contention show up in profilesRead -gcflags=-m; replace per-request closures that escape; add sync.Pool where measured
100x: many replicasPer-process memo and state no longer sharedMove memo to Redis or a table; idempotent callbacks; retry helpers with jitter
Many teamsFunction types become contractsVersioned interfaces, generated clients instead of hand-written function types
Hostile inputDepth limits and timeouts everywhereParser depth cap, context deadlines on callbacks

Lab ​

All commands run on a laptop with Go installed; no network is needed. Output below was produced with Go 1.27.4 on macOS (arm64) except where labelled expected, not run.

Setup

bash
cd docs/snippets/go/functions-closures/go
go version
gofmt -l . && go vet ./... && go test -race ./...

Output: ok for each of the ten packages (verified).

Experiment 1: loop variables across versions

go
package main

import "fmt"

func main() {
	var fs []func()
	for i := 0; i < 3; i++ {
		fs = append(fs, func() { fmt.Print(i, " ") })
	}
	for _, f := range fs {
		f()
	}
	fmt.Println()
}

With go 1.21 in go.mod: 3 3 3. With go 1.22: 0 1 2. (Both outputs observed.)

Experiment 2: read the compiler's decisions

bash
go build -gcflags=-m ./escape

Observed output includes can inline AddInlined, moved to heap: p, moved to heap: total, func literal escapes to heap, f does not escape and func literal does not escape, as listed in Inlining and escape analysis.

Experiment 3: vet on a printf wrapper

bash
go vet ./...

Observed for a logf(format string, args ...any) that forwards to fmt.Printf:

text
main.go:8:13: vet.logf format %d has arg "ada" of wrong type string
main.go:9:15: vet.logf format %s reads arg #2, but call has 1 arg

Experiment 4: stack overflow

go
package main

func f(n int) int { return f(n+1) + 1 }

func main() { println(f(0)) }
text
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow

The exit status is 2; the output shows a long stack trace. (Observed.)

Experiment 5: a panic in a goroutine

text
panic: boom in goroutine

goroutine 18 [running]:
main.main.func1()
created by main.main in goroutine 1
exit status 2

The deferred fmt.Println in main never prints. (Observed.)

Experiment 6: race on a captured counter (expected, not run)

Write the loop from the mechanics section and run go test -race; expected: WARNING: DATA RACE naming the closure main.main.func1. Output is expected, not run.

Common misconceptions ​

BeliefReality
"Go passes slices and maps by reference"Everything is passed by value; slices, maps and channels contain references
"append inside a function grows the caller's slice"Only the callee's header changes; return and assign it
"A closure copies the variable's value"It shares the variable
"The loop variable bug is gone everywhere"Only for modules with go 1.22 or newer in go.mod
"defer cannot change the return value"With named results, a deferred closure can
"Naked returns are always bad"Fine in very short functions; discouraged in long ones
"Tail recursion is optimised"The gc compiler does not do tail-call elimination
"A stack overflow can be recovered"It is a fatal error; recover cannot catch it
"Returning a pointer to a local is unsafe"The compiler moves it to the heap
"f(xs...) copies the slice"It passes xs itself; the callee shares the array
"recover in main protects goroutines"A panic in another goroutine kills the process
"Method values track later changes of the receiver"A value receiver is copied when the method value is evaluated
"Functions can be compared or used as map keys"Only comparison with nil is allowed

Cheat sheet ​

TopicWhat to remember
ArgumentsAlways copied; pointer, slice, map, channel copies share data
Slice parameterElement writes visible; append visible only if you return it
Results(T, error); check err first; _ discards
Named resultsDocumentation or deferred edits; avoid naked returns in long functions
deferLIFO; arguments evaluated now; can edit named results
VariadicLast parameter; nil when empty; xs... shares the array
Function typestype F func(...); methods allowed; adapter pattern
ClosureCaptures variables, not values; lives as long as reachable
Loop variablesPer iteration from Go 1.22 (go.mod decides)
Iteratorsiter.Seq[V]; check yield's return value
RecursionNo tail calls; 1 GB stack cap; fatal error, not a panic
OptionsNew(required, opts ...Option); options validate and return error
Method valueReceiver evaluated at creation; T.M takes receiver first
Compiler viewgo build -gcflags=-m; //go:noinline for demos
Static checksgo vet ./...; printf wrappers must forward format, args...

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A function receives s []int and does s = append(s, 1). Does the caller's slice get longer? Must-know ​

Answer

Answer: No. The callee changed its own copy of the header. If the capacity was large enough the new element is written into the shared array, but the caller's length is unchanged. Return the slice and assign it. See Pass by value.

2 — What does DeferDoubles return, and why? Important ​

Answer

Answer: 4. return 2 sets the named result n to 2, then the deferred closure runs and doubles it. See Named results and defer.

3 — In a module with go 1.21, what does a loop that appends func() { print(i) } for i := 0; i < 3; i++ print when the functions are run afterwards? And with go 1.22? Must-know ​

Answer

Answer: 3 3 3 with go 1.21 (one shared i, left at 3); 0 1 2 with go 1.22 (one i per iteration). See Loop variables.

4 — Why can Sum(xs...) modify xs[0] when Sum(xs[0], xs[1]) cannot? Important ​

Answer

Answer: With xs... the slice is passed unchanged, sharing its array. Separate arguments create a new slice for the call. See Variadic functions.

5 — How do you turn a plain function into an http.Handler? Must-know ​

Answer

Answer: Convert it with http.HandlerFunc(f). HandlerFunc is a function type with a ServeHTTP method that calls the function, an adapter. See Function types.

6 — A closure returned by Counter() outlives the call. Where does its n live? Important ​

Answer

Answer: On the heap; the compiler reports moved to heap: n. Each call to Counter creates a new n. See Closures and Inlining and escape analysis.

7 — Does Go optimise tail recursion? What happens at a billion levels? Good to know ​

Answer

Answer: No. Each call uses a frame; the stack grows by copying until 1 GB on 64-bit, then fatal error: stack overflow, which cannot be recovered. See Recursion.

8 — What is the difference between g.Hello and Greeter.Hello? Important ​

Answer

Answer: g.Hello is a method value with the receiver already bound (a copy for value receivers); Greeter.Hello is a method expression, a function that takes the receiver as its first argument. See Method values and expressions.

9 — Why does vet miss a bad format string in logf(format string, args ...any) { fmt.Printf(format+"\n", args...) }? Good to know ​

Answer

Answer: The wrapper inference requires format to be forwarded unchanged. Concatenating breaks the pattern, so vet no longer treats logf as a printf wrapper. See go vet and printf wrappers.

10 — A goroutine panics. Can recover in main stop the crash? Must-know ​

Answer

Answer: No. A recover works only in a deferred function of the panicking goroutine. Otherwise the process prints panic: ... and exits with status 2. See init, defer in loops, goroutine panics.

Glossary ​

TermMeaning
FunctionA named or anonymous unit of code with parameters and results; also a value
ParameterA local variable initialised from an argument
ArgumentThe value supplied at the call site
Pass by valueThe callee receives a copy of each argument
Pointer parameterA parameter of type *T; the copy points at the caller's data
Slice headerThe (pointer, length, capacity) triple copied when a slice is passed
Multiple return valuesA function returning more than one result
Comma-ok idiomv, ok := m[k] style second boolean result
Named resultsResults declared with names; usable by defer and naked return
Naked returnreturn with no values in a function with named results
Variadic functionA function whose last parameter is ...T
Spread operatorThe trailing ... that passes a slice as the variadic argument
Function literalAn anonymous function expression
ClosureA function value together with the variables it captured
Captured variableA variable from an enclosing scope used inside a function literal
GeneratorA function returning a function that yields the next value on each call
Iterator (iter.Seq)A function that calls yield for each value; drives for range since Go 1.23
MemoisationCaching a function's results by argument
Function typeA type such as func(string) error, optionally named
HandlerFuncThe net/http function type that adapts a function to http.Handler
Method on func typeA method declared on a named function type
AdapterA conversion that makes one shape satisfy another interface
Higher-order functionA function that takes or returns functions
MiddlewareA function of type func(Handler) Handler
Functional optionsConstructor pattern with variadic option functions
Method valuex.M, a function with receiver x already bound
Method expressionT.M, a function taking the receiver as first argument
RecursionA function calling itself
Tail callA call that is the last action of a function; not optimised by gc
Stack growthRuntime copying a goroutine stack to a larger one when full
Stack overflowFatal error when the stack exceeds its limit (1 GB on 64-bit)
InliningThe compiler pasting a small function body into its caller
Escape analysisThe compiler deciding stack or heap placement for a variable
-gcflags=-mBuild flag printing inlining and escape decisions
deferSchedules a call to run when the surrounding function returns
init functionA package-level func init() run before main
Callable (PHP)A PHP pseudo-type for anything invocable
Arrow function (PHP)fn($x) => ..., capturing outer variables by value

References ​

Read for Go 1.24 to 1.27 behaviour; the spec and docs pages were fetched and saved on 2026-11-26.

Built by Morteza Negahi