Zero-value Mutexes are Valid
The zero-value of sync.Mutex
and sync.RWMutex
is valid, so you almostnever need a pointer to a mutex.
Bad | Good |
---|
- mu := new(sync.Mutex)
- mu.Lock()
|
- var mu sync.Mutex
- mu.Lock()
|
If you use a struct by pointer, then the mutex can be a non-pointer field.
Unexported structs that use a mutex to protect fields of the struct may embedthe mutex.
- type smap struct {
- sync.Mutex // only for unexported types
-
- data map[string]string
- }
-
- func newSMap() smap {
- return &smap{
- data: make(map[string]string),
- }
- }
- func (m smap) Get(k string) string {
- m.Lock()
- defer m.Unlock()
-
- return m.data[k]
- }
|
- type SMap struct {
- mu sync.Mutex
-
- data map[string]string
- }
-
- func NewSMap() SMap {
- return &SMap{
- data: make(map[string]string),
- }
- }
- func (m SMap) Get(k string) string {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- return m.data[k]
- }
|
Embed for private types or types that need to implement the Mutex interface. | For exported types, use a private field. |