title: Go loop pointer changes
body: <p>I am using a <code>for range</code> loop in Go to iterate through a slice of structs.</p>
  
  <p>In each loop, I a pointer to the current item to a variable.</p>
  
  <p>I am confused why the pointer changes value in the next loop.</p>
  
  <p>For example <a href="http://play.golang.org/p/7Ruqt0pRB9" rel="nofollow">this code</a>:</p>
  
  <pre><code>package main
  
  import "fmt"
  
  type t struct {
      val int
  }
  
  func main() {
      l := []t{{1}, {2}}
      var p *t
      for _, i := range l {
          fmt.Println("begin", p)
          p = &amp;i
          fmt.Println("end", p)
      }
  }
  </code></pre>
  
  <p>I would expect to produce:</p>
  
  <pre><code>begin &lt;nil&gt;
  end &amp;{1}
  begin &amp;{1}
  end &amp;{2}
  </code></pre>
  
  <p>But actually does:</p>
  
  <pre><code>begin &lt;nil&gt;
  end &amp;{1}
  begin &amp;{2}
  end &amp;{2}
  </code></pre>
  
  <p>For reference, in my actual code, I am checking for a condition during the loop, and returning the current item and previous one. So I am trying to save a pointer to it, so that in the next iteration it will have access to the previous as well.</p>