Code-Memo

Function values and closures

Go has function types and anonymous functions (literals). A closure captures variables from its surrounding lexical scope.

Function type
type Op func(int, int) int

var add Op = func(a, b int) int { return a + b }
Anonymous function
fn := func(x int) int { return x * 2 }
_ = fn(3)
Immediate invocation
v := func(x int) int { return x + 1 }(41)
Closure capturing loop variable (classic pitfall)

Before Go 1.22, loop variables were reused; closures created in a loop often needed a local copy:

for _, id := range ids {
	id := id // copy for closure body
	go func() { use(id) }()
}

Since Go 1.22, each iteration has its own id in for loops — but understanding the capture model still matters for readability and older toolchains.

Higher-order functions
func mapInts(xs []int, f func(int) int) []int {
	out := make([]int, len(xs))
	for i, v := range xs {
		out[i] = f(v)
	}
	return out
}
Methods vs function values

Methods bind a receiver; function values are useful for callbacks, middleware, and dependency injection without frameworks.