Inspect closure environments and struct layout
Inspect closure environments and struct layout
A closure is a function that can access variables from its enclosing scope. In the Go 1.23 implementation a function value may refer to a code entry and captured environment; compiler escape analysis decides how captures are stored. Captured variables can remain live after the enclosing function returns. A struct, meanwhile, stores fields with alignment and possible padding. Use unsafe.Sizeof, Alignof and Offsetof to inspect your own typed values, without assuming these numbers are a serialization format.
package main
import ( "fmt")
func counter(start int) func() int { return func() int { start++; return start } }func main() { a, b := counter(0), counter(10) fmt.Println(a(), a(), b()) c := a fmt.Println(c(), a())}Each counter call creates its own captured variable; copying a function value does not create an independent captured variable. Mutating a shared capture from multiple goroutines requires synchronization. The compiler may optimize the environment, so do not equate every closure with a heap allocation. Use go build -gcflags=-m for version-specific diagnostics.
Expected output:
1 2 113 4Measure alignment without hard-coded offsets
package main
import ( "fmt" "unsafe")
type Record struct { A byte B uint64 C byte}type Compact struct { B uint64 A, C byte}
func main() { var x Record var y Compact fmt.Println(unsafe.Offsetof(x.B)%unsafe.Alignof(x.B) == 0, unsafe.Sizeof(x) >= unsafe.Sizeof(y)) fmt.Println(unsafe.Sizeof(x)%unsafe.Alignof(x) == 0)}Field order can affect padding. On amd64 these particular layouts are typically 24 and 16 bytes, while on 386 alignment differs. The program checks relationships rather than demanding those numbers. Reordering fields may affect unkeyed literals, ABI assumptions and reflection-based consumers; measure before changing a public type. For serialized data specify fields and byte order explicitly.
Expected output:
true truetrueTry it locally
Build two independent accumulators that add a supplied delta to a private total. Start them at 5 and 20, add 3 and -2 to the first, and add 1 to the second.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime representations 04: Inspect closure environments and struct layout
Check the lesson objective before moving on.
What happens when you copy a closure value that captures a mutable variable?
Why avoid using raw struct bytes as a network format?