Defer to Clean Up

Use defer to clean up resources such as files and locks.

BadGood
```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 ``` ```go p.Lock() defer p.Unlock() if p.count < 10 { return p.count } p.count++ return p.count // more readable ```

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.

© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:05:01

results matching ""

    No results matching ""

    results matching ""

      No results matching ""