Defer

A defer statement defers the execution of a function until the surrounding function returns. The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.

import ( "io" "os" ) func CopyFile(dstName, srcName string) (written int64, err error) { src, err := os.open(srcName) if err != nil { return } defer src.close() dst, err := os.create(dstName) if err != nil { return } defer dst.close() return io.copy(dst, src) }

Defer statements allow us to think about closing each file right after opening it, guaranteeing that, regardless of the number of return statements in the function, the files will be closed.

Stacking defers

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

println("counting") for i := 0; i < 10; i++ { defer println(i) } println("done")

Next example: Exceptions