Skip to content

no-defer-in-loop

Avoid accumulating deferred calls across loop iterations.

Updated View as Markdown

Default severity: warning

Configuration: severity and path excludes

Reports defer statements nested inside for or range loops. Deferred calls run when the surrounding function returns, not when the current iteration ends, so resources can accumulate for the entire loop.

Bad

for _, filename := range filenames {
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer file.Close()
}

Good

for _, filename := range filenames {
	if err := processFile(filename); err != nil {
		return err
	}
}

func processFile(filename string) error {
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer file.Close()
	return consume(file)
}

A defer inside a function literal declared within the loop is not reported: that defer belongs to the nested function and runs when that invocation ends.

Suppress

//strider:ignore no-defer-in-loop
for range smallFixedSet {
	defer releaseAtFunctionExit()
}
Navigation

Type to search…

↑↓ navigate↵ selectEsc close