IT lexicon › Programming › defer

defer

Programming På svenska → Updated: 2026-07-30

Language feature: defer execution of an expression until the enclosing function returns. Guarantees cleanup regardless of early returns or panics. Go original (2009), Zig and Swift also have it. Replacement for try-finally / RAII.

Classic Go: defer file.Close() right after file, _ := os.Open(...) — close will always happen, even on error-return mid-function. Multiple defers run in LIFO order (stack-based). Common trap: defer file.Close() inside a loop — closes accumulate until function exit, file handles leak. Fix with an inner function. Swift: defer { cleanup() } similar. Zig: defer + errdefer (runs only on error-return). Modern resource-management pattern — read as "Java try-finally with syntactic sugar".

← Back to the lexicon