|
|
|
|
|
by TheDong
499 days ago
|
|
> Only really a gotcha if you pass a slice into a function and expect to see modifications in that slice after the function completes. It's helpful to remember that Go passes by value, not reference. Slices are passed partly by value (the length), partly by reference (the data). func takeSlice(s []int) {
slices.Sort(s)
}
From your explanation, you would expect that to not mutate the slice passed in, but it does.This can have other quite confusing gotchas, like: func f(s []int) {
_ = append(s, 1)
}
func main() {
s := []int{1, 2, 3}
f(s[0:2])
fmt.Printf("%v\n", s)
}
I'm sure the output makes perfect intuitive sense https://go.dev/play/p/79gOzSStTp4 |
|
I can see why it trips up newcomers, but it feels pretty basic otherwise.