How do I understand how slicing affects underlying arrays in Go?

Understanding how slicing affects underlying arrays in Go is crucial for efficient memory management and data manipulation. In Go, slices are built on top of arrays, and they reference the same underlying data. This means that changes made to the elements of a slice will reflect in the underlying array and vice versa. Here's a deeper look into how it works.

Example

package main import "fmt" func main() { // Create an array arr := [5]int{1, 2, 3, 4, 5} // Create a slice from the array slice := arr[1:4] // Slice includes elements 2, 3, and 4 // Modify the slice slice[0] = 99 // Sets the first element of the slice (2) to 99 // Print the updated slice and array fmt.Println("Slice:", slice) // Output: Slice: [99 3 4] fmt.Println("Array:", arr) // Output: Array: [1 99 3 4 5] }

Go Slicing Arrays Memory Management Data Manipulation Programming Basics