title: Using Pointers in a for loop
body: <p>I'm struggling to understand why I have a bug in my code in one state but not the other. It's been a while since I've covered pointers, so I'm probably rusty!</p>
  
  <p>Basically I have a repository structure I'm using to store an object in memory, that has a <code>Store</code> function.</p>
  
  <pre><code>type chartsRepository struct {
      mtx    sync.RWMutex
      charts map[ChartName]*Chart
  }
  
  func (r *chartsRepository) Store(c *Chart) error {
      r.mtx.Lock()
      defer r.mtx.Unlock()
      r.charts[c.Name] = c
      return nil
  }
  </code></pre>
  
  <p>So all it does is put a RW mutex lock on and adds the pointer to a map, referenced by an identifier.</p>
  
  <p>Then I've got a function that will basically loop through a slice of these objects, storing them all in the repository.</p>
  
  <pre><code>type service struct {
      charts Repository
  }
  
  func (svc *service) StoreCharts(arr []Chart) error {
      hasError := false
      for _, chart := range arr {
          err := svc.repo.Store(&amp;chart)
          // ... error handling
      }
      if hasError {
          // ... Deals with the error object
          return me
      }
      return nil
  }
  </code></pre>
  
  <p>The above doesn't work, it looks like everything works fine at first, but on trying to access the data later, the entries in the map all point to the same <code>Chart</code> object, despite having different keys.</p>
  
  <p>If I do the following and move the pointer reference to another function, everything works as expected:</p>
  
  <pre><code>func (svc *service) StoreCharts(arr []Chart) error {
      // ...
      for _, chart := range arr {
          err := svc.storeChart(chart)
      }
      // ...
  }
  
  func (svc *service) storeChart(c Chart) error {
      return svc.charts.Store(&amp;c)
  }
  </code></pre>
  
  <p>I'm assuming the issue is that because the loop overwrites the reference to the <code>chart</code> in the <code>for</code> loop, the pointer reference also changes. When the pointer is generated in an independent function, that reference is never overwritten. Is that right?</p>
  
  <p>I feel like I'm being stupid, but shouldn't the pointer be generated by <code>&amp;chart</code> and that's independent of the <code>chart</code> reference? I also tried creating a new variable for the pointer <code>p := &amp;chart</code> in the <code>for</code> loop and that didn't work either.</p>
  
  <p>Should I just avoid generating pointers in loops?</p>