title: Using a mutex within a struct in Go
body: <p>I see in <a href="https://www.programming-books.io/essential/go/" rel="nofollow noreferrer">Essential Go</a> that using a mutex within a struct is not too straight-forward. To quote from the <a href="https://www.programming-books.io/essential/go/mutex-gotchas-1c78058100ed4b45aab9461f69c05ecd#3968befb-6d13-46b8-819c-459f9df67793" rel="nofollow noreferrer">Mutex Gotchas</a> page:</p>
  <blockquote>
  <p><strong>Don’t copy mutexes</strong></p>
  <p>A copy of <code>sync.Mutex</code> variable starts with the same state as original
  mutex but it is not the same mutex.</p>
  <p>It’s almost always a mistake to copy a <code>sync.Mutex</code> e.g. by passing it
  to another function or embedding it in a struct and making a copy of
  that struct.</p>
  <p>If you want to share a mutex variable, pass it as a pointer
  <code>*sync.Mutex</code>.</p>
  </blockquote>
  <p>I'm not quite sure I fully understand exactly what's written. I looked <a href="https://stackoverflow.com/questions/44949467/when-do-you-embed-mutex-in-struct-in-go">here</a> but still wasn't totally clear.</p>
  <p>Taking the Essential Go example of a <a href="https://www.codeeval.dev/gist/2f0f3ca37296cade012f22c52b28547a" rel="nofollow noreferrer">Set</a>, should I be using the mutex like this:</p>
  <pre><code>type StringSet struct {
      m map[string]struct{}
      mu            sync.RWMutex
  }
  </code></pre>
  <p>or like this?</p>
  <pre><code>type StringSet struct {
      m map[string]struct{}
      mu            *sync.RWMutex
  }
  </code></pre>
  <p>I tried both with the Delete() function within the example and they both work in the <a href="https://play.golang.org/p/xHP0tTh5FDz" rel="nofollow noreferrer">Playground</a>.</p>
  <pre><code>// Delete removes a string from the set
  func (s *StringSet) Delete(str string) {
      s.mu.Lock()
      defer s.mu.Unlock()
      delete(s.m, str)
  }
  </code></pre>
  <p>There will obviously be several instances of a 'Set', and hence each instance should have its own mutex. In such a case, is it preferable to use the mutex or a pointer to the mutex?</p>