Skip to content
Codewilds

Lesson 15 of 38 · Slices & Maps

Go Arrays vs Slices: Slicing and range

easy10 XP4 min read

One variable holds one value — but a dragon's hoard, a high-score table or a party of adventurers is a collection. Go has two built-in types for ordered collections: arrays and slices. Arrays are the foundation; slices are built on top of them, and they are what you will use almost all the time.

In this lesson you'll learn how Go arrays and slices differ, how to cut one slice out of another, why two slices can share the same elements, and how to loop over them with range.

Arrays: the length is part of the type

An array holds a fixed number of elements of one type. The length is written in the brackets and belongs to the type itself, so [3]int and [5]int are two different types. With [...] the compiler counts the elements for you.

var scores [3]int // three ints, all 0
scores[0] = 90
primes := [5]int{2, 3, 5, 7, 11}
days := [...]string{"Mon", "Tue", "Wed"} // type [3]string
fmt.Println(scores, len(primes), len(days))
[90 0 0] 5 3

Arrays are values: assigning an array or passing it to a function copies every element.

a := [3]int{1, 2, 3}
b := a // b is a complete copy
b[0] = 100
fmt.Println(a, b)
[1 2 3] [100 2 3]

Because their size can never change, arrays are rare in everyday Go code. You'll mostly meet them as the storage behind slices.

Slices: a flexible view

A slice type has no length in its brackets: []int, []string. A slice literal looks like an array literal without the size:

party := []string{"Ada", "Bo", "Cy"}
fmt.Println(len(party), party[1]) // 3 Bo

A slice doesn't own its elements. It is a small descriptor — a pointer into an underlying array, a length and a capacity — so several slices can look at the same array.

s[low:high] creates a new slice from index low up to, but not including, high. Its length is high - low. Leave out low to start at 0, or high to go to the end. You can slice an array too: arr[:] covers the whole array.

nums := []int{10, 20, 30, 40, 50}
fmt.Println(nums[1:3]) // indexes 1 and 2
fmt.Println(nums[:2])  // from the start
fmt.Println(nums[3:])  // to the end
[20 30]
[10 20]
[40 50]

Slices share their elements

Slicing never copies. The new slice is a window on the same array, so a change made through one slice is visible through the other:

nums := []int{10, 20, 30, 40, 50}
middle := nums[1:4]
middle[0] = 99
fmt.Println(middle)
fmt.Println(nums)
[99 30 40]
[10 99 30 40 50]

The same happens when you pass a slice to a function: Go copies the small descriptor, not the elements, so the function can change the caller's data. That makes passing slices cheap — just remember it when a function should not touch its input.

func reset(s []int) {
	for i := range s {
		s[i] = 0 // changes the caller's elements
	}
}

The zero value of a slice is nil: no array, length 0. The literal []int{} is empty but not nil. Both work with len, range and append, so test for emptiness with len(s) == 0 rather than s == nil.

Looping with range

for i, v := range s visits every element in order and gives you its index and a copy of its value:

loot := []string{"gold", "gem", "sword"}
for i, item := range loot {
	fmt.Println(i, item)
}
0 gold
1 gem
2 sword

Write for _, item := range loot when you don't need the index (Go rejects unused variables, and _ discards a value), or for i := range loot when you only need the index. Because the value variable is a copy, assigning to it doesn't change the slice — use the index for that:

nums := []int{1, 2, 3}
for _, n := range nums {
	n = n * 10 // only changes the copy
}
fmt.Println(nums) // [1 2 3]
for i := range nums {
	nums[i] *= 10
}
fmt.Println(nums) // [10 20 30]

Common mistakes

  • Off-by-one slicing: s[1:3] has two elements, because high is excluded.
  • Indexing past the end: valid indexes run from 0 to len(s)-1. s[3] on a slice of length 3 panics with index out of range [3] with length 3.
  • Mixing up arrays and slices: a function that takes []int doesn't accept a [3]int — pass arr[:].
  • Forgetting that slices share memory: changing a sub-slice, or a slice inside a function, changes the original.
  • Comparing slices with ==: only s == nil compiles. Arrays, on the other hand, can be compared with ==.

Assignment

The treasury of the Gopher Isles needs four helpers:

  1. SumSlice(nums []int) int returns the sum of all numbers (0 for an empty or nil slice).
  2. Middle(nums []int) []int returns everything except the first and the last element. If nums has fewer than 3 elements, return an empty slice. Returning a sub-slice of nums is fine.
  3. CountAbove(nums []int, limit int) int returns how many numbers are strictly greater than limit.
  4. DoubleInPlace(nums []int) multiplies every element by 2. It returns nothing — it changes the caller's slice.
SumSlice([]int{3, -1, 10})           // 12
Middle([]int{1, 2, 3, 4, 5})         // [2 3 4]
CountAbove([]int{5, 10, 15, 20}, 10) // 2
nums := []int{1, 2, 3}
DoubleInPlace(nums) // nums is now [2 4 6]

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Arrays and lists in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+10 XP

Lesson 15 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.