snapshot of https://github.com/uber-go/guide.git (master, 2026-09-15; blobs > 131072B omitted)
This commit is contained in:
49
src/defer-clean.md
Normal file
49
src/defer-clean.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# Defer to Clean Up
|
||||
|
||||
Use defer to clean up resources such as files and locks.
|
||||
|
||||
<table>
|
||||
<thead><tr><th>Bad</th><th>Good</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>
|
||||
|
||||
```go
|
||||
p.Lock()
|
||||
if p.count < 10 {
|
||||
p.Unlock()
|
||||
return p.count
|
||||
}
|
||||
|
||||
p.count++
|
||||
newCount := p.count
|
||||
p.Unlock()
|
||||
|
||||
return newCount
|
||||
|
||||
// easy to miss unlocks due to multiple returns
|
||||
```
|
||||
|
||||
</td><td>
|
||||
|
||||
```go
|
||||
p.Lock()
|
||||
defer p.Unlock()
|
||||
|
||||
if p.count < 10 {
|
||||
return p.count
|
||||
}
|
||||
|
||||
p.count++
|
||||
return p.count
|
||||
|
||||
// more readable
|
||||
```
|
||||
|
||||
</td></tr>
|
||||
</tbody></table>
|
||||
|
||||
Defer has an extremely small overhead and should be avoided only if you can
|
||||
prove that your function execution time is in the order of nanoseconds. The
|
||||
readability win of using defers is worth the miniscule cost of using them. This
|
||||
is especially true for larger methods that have more than simple memory
|
||||
accesses, where the other computations are more significant than the `defer`.
|
||||
Reference in New Issue
Block a user