title: Initializing map elements, where value is a struct with mutex lock golang
body: <p>I have a map where every value is a pointer to another struct that itself has a lock. </p>
  
  <pre><code>type StatMap map[string]*Stats
  
  type Stats struct {
      sync.RWMutex
      someStats, someMoreStats float64
  }
  </code></pre>
  
  <p>I have implemented a method where I pack the StatMap into another struct and have a Mutex lock for the entire map, but I am expecting to modify every entry in the map simoultaniously from hundreds of goroutines, so it would be more effective to lock every element in the map so that two or more goroutines can read and modify values for entries in parallell.</p>
  
  <p>What I am wondering is how I can initialize a new entry in the map whenever there comes a new key? I cannot lock the entry if it isn't in the map already, and I cannot check if it is in the map (as far as I know) in case another goroutine is currently modifying that entry. </p>
  
  <p>I do not know what keys will be in the map before runtime. </p>
  
  <p>My current implementation (that causes data races):</p>
  
  <pre><code>initializeStatMap("key")
  statMap["key"].Lock()
  // . . . 
  
  
  func initializeStatMap(key string) {
      if statMap[key] != nil {
          return
      }
      statMap[key] = &amp;Stats{someStats: 0, someMoreStats: 0}
  }
  </code></pre>