Arrays and Slices
What you will learn
Arrays and slices both hold an ordered list of values of one type. You will use slices almost all the time, but arrays explain how slices work. This lesson covers creating, indexing, appending, slicing, copying, and looping, and ends with the one behaviour that surprises almost everyone: two slices can share the same underlying data.
Arrays have a fixed length
scores := [3]int{90, 82, 97}
fmt.Println(scores[0]) // 90
fmt.Println(len(scores)) // 3
scores[1] = 85
The length is part of the type, so [3]int and [4]int are different types, and an array can never grow. Indexes start at 0, and an index outside the array is a compile error for constants or a runtime panic otherwise.
An array is a value, like an int. Assigning it or passing it to a function copies every element:
a := [3]int{1, 2, 3}
b := a
b[0] = 99
fmt.Println(a, b) // [1 2 3] [99 2 3]
Because of the fixed length and the copying, arrays are used less often than slices. Reach for an array when the size is truly part of the problem, such as a 3-component colour or a fixed-size hash.
Slices are flexible
A slice looks like an array without the length:
names := []string{"Ada", "Linus", "Grace"}
names = append(names, "Rob")
fmt.Println(names) // [Ada Linus Grace Rob]
fmt.Println(len(names)) // 4
A slice has three pieces of information: where its elements are stored, its length (how many elements it currently has), and its capacity (how many it can hold before Go has to find more room). Conceptually:
names ──► [ "Ada" | "Linus" | "Grace" | "Rob" | _ | _ ]
len = 4 cap = 6
The elements live in an underlying array, and the slice is a small window onto it. This is why slices are cheap to pass around, and also why they can share data.
Creating slices
empty := []int{} // length 0
items := make([]string, 3) // length 3, capacity 3, filled with ""
queue := make([]string, 0, 10) // length 0, capacity 10
The second form is useful when you know roughly how many items you will add. Reserving capacity up front avoids repeated allocation while keeping the slice logically empty.
Growing with append
values := []int{1, 2, 3}
values = append(values, 4)
values = append(values, 5, 6)
values = append(values, []int{7, 8}...)
append adds one or more elements, and ... spreads another slice. Always assign the result back, because append may return a different slice. If the underlying array has room, Go reuses it. If not, Go allocates a bigger array, copies the elements across, and returns a slice that points to the new one. You can watch capacity grow:
var s []int
for i := 0; i < 5; i++ {
s = append(s, i)
fmt.Println(len(s), cap(s))
}
The capacity jumps in steps rather than by one each time (for example 1, 2, 4, 4, 8), though the exact numbers are an implementation detail you should not depend on.
Slicing a slice
slice[low:high] creates a new slice that includes low and excludes high:
numbers := []int{10, 20, 30, 40, 50}
fmt.Println(numbers[1:4]) // [20 30 40]
fmt.Println(numbers[:2]) // [10 20]
fmt.Println(numbers[3:]) // [40 50]
Leaving out low means "from the start" and leaving out high means "to the end".
The shared array trap
A slice created by slicing does not copy the data. It is another window onto the same underlying array:
numbers := []int{10, 20, 30, 40, 50}
middle := numbers[1:4]
middle[0] = 99
fmt.Println(numbers) // [10 99 30 40 50]
Changing middle[0] changed numbers, because both view the same storage. This is efficient, but it surprises people who expect a copy.
append can cause an even subtler version. If a slice has spare capacity, appending writes into the shared array and can overwrite data another slice still sees:
base := []int{1, 2, 3, 4}
part := base[:2] // [1 2], with capacity 4
part = append(part, 100)
fmt.Println(base) // [1 2 100 4], base was changed!
The rule is: if you need independence, make a copy.
Copying a slice
original := []int{1, 2, 3}
clone := make([]int, len(original))
copy(clone, original)
clone[0] = 99
fmt.Println(original) // [1 2 3]
fmt.Println(clone) // [99 2 3]
copy(destination, source) copies as many elements as fit and returns how many it copied. The destination must already have the right length.
The standard library's slices package offers a shorter route: clone := slices.Clone(original).
Looping with range
for index, value := range names {
fmt.Println(index, value)
}
for _, name := range names { // ignore the index
fmt.Println(name)
}
value is a copy of each element, so assigning to it does not change the slice. To modify elements, use the index: names[i] = strings.ToUpper(names[i]).
Useful helpers
The slices package (standard library, Go 1.21+) covers common jobs:
nums := []int{3, 1, 2}
slices.Sort(nums) // [1 2 3]
fmt.Println(slices.Contains(nums, 2)) // true
fmt.Println(slices.Index(nums, 3)) // 2
Removing an element does not need a special function in the language: slices.Delete(nums, 1, 2) removes index 1.
Nil and empty slices
var nilSlice []int // nil
emptySlice := []int{} // not nil, but empty
Both have length 0 and both work with append and range. They differ only when compared to nil, or when encoded as JSON (null versus []). Most code can treat them the same.
Common mistakes
- Not using
append's result. Writingappend(values, 4)alone does nothing useful. - Indexing out of range.
values[len(values)]panics withindex out of range. - Treating a subslice as a copy. Use
copyorslices.Clonewhen you need independence. - Keeping a tiny subslice of a huge slice. The whole underlying array stays in memory. Copy the part you need.
- Modifying
valuein arangeloop and expecting the slice to change.
Practice
Write a function evens(numbers []int) []int that returns a new slice containing only the even values from the input. The input slice must not be modified. Test it with []int{1, 2, 3, 4, 5, 6}.
package main
import "fmt"
func evens(numbers []int) []int {
result := make([]int, 0, len(numbers))
for _, n := range numbers {
if n%2 == 0 {
result = append(result, n)
}
}
return result
}
func main() {
input := []int{1, 2, 3, 4, 5, 6}
output := evens(input)
fmt.Println(input) // [1 2 3 4 5 6]
fmt.Println(output) // [2 4 6]
}
The function builds a brand-new slice, so the input is untouched. make([]int, 0, len(numbers)) starts with length 0 and enough capacity for the worst case, so append never has to reallocate. If you wrote return numbers[:3] instead, the result would share storage with the input, which is exactly the trap this lesson warns about.
Summary
An array has a fixed length that is part of its type, and it is copied when assigned. A slice is a flexible window onto an underlying array, with a length and a capacity. Use append and always keep its result, and remember that slicing a slice shares the same storage, so use copy or slices.Clone when you need independent data. range walks over slices, and value in the loop is a copy.
Official reference: Go Slices: usage and internals and the Array types section of the specification.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.