...
Slices and maps contain pointers to the underlying data so beĀ conscious of ownership when passing them as parameters or returning them as values.
On the other hand, do not unnecessarily copy slices - heap allocations are expensive and we want to avoid them when possible.
...
Bad | Good |
---|
Code Block |
---|
| func myFunc() error {
// do some work...
p.Lock()
if err := somethingThatCanPanic(); err != nil {
p.Unlock()
return err
}
p.Unlock()
// do some more work...
return nil
}
// if somethingThatCanPanic() panics, the mutex will be left locked. |
| Code Block |
---|
| func myFunc() error {
// do some work...
myFuncdoWork := func() error {
p.Lock()
defer p.Unlock()
return somethingThatCanPanic()
}
if err := myFuncdoWork(); err != nil {
return err
}
// do some more work...
return nil
}
// enables us to continue use defer without leaving the mutex locked longer than necessary. |
|
...