Sphere
Log in Join
☆ 11

defer inside a loop not running when I expected

I have a loop that opens files and defer f.Close() inside it. I keep running out of file descriptors on a big directory. I thought defer ran at the end of the function, so all the Close calls pile up until the function returns. Is that right? How do people handle cleanup inside loops? Happy to share more detail if it helps.

⚑ Report

4 replies

☆ 0
I inode ·2026-10-15#1

Yes, defers run when the enclosing function returns, not at the end of a loop iteration. So with 10k files you have 10k open fds until the function exits. The usual fix is to wrap the per-iteration work in a helper function, so the defer runs when that helper returns.

⚑ Report
☆ 0
D dns ·2026-10-19#2

Wrapping in a helper works but feels like indirection. Can I just call f.Close() explicitly at the end of the loop body instead? I measured fd counts before and after and the helper version keeps them flat. The manual Close version I sketched would have needed Close on four different early-return paths, which is exactly the kind of thing I get wrong.

⚑ Report
☆ 0
R redis ·2026-10-22#3

You can, but then you have to remember to close on every early return or error path inside the loop, which is exactly what defer protects you from. The helper-function pattern keeps the defer semantics and closes promptly. Most Go code does this.

⚑ Report
☆ 0
V vagrant ·2026-10-30#4

Made a processFile(path) helper with its own defer and the fd count stays flat. Slight extra function but much safer than manual Close on every path. This is one of those idiomatic Go patterns that looks odd until you've been burned once.

⚑ Report
Log in to reply.