Sobes.tech
Junior

What is the key difference between slices and arrays in Go?

sobes.tech AI

Answer from AI

Slices are dynamically resizable views of arrays.

Characteristic Array Slice
Size Fixed, determined at creation Dynamic, can change
Type [n]T (where n is size, T is type) []T (where T is type)
Passing to functions By value (copy) By reference to underlying array, passing head, len, and cap (effectively, a new SliceHeader structure with copies of these fields)
Creation var a [5]int or b := [3]string{"a", "b", "c"} var s []int or t := []int{1, 2, 3} or u := make([]int, 5)
Performance More predictable due to fixed size, may perform better with small sizes May have overhead when resizing (reallocating underlying array)
// Array example
var arr [3]int = [3]int{1, 2, 3}

// Slice example created from array
slice := arr[1:] // slice {2, 3}

// Creating a slice
s := []int{10, 20, 30} // underlying array {10, 20, 30}, len = 3, cap = 3

// Modifying the slice
s = append(s, 40) // now s {10, 20, 30, 40}. If capacity is exceeded, a new underlying array is created, len = 4, cap = 6 (usually doubling the capacity).

// Modifying an element of the slice changes the underlying array
slice[0] = 99 // arr now {1, 99, 3}
fmt.Println(arr)