> For the complete documentation index, see [llms.txt](https://go.xiao5.info/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://go.xiao5.info/di-san-bu-fen-go-gao-ji-bian-cheng/12.0/12.7.md).

# 用 defer 关闭文件

`defer` 关键字（参看 [6.4](/di-er-bu-fen-yu-yan-de-he-xin-jie-gou-yu-ji-shu/06.0/06.4.md)）对于在函数结束时关闭打开的文件非常有用，例如下面的代码片段：

```go
func data(name string) string {
	f, _ := os.OpenFile(name, os.O_RDONLY, 0)
	defer f.Close() // idiomatic Go code!
	contents, _ := ioutil.ReadAll(f)
	return string(contents)
}
```

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

## 链接

* [目录](https://github.com/MartialBE/the-way-to-go_ZH_CN/blob/master/eBook/directory.md)
* 上一节：[用切片读写文件](/di-san-bu-fen-go-gao-ji-bian-cheng/12.0/12.6.md)
* 下一节：[使用接口的实际例子：fmt.Fprintf](/di-san-bu-fen-go-gao-ji-bian-cheng/12.0/12.8.md)
