Defer In Loops Delays Cleanup

See why defer inside a loop holds every resource until the function returns, and how extracting the iteration body closes each file on schedule.

GoResilience

Code

gosnippet
55 lines
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

// openAllLeaky defers inside the loop: every file closes only when the function returns,
// so open descriptors keep accumulating for the whole loop
func openAllLeaky(dir string, names []string) {
	for _, name := range names {
		f, err := os.Open(filepath.Join(dir, name))
		if err != nil {
			continue
		}
		defer f.Close() // bound to the function, not to this iteration
		fmt.Println("leaky opened:", name)
	}
	// after the loop ends and before the function returns, the files are still open
}

// openAllFixed extracts the loop body into a function: each defer runs right away
func openAllFixed(dir string, names []string) {
	for _, name := range names {
		func() {
			f, err := os.Open(filepath.Join(dir, name))
			if err != nil {
				return
			}
			defer f.Close() // the body's own function scope: closed as soon as this iteration ends
			fmt.Println("fixed opened:", name)
		}()
	}
}

func main() {
	dir, err := os.MkdirTemp("", "defer-loop-*")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)

	names := []string{"a.txt", "b.txt", "c.txt"}
	for _, name := range names {
		if err := os.WriteFile(filepath.Join(dir, name), []byte("x"), 0o644); err != nil {
			fmt.Println(err)
			return
		}
	}

	openAllLeaky(dir, names)
	openAllFixed(dir, names)
}

How it works

The code’s whole job belongs to the functions openAllLeaky, openAllFixed and main.

The one repetition in this snippet is the loop for _, name := range names. Error handling is inline: 4 places test err != nil and branch immediately. Cleanup is attached with defer, so it runs on every exit path of the function.

What to watch for

  • The import surface (if any) is all standard library, all versioned with the language itself.

Putting it to use

The one signature to know: func openAllLeaky(dir string, names []string)

Look for the leaky opened:, fixed opened: prefixes when the file runs; they tie each line to its step.

main calls 2 helpers in sequence: openAllLeaky and openAllFixed.

The core lines of the flow

func openAllFixed(dir string, names []string) {
for _, name := range names {
func() {
f, err := os.Open(filepath.Join(dir, name))
if err != nil {
return
}
defer f.Close() // the body's own function scope: closed as soon as this iteration ends
fmt.Println("fixed opened:", name)
}()
}
}
for _, name := range names {
f, err := os.Open(filepath.Join(dir, name))
if err != nil {
continue
}
defer f.Close() // bound to the function, not to this iteration
fmt.Println("leaky opened:", name)
}
for _, name := range names {
if err := os.WriteFile(filepath.Join(dir, name), []byte("x"), 0o644); err != nil {
fmt.Println(err)
return
}
}

Interactive Tools for This Topic

FAQ

What does Defer In Loops Delays Cleanup print when run?
Invoke the file as-is — the `leaky opened:`, `fixed opened:` prefixes identify which step printed each line.