Files
the-way-to-go_ZH_CN/eBook/12.7.md

21 lines
535 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 12.7 用 defer 关闭文件
`defer` 关键字(参看 6.4)对于在函数结束时关闭打开的文件非常有用,例如下面的代码片段:
```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()`
## 链接
- [目录](directory.md)
- 上一节:[用切片读写文件](12.6.md)
- 下一节:[使用接口的实际例子fmt.Fprintf](12.8.md)