Files
the-way-to-go_ZH_CN/eBook/12.7.md
2015-10-31 18:08:57 +08:00

515 B
Raw Blame History

用 defer 关闭文件

defer 关键字(参看 6.4)对于在函数结束时关闭打开的文件非常有用,例如下面的代码片段:

func data(name string) string {
	f := os.Open(name, os.O_RDONLY, 0)
	defer f.Close() // idiomatic Go code!
	contents := io.ReadAll(f)
	return contents
}

在函数 return 后执行了 f.Close()

链接