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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.