Skip to content

See When Slices Share Storage

The Course
•
25 min study

On Day 1, passing a struct to a function copied it. Slices look as if they behave the same way, and they don't, which surprises almost everyone. A slice value is small: a pointer to an underlying array, a length and a capacity. Copying the slice, passing it to a function or taking a subslice copies that small header, and the copy still points at the same array. Assigning through either slice changes what the other sees.

The task queue hands slices to callers, so it has to know exactly when two slices share storage. This lesson shows when they do. The next shows how append can share storage too, and the one after shows how to stop it.

Predict and run

What does the original slice contain?

Predict, then run Go
package main

import (
	"fmt"
)

func main() {
	tasks := []string{"Read", "Draft", "Review"}
	tail := tasks[1:]
	tail[0] = "Outline"
	fmt.Println(tasks)
}
Check your prediction
Text
[Read Outline Review]

Set tail[1] instead. Which original index changes?

Draw the array

Sketch the program above as one array and two windows onto it:

Text
array:  [ Read | Draft | Review ]
index:     0      1       2
tasks:  [  0 ..................2 ]   len 3
tail:          [  0 .........1 ]     len 2, starts at array index 1

tail[0] and tasks[1] are two names for the same box. Writing Outline through tail fills that box, and tasks sees it because it reads the same box. Nothing was copied except the slice header.

A function can change the caller's elements

The same rule holds for parameters. A function that receives a slice can't make the caller's slice longer, because the length is part of the header it received a copy of. But it can change the caller's elements, because it shares the array. Compare this with the struct parameter from Day 1, which could not change anything in the caller.

Shared elements, separate headers Go
package main

import (
	"fmt"
)

func shout(titles []string) {
	for i := range titles {
		titles[i] += "!"
	}
	titles = append(titles, "Extra")
	fmt.Println("inside:", len(titles))
}

func main() {
	titles := []string{"Read", "Draft"}
	shout(titles)
	fmt.Println("outside:", len(titles), titles)
}
Text
inside: 3
outside: 2 [Read! Draft!]

The exclamation marks reach main because they were written into the shared array. Extra does not, because append changed only the function's copy of the header. That is why append's result must always be stored, and why a function that grows a slice has to return it.

Practice

Exercise

Your turn

Write markLate(due []int, today int), which changes every due day earlier than today to today. It returns nothing: the caller's slice should change. Then, with today as 4, call it on only the second half of the starter's slice, so the first half stays as it is. The output should be:

Text
[1 5 4 7]
Your working space Go
package main

import (
	"fmt"
)

func main() {
	due := []int{1, 5, 2, 7}
	fmt.Println(due)
}
Hint 1: the idea

The function shares the caller's array, so assigning to its elements is enough, with no return value. A subslice passed as the argument limits which elements the function can reach.

Hint 2: a first step

Write markLate and call it on the whole slice first. You should see [4 5 4 7], which proves the change reaches the caller. Then pass only the second half.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func markLate(due []int, today int) {
	for i := range due {
		if due[i] < today {
			due[i] = today
		}
	}
}

func main() {
	due := []int{1, 5, 2, 7}
	markLate(due[2:], 4)
	fmt.Println(due)
}
Text
[1 5 4 7]

Inside markLate, due[0] is the original's index 2, so the 2 becomes 4 while the 1 at the front is out of reach. Sharing is useful here, because the function changes data in place without copying it. The next lessons are about the cases where sharing is a bug.

Was this article helpful?

Your response is saved on this device.