Files
the-way-to-go_ZH_CN/eBook/17.2.md
yusuf b242141e22 更新14、15和17章目录 (#702)
* 更新14、15和17章目录

* Update README.md

* 添加章节序号

* 添加章节序号

* 添加代码链接

* 修改错别字

* 删除多余字符

* 修复代码与文件不对应的问题

* 修改代码
2019-08-01 21:16:20 -07:00

63 lines
1.3 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.

# 17.2 defer 模式
使用 `defer` 可以确保资源不再需要时,都会被恰当地关闭或归还到“池子”中。更重要的一点是,它可以恢复 panic。
1. 关闭一个文件流:(见 [12.7节](12.7.md)
```go
// 先打开一个文件 f
defer f.Close()
```
2. 解锁一个被锁定的资源(`mutex`):(见 [9.3节](09.3.md)
```go
mu.Lock()
defer mu.Unlock()
```
3. 关闭一个通道(如有必要):
```
ch := make(chan float64)
defer close(ch)
```
也可以是两个通道:
```go
answerα, answerβ := make(chan int), make(chan int)
defer func() { close(answerα); close(answerβ) }()
```
4. 从 panic 恢复:(见 [13.3节](13.3.md)
```go
defer func() {
if err := recover(); err != nil {
log.Printf("run time panic: %v", err)
}
}()
```
5. 停止一个计时器:(见 [14.5节](14.5.md)
```go
tick1 := time.NewTicker(updateInterval)
defer tick1.Stop()
```
6. 释放一个进程 p见 [13.6节](13.6.md)
```go
p, err := os.StartProcess(, , )
defer p.Release()
```
7. 停止 CPU 性能分析并立即写入:(见 [13.10节](13.10.md)
```go
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
```
当然 `defer` 也可以在打印报表时避免忘记输出页脚。
## 链接
- [目录](directory.md)
- 上一节:[逗号 ok 模式](17.1.md)
- 下一节:[可见性模式](17.3.md)