← 中文资源

简体中文版本

循环里的 defer 会推迟清理

循环内 defer 把关闭推迟到整个函数返回,长循环会累积描述符;把迭代体抽成匿名函数,defer 就绑定到每轮作用域、立即释放。

阅读英文原文

实现说明

整个示例围绕函数 openAllLeaky、openAllFixed、main组织。 for _, name := range names 承担全部的逐项处理。没有静默穿透——中途有 4 个检查点测试 err != nil。入口处 defer、出口处执行:defer 让清理与获取紧挨着写。

使用要点

  • 直接运行文件,输出会带上标签,比如 leaky opened:、fixed opened:——输出的每一行都能指回产生它的那次调用。
  • main 的演示流程是 openAllLeaky、openAllFixed——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「循环里的 defer 会推迟清理」会打印什么?

运行文件本身,leaky opened:、fixed opened: 这些前缀各对应一段演示逻辑。

入口签名:func openAllLeaky(dir string, names []string)

核心语句

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

代码示例

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)
}