mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 03:34:15 +08:00
add new section
This commit is contained in:
37
eBook/16.3.md
Normal file
37
eBook/16.3.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# 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)
|
Reference in New Issue
Block a user