Files
the-way-to-go_ZH_CN/eBook/16.3.md
2016-03-23 22:48:26 +08:00

37 lines
1.0 KiB
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.

# 16.3 发生错误时使用defer关闭一个文件
如果你在一个for循环内部处理一系列文件你需要使用defer确保文件在处理完毕后被关闭例如
```go
for _, file := range files {
if f, err = os.Open(file); err != nil {
return
}
// 这是错误的方式,当循环结束时文件没有关闭
defer f.Close()
// 对文件进行操作
f.Process(data)
}
```
但是在循环结尾处的defer没有执行所以文件一直没有关闭垃圾回收机制可能会自动关闭文件但是这会产生一个错误更好的做法是
```go
for _, file := range files {
if f, err = os.Open(file); err != nil {
return
}
// 对文件进行操作
f.Process(data)
// 关闭文件
f.Close()
}
```
**defer仅在函数返回时才会执行在循环的结尾或其他一些有限范围的代码内不会执行。**
## 链接
- [目录](directory.md)
- 上一节:[误用字符串](16.2.md)
- 下一节:[何时使用new()和make()](16.4.md)