mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 06:19:44 +08:00
完成12.7章节
This commit is contained in:
21
eBook/12.7.md
Normal file
21
eBook/12.7.md
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
# 用defer关闭文件
|
||||||
|
|
||||||
|
`defer`关键字(参看6.4)对于在函数结束时关闭打开的文件非常有用,例如下面的代码片段:
|
||||||
|
|
||||||
|
```go
|
||||||
|
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()`
|
||||||
|
|
||||||
|
|
||||||
|
## 链接
|
||||||
|
|
||||||
|
- [目录](directory.md)
|
||||||
|
- 上一节:[用切片读写文件](12.6.md)
|
||||||
|
- 下一节:[一个使用接口的实际例子:fmt.Fprintf](12.8.md)
|
Reference in New Issue
Block a user