Why does a
remain the same? Does append()
generate a new slice?
package main
import (
"fmt"
)
var a = make([]int, 7, 8)
func Test(slice []int) {
slice = append(slice, 100)
fmt.Println(slice)
}
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(a)
fmt.Println(a)
}
Typical
append
usage isbecause
append
may either modify its argument in-place or return a copy of its argument with an additional entry, depending on the size and capacity of its input. Using a slice that was previously appended to may give unexpected results, e.g.may print
Here is a nice implementation of append for slices. I guess its similar to what is going on under the hood:
More details see https://allegro.tech/2017/07/golang-slices-gotcha.html