title: Copying the address of a loop variable in Go
body: <p>In the following code sample, the result is not what I would expect:</p>
  
  <pre><code>package main
  
  import "fmt"
  
  func main() {
      src := map[int]int{1: 1, 2: 2, 3: 3}
      fmt.Println("src ", src)
  
      dst := make([]*int, 0, len(src))
      for k, _ := range src {
          dst = append(dst, &amp;k)
      }
      for _, a := range dst {
          fmt.Print(*a, " ")
      }
      fmt.Println()
  }
  </code></pre>
  
  <p>Result:</p>
  
  <pre><code>src map[1:1 2:2 3:3]
  3 3 3
  </code></pre>
  
  <p>Go Playground: <a href="https://play.golang.org/p/BSDsd3nojz" rel="nofollow noreferrer">https://play.golang.org/p/BSDsd3nojz</a></p>
  
  <p>but I understand what is happening. The unchanging address of <code>k</code> is being added to <code>dst</code>, so when I loop over <code>dst</code>, the same value is in every location: <code>3</code>.</p>
  
  <p>The address of <code>k</code> never changes in the loop, so the second loop keeps referring to that location, containing the last value it had, <code>3</code>.</p>
  
  <p>How can I get the address of the current value of <code>k</code> to be copied? Do I need something like this:</p>
  
  <pre><code>for k, _ := range src {
      key = new(int)
      *key = k
      dst = append(dst, key)
  }
  </code></pre>
  
  <p>That seems awkward.</p>