Use go.uber.org/atomic

Atomic operations with the sync/atomic package operate on the raw types(int32, int64, etc.) so it is easy to forget to use the atomic operation toread or modify the variables.

go.uber.org/atomic adds type safety to these operations by hiding theunderlying type. Additionally, it includes a convenient atomic.Bool type.

BadGood
  1. type foo struct {
  2. running int32 // atomic
  3. }
  4.  
  5. func (f foo) start() {
  6. if atomic.SwapInt32(&f.running, 1) == 1 {
  7. // already running…
  8. return
  9. }
  10. // start the Foo
  11. }
  12. func (f foo) isRunning() bool {
  13. return f.running == 1 // race!
  14. }
  1. type foo struct {
  2. running atomic.Bool
  3. }
  4.  
  5. func (f foo) start() {
  6. if f.running.Swap(true) {
  7. // already running…
  8. return
  9. }
  10. // start the Foo
  11. }
  12. func (f foo) isRunning() bool {
  13. return f.running.Load()
  14. }