title: How to pass a copy of a slice to a function?
body: <p>I have a doubt about passing slices to functions. </p>
  
  <p>If I'm not wrong the slices are passed by reference in Go, so if I do something like this:</p>
  
  <pre><code>package main
  
  import "fmt"
  
  func main() {
      slice := []int{1, 2, 3, 4, 5}
      fmt.Println(slice)
      testSlice(slice)
      fmt.Println(slice)
  }
  
  func testSlice(slice []int) {
      slice[0] = 5
      slice[4] = 1
  }
  </code></pre>
  
  <p>The <code>testSlice</code> function will actually change the values in the original slice, because it was passed by reference (by default).</p>
  
  <p>There is some easy way that I can directly pass a copy of the slice to the <code>testSlice</code> function?</p>
  
  <p>Sure I can do something like this to create a copy of the slice:</p>
  
  <pre><code>package main
  
  import "fmt"
  
  func main() {
      slice := []int{1, 2, 3, 4, 5}
      fmt.Println(slice)
      testSlice(slice)
      fmt.Println(slice)
  }
  
  func testSlice(slice []int) {
      var newSlice []int
      for i := 0; i &lt; len(slice); i++ {
          newSlice = append(newSlice, slice[i])
      }
      newSlice[0] = 5
      newSlice[4] = 1
  }
  </code></pre>
  
  <p>But it needs to go through all values in the original slice to copy each of them, and it doesn't seem to be a great solution.</p>