title: Concurrency-safe map of slices
body: <p>I have a type that contains a <code>sync.Map</code> where the key in the map is a string and the value is a slice. My code for inserting items into the map is as follows:</p>
  <pre><code>newList := []*Item{item}
  if result, ok := map.LoadOrStore(key, newList); ok {
      resultList := result.([]*Item)
      resultList = append(resultList, item)
      map.Store(key, resultList)
  }
  </code></pre>
  <p>This is not concurrency-safe because the the slice can be loaded and modified by multiple calls concurrently. This code is very fragile so I've attempted to modify it to be:</p>
  <pre><code>newList := []*Item{item}
  if result, ok := map.LoadOrStore(key, &amp;newList); ok {
      resultList := result.(*[]*Item)
      *resultList = append(*resultList, item)
  }
  </code></pre>
  <p>All this does is make the issues occur deterministically. So, I'm trying to find a way to have a map-of-slices that can be added to concurrently. My instinct is to use <code>sync.Mutex</code> to lock the list while I'm adding to it but in order to maintain the concurrent access to the <code>sync.Map</code> I would need to create a map of <code>sync.Mutex</code> objects as well, like this:</p>
  <pre><code>newLock := sync.Mutex{}
  raw, _ := lockMap.LoadOrStore(key, &amp;newLock)
  lock := raw.(*sync.Mutex)
  
  newList := []*Item{item}
  if result, ok := map.LoadOrStore(key, &amp;newList); ok {
      lock.Lock()
      resultList := result.(*[]*Item)
      *resultList = append(*resultList, item)
      lock.Unlock()
  }
  </code></pre>
  <p>Is there an easier way to go about this?</p>