Immediate Argument Evaluation in defer in Golang #6269
Answered
by
alexandear
novahe
asked this question in
Linter Ideas
-
Welcome
How did you install golangci-lint?N/A Your feature request related to a problem? Please describeI'm not sure if golangci-lint can catch this, thanks in advance. in Go, arguments to deferred function calls are evaluated immediately package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
// --- 1. ❌ INCORRECT WAY: Immediate Argument Evaluation ---
// The function time.Since(start) is an ARGUMENT to fmt.Println.
// Go's defer rule states that arguments are evaluated IMMEDIATELY
// when the defer statement is executed.
// Result: Reports a time duration close to zero.
defer fmt.Println("❌ Incorrect Value (Immediate Evaluation):", time.Since(start))
// --- 2. ✅ CORRECT WAY: Using a Closure/Anonymous Function ---
// The deferred function is now the anonymous function itself (func() {}).
// The code inside the closure (time.Since(start)) is NOT evaluated
// until the function exits and the deferred call is actually made.
// Result: Reports the true duration of the main function's execution.
defer func() {
fmt.Println("✅ Correct Value (Delayed Evaluation):", time.Since(start))
}()
fmt.Println("Main function execution STARTING...")
// Simulate a time-consuming operation (e.g., an HTTP request or database query)
time.Sleep(100 * time.Millisecond)
fmt.Println("Main function execution FINISHED.")
// When the function exits, deferred statements are executed (LIFO).
}Describe the solution you'd likeN/A Describe alternatives you've consideredN/A Additional contextNo response Supporter
|
Beta Was this translation helpful? Give feedback.
Answered by
alexandear
Dec 15, 2025
Replies: 1 comment
-
|
The $ golangci-lint run --enable-only govet
issue6268/main.go:16:67: defers: call to time.Since is not deferred (govet)
defer fmt.Println("❌ Incorrect Value (Immediate Evaluation):", time.Since(start))
^
1 issues:
* govet: 1 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
alexandear
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
govet(defersanalyzer) caught this: