The Shared Slice Backing Array Gotcha in Go

The shared slice backing array occurs when a slice is created from a larger array (like a buffer) and modified, causing changes to reflect in the original array because they share the same underlying memory.

The Shared Slice Backing Array Gotcha in Go

The shared slice backing array occurs when a slice is created from a larger array (like a buffer) and modified, causing changes to reflect in the original array because they share the same underlying memory.

package main

import "fmt"

func main() {
	// Original buffer
	buf := make([]byte, 10)
	buf[0] = 'A'

	// Slice sharing the same backing array
	slice := buf[0:5]
	slice[0] = 'B'

	// buf[0] is now 'B' because slice and buf share memory
	fmt.Println(buf[0]) // Output: B

	// Fix: Copy the data to a new backing array
	safeSlice := make([]byte, len(slice))
	copy(safeSlice, slice)
	safeSlice[0] = 'C'

	// buf[0] remains 'B', safeSlice[0] is 'C'
	fmt.Println(buf[0]) // Output: B
	fmt.Println(safeSlice[0]) // Output: C
}