Go defer in Loops: Close Files per Iteration with a Helper Function
Reproduce file descriptor accumulation caused by defer inside Go loops. Use a per-file helper to finish cleanup before the next iteration and preserve read and close errors.
In a Go loop that processes files sequentially, defer f.Close() does not close each file at the end of its iteration. Put each file's work in a separate function and register the defer there to finish cleanup before opening the next file. This article counts real Linux file descriptors to compare the two structures and provides an implementation that preserves both read and close errors.
Conceptual illustration contrasting files held open until a function returns with files closed after per-file processing; not a measured chart.
Written and documentation checked: December 3, 2026. Execution environment: Go 1.24.7, Linux/amd64. The example requires Go 1.20 or later for errors.Join; its observation code requires Linux with /proc/self/fd. These results do not represent a run on the latest Go release.
The function outlives the loop iteration
If a small input works but a larger batch fails to open files with too many open files, check when Close executes, as well as whether the call exists. Finishing work on the contents does not mean the file handle has been closed.
The Go specification's defer rules place execution immediately before the enclosing function returns. Reaching a loop's closing brace or using continue does not return from that function. Deferred calls run in reverse registration order.
The badBatch below cleans up on return, so it does not permanently lose track of its files. The problem is that completed files stay open while the batch runs. The key is to match resource lifetime to the unit of work.
| Structure | When a successfully opened file closes | Sequential processing consideration |
| Defer inside the outer batch function's loop | Just before the batch function returns | Completed files remain open until the batch ends |
| Defer inside a per-file function | Just before that file's function returns | Cleanup finishes before the next iteration |
| Explicit Close in the loop | At the written call site | Early return and continue paths must also close the file |
Keep opening, use, and cleanup within one call
readOne keeps ownership of the file inside the function. It registers cleanup only after opening succeeds, then closes the file during return whether reading succeeds or fails. The caller receives the final error rather than a file handle.
The named result lets the deferred function combine the read result with the close result. Under the errors.Join contract, two nil errors produce nil; otherwise the result wraps the errors that occurred. errors.Is can inspect the original errors. A plain defer f.Close() leaves the close call's returned error unchecked.
Save the following as defer-demo.go. It independently opens the same file four times, showing that handles can accumulate regardless of the number of distinct input paths. badBatch also collects close errors so that the comparison isolates cleanup timing.
Run it with:
check is test observation code. It reads the descriptor symlinks described in the Linux proc_pid_fd documentation, counting only entries pointing to this temporary file's absolute path. It does not count the process's total descriptors, so standard I/O and runtime descriptors do not affect the result. It skips entries that disappeared after listing the directory; other observation errors and unexpected counts cause a panic.
Observed results: accumulation before return and cleanup on errors
On Go 1.24.7 Linux/amd64, the program exited with code 0 and printed:
The first four lines show one additional file descriptor remaining open after each iteration. The zero in bad returned shows that deferred cleanup ran during the batch's return. In the corrected sequential loop, the count is already zero immediately after each readOne call. This observation is not a throughput benchmark.
The error paths are separate checks. An empty file opens successfully but produces EOF when reading one byte. The program verifies that the descriptor count is zero afterward and that errors.Is finds EOF. A missing file returns during opening, with the not-exist classification preserved. No actual Close failure was injected or reproduced, so this does not validate behavior on storage that fails during close.
This run did not lower the descriptor limit or trigger EMFILE. It opened only four files to check the lifetime difference. Other files and sockets share the limit in a real server, so this output cannot determine a safe batch size.
Ownership transfer and concurrency need separate decisions
This structure fits sequential work that opens a file and fully consumes it within the function. If the caller needs a returned file handle or a reader dependent on that file, a helper that closes it just before returning is wrong. The call contract must state who finishes using and closes it. The os.File.Close documentation explains that a closed file is unusable for I/O and that closing it again returns an error.
Launching unbounded goroutines for per-file functions can still open many files at once, even when each function cleans up correctly. That requires a separate concurrency bound, such as a worker limit. This verification covered sequential processing and did not measure concurrent load.
For writes, handle buffered Flush errors separately as well. Do not assume closing alone guarantees buffered writes or storage durability. The example's one-byte io.ReadFull operation is minimal work for reproducing lifetime behavior; it does not validate a real parser or TTS input processor.
Adding another brace-delimited block inside the loop does not create a function boundary. An immediately invoked anonymous function can replace the named helper, but deferring that invocation again delays the per-file work. The review criterion is simple: have both use and cleanup of the current resource finished before the next job starts?