Skip to content
Sword

defer

defer runs a statement when the block it sits in ends — the block, not the function:

import "std/io"
func main() !int {
try io.Print("a")
{
defer io.Print("c") catch {}
try io.Print("b")
}
try io.Print("d\n")
return 0
}

That prints abcd. Block scope is what makes defer inside a loop do the obvious thing — release once per iteration, instead of piling up until the function returns.

errdefer is the same, but only on the way out through an error. It is how you undo half of something:

buf := try alloc(a, size)
errdefer a.release(buf, size)
try fill(buf)
return buf

Within a scope, deferred statements run in reverse order, and defer and errdefer share that order.