Why This Happens
The defer statement schedules a function call to run when the surrounding function returns, not when the loop iteration ends. If you open files or connections in a loop and defer their close, all resources stay open until the function exits. This can exhaust file descriptors or connections.
The Problem
func processFiles(paths []string) error {
for _, path := range paths {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close() // all files stay open until function returns
// process f
}
return nil
}The Fix
func processFiles(paths []string) error {
for _, path := range paths {
if err := processOneFile(path); err != nil {
return err
}
}
return nil
}
func processOneFile(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close() // closes at end of this function
// process f
return nil
}Step-by-Step Fix
- 1
Identify the defer in loop
Find the defer call inside a for loop that opens resources.
- 2
Extract to a function
Move the loop body into a separate function so defer runs at the end of each iteration.
- 3
Verify resource cleanup
Test that resources are properly closed after each iteration, not accumulated.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free