Today I learned (revisted after a long while) how to make a copy of a slice in Go using the in-built copy
function. The process is still cumbersome (compared to python) but that’s the trade-off you gotta make.
This is because slices in Go are passed by reference. That means you can’t copy by value using a := b
.
Instead, you have to do this
copyArr := make([]int, len(arr))
copy(copyArr, arr)
Perhaps, if you’re doing this enough number of times in your go program, it ought to be useful to just build a helper function and use that everytime.
func copyIntSlice(arr []int) []int {
copyArr := make([]int, len(arr))
copy(copyArr, arr)
return copyArr
}
If you want to make it data-type agnostic and you’re working with go1.18+, then you can use generics,
func copySlice[T any](arr []T) []T {
copyArr := make([]T, len(arr))
copy(copyArr, arr)
return copyArr
}
This trick could help programmers gain back a ton of time in dev-loops. Hope you found this helpful!
π βΈ» @TnvMadhav