A defer inside a loop runs only when the function returns
What it finds
A defer inside the body of a for loop runs when the function returns, not at the end of the iteration, so resources pile up until the loop is done: open files, held locks, pending calls.
A defer in a function literal inside the loop runs when that literal returns and is fine. So is a defer after which the iteration always leaves the loop, by return or break, since it runs at most once. One that runs once for another reason, such as a guard for lazy initialization, is still reported, and some loops defer on purpose, such as one that takes a lock for each element and holds all of them, so the rule is recommended rather than on by default.
From the rule's source, defer_in_loop.rs.
package p import ( "os" "sync") func process(paths []string, mu *sync.Mutex) error { for _, path := range paths { f, err := os.Open(path) if err != nil { return err } defer f.Close()tx0 reports: this defer runs when the function returns, not after each iteration } for _, path := range paths { func() { f, _ := os.Open(path) defer f.Close() }() } for i := 0; i < len(paths); i++ { if paths[i] == "" { mu.Lock() defer mu.Unlock()tx0 reports: not after each iteration continue } switch paths[i] { case "first": mu.Lock() defer mu.Unlock() return nil case "second": defer mu.Unlock()tx0 reports: not after each iteration break } }outer: for { select { default: defer mu.Unlock() break outer } } for _, path := range paths { f, err := os.Open(path) if err != nil { continue } defer f.Close() if path == "" { return nil } else { panic(path) } } for _, path := range paths { if path != "" { mu.Lock() defer mu.Unlock() } return nil } for _, path := range paths { if path != "" { defer mu.Unlock()tx0 reports: not after each iteration } if path == "skip" { continue } return nil } defer mu.Unlock() return nil} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/go:defer-in-loop" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/go:defer-in-loop] reason="..."tx0 explain tx0/go:defer-in-loop shows the same in the terminal. Found a false positive? Report it.