Defer Arguments Evaluate At Defer Time

Deferred call arguments are evaluated when the defer statement runs, while a deferred closure reads the variable's latest value.

GoData Integrity

Code

gosnippet
16 lines
package main

import "fmt"

func main() {
	progress := 0

	// defer arguments are evaluated at defer time, not at call time:
	// fmt.Println receives a copy of progress as it is right here
	defer fmt.Println("deferred progress:", progress)
	// a deferred closure reads the variable's latest value instead
	defer func() { fmt.Println("closure progress:", progress) }()

	progress = 100
	fmt.Println("current progress:", progress)
}

How the snippet works

The snippet is organized around the function main.

Cleanup is attached with defer, so it runs on every exit path of the function.

Watch out for

  • No third-party packages are used — the runtime ships every API called here.

Putting it to use

Entry signature: func main()

The file’s steps are announced right in the output: deferred progress:, closure progress:, current progress:.

The core lines of the flow

progress = 100

Interactive Tools for This Topic

FAQ

What does Defer Arguments Evaluate At Defer Time print when run?
The script runs standalone; its 3 labeled outputs include `deferred progress:`, `closure progress:`, `current progress:`.