Array — fixed-length, value-type container whose length is part of its type. Slice — a flexible, dynamically-sized view into an underlying array.
Arrays are rarely used directly in Go because their fixed size makes them cumbersome for most tasks. However, they are useful as building blocks for slices and as keys in maps (since arrays are comparable).
1arr := [3]int{10, 20, 30} // compile-time size2arr2 := [3]int{10, 20, 30} // same type3arr3 := [4]int{1, 2, 3, 4} // different type4fmt.Println(arr == arr2) // true
Slices wrap an array with three components: a pointer to the first element, a length, and a capacity. This makes them efficient for passing to functions — you share the underlying data without copying.
1nums := []int{1, 2, 3, 4, 5}2sub := nums[1:3] // [2, 3] — shares backing array3sub[0] = 99 // modifies nums[1] too4fmt.Println(nums) // [1 99 3 4 5]56// append may or may not reallocate7nums = append(nums, 6)
When to use:
Common mistakes:
append always modifies the original slice — it may return a new pointer if capacity is exceeded.len(arr) == len(slice) to compare — they may have different backing arrays.