---
title: "no-defer-in-loop"
description: "Avoid accumulating deferred calls across loop iterations."
image: "https://strider.gempir.com/og.png"
---

> Documentation Index
> Fetch the complete documentation index at: https://strider.gempir.com/llms.txt
> Use this file to discover all available pages before exploring further.

# no-defer-in-loop

**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

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

## Good

```go
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

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

Source: https://strider.gempir.com/lints/no-defer-in-loop/index.mdx
