go / intermediate
Snippet
Understanding Memory Sharing in Slice Headers
Slices in Go are passed by value, meaning the slice header (length, capacity, and pointer to backing array) is copied. Thus, modifying elements modifies the original array, but appending can trigger a reallocation or change local length, leaving the caller's slice length unmodified.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package mainimport "fmt"func updateValues(s []int) {s[0] = 42s = append(s, 99)fmt.Println("Inside function:", s)}func main() {original := []int{1, 2, 3}updateValues(original)fmt.Println("Outside function:", original)}
Breakdown
1
func updateValues(s []int) {
Receives a copy of the slice header, which points to the original backing array.
2
s[0] = 42
Mutates the original backing array through the copied pointer, affecting the caller.
3
s = append(s, 99)
Appends a new value, potentially reallocating or modifying length within the local copy only.