I am just learning Go and I have a doubt about passing slices
to functions.
If I'm not wrong the slices
are passed by reference in Go, so if I do something like this:
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
}
The testSlice
function will actually change the values in the original slice
, because it was passed by reference (by default).
There is some easy way that I can directly pass a copy of the slice
to the testSlice
function?
Sure I can do something like this to create a copy of the slice
:
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 < len(slice); i++ {
newSlice = append(newSlice, slice[i])
}
newSlice[0] = 5
newSlice[4] = 1
}
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.