mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 05:33:04 +08:00
@@ -60,25 +60,33 @@ func f() {
|
||||
|
||||
关键字 defer 允许我们进行一些函数执行完成后的收尾工作,例如:
|
||||
|
||||
1. 关闭文件流:
|
||||
1. 关闭文件流 (详见 [第 12.2 节](12.2.md))
|
||||
|
||||
// open a file
|
||||
defer file.Close() (详见第 12.2 节)
|
||||
```go
|
||||
// open a file
|
||||
defer file.Close()
|
||||
```
|
||||
|
||||
2. 解锁一个加锁的资源
|
||||
2. 解锁一个加锁的资源 (详见 [第 9.3 节](09.3.md))
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock() (详见第 9.3 节)
|
||||
```go
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
```
|
||||
|
||||
3. 打印最终报告
|
||||
|
||||
printHeader()
|
||||
defer printFooter()
|
||||
```go
|
||||
printHeader()
|
||||
defer printFooter()
|
||||
```
|
||||
|
||||
4. 关闭数据库链接
|
||||
|
||||
// open a database connection
|
||||
defer disconnectFromDB()
|
||||
```go
|
||||
// open a database connection
|
||||
defer disconnectFromDB()
|
||||
```
|
||||
|
||||
合理使用 defer 语句能够使得代码更加简洁。
|
||||
|
||||
|
Reference in New Issue
Block a user