Skip to content

Return a Separate Slice

The Course
•
25 min study

The last two lessons showed sharing happening by accident. When a type keeps a slice inside it and hands that slice to a caller, sharing becomes a hole in its protection: the caller can edit, reorder or overwrite the type's records without calling any of its methods. The fix is to hand out a copy.

Create a destination of the right length with make and copy the elements into it. copy(dst, src) returns how many elements it copied, which is the shorter of the two lengths, so a destination that is too short silently gets fewer elements. The copy is shallow: elements that hold maps, pointers or slices still refer to the same data. Strings can't be changed in place, so sharing their text is safe. The standard library's slices package, imported as "slices", has ready-made helpers for slices: slices.Clone does the same as make plus copy in one call, and slices.Sort sorts a slice in place. Day 3 looks at the package more closely.

Predict and run

Which slice changes after the edit?

Predict, then run Go
package main

import (
	"fmt"
)

func main() {
	original := []string{"Read", "Draft"}
	snapshot := make([]string, len(original))
	n := copy(snapshot, original)
	snapshot[0] = "Review"
	fmt.Println(n, original, snapshot)
}
Check your prediction
Text
2 [Read Draft] [Review Draft]

Make the destination one element long. Predict the count and snapshot.

Find the bug

This Board keeps its tasks in priority order, and Tasks lets callers see them. A report sorts what it receives alphabetically, and afterwards the board's own order is wrong. Run it and find the line that let the report reach inside the board.

Find the bug Go
package main

import (
	"fmt"
	"slices"
)

type Board struct {
	tasks []string
}

func (b *Board) Tasks() []string {
	return b.tasks
}

func main() {
	board := Board{tasks: []string{"Urgent fix", "Backup", "Cleanup"}}
	report := board.Tasks()
	slices.Sort(report)
	fmt.Println("report:", report)
	fmt.Println("board: ", board.tasks)
}
Text
report: [Backup Cleanup Urgent fix]
board:  [Backup Cleanup Urgent fix]
Check your fix

return b.tasks hands out a header that points at the board's own array, so sorting the report sorted the board. Return a copy:

Fixed Go
package main

import (
	"fmt"
	"slices"
)

type Board struct {
	tasks []string
}

func (b *Board) Tasks() []string {
	return slices.Clone(b.tasks)
}

func main() {
	board := Board{tasks: []string{"Urgent fix", "Backup", "Cleanup"}}
	report := board.Tasks()
	slices.Sort(report)
	fmt.Println("report:", report)
	fmt.Println("board: ", board.tasks)
}
Text
report: [Backup Cleanup Urgent fix]
board:  [Urgent fix Backup Cleanup]

Notice that the buggy version compiled, ran and printed a sensible-looking report. Sharing bugs show up somewhere else, later, which is why a type that owns a slice should never return it directly.

Practice

Exercise

Your turn

Write without(titles []string, i int) []string, which returns a new slice with the element at index i left out. The caller's slice must not change at all. The output should be:

Text
[Read Draft Review] [Read Review]
Your working space Go
package main

import (
	"fmt"
)

func main() {
	titles := []string{"Read", "Draft", "Review"}
	fmt.Println(titles)
}
Hint 1: the idea

Build the result in storage of its own, never in titles's array. Then nothing you do to the result can reach the caller.

Hint 2: a first step

Start with result := make([]string, 0, len(titles)-1), which has length 0 and room for every kept element. Range over titles with its index and append every element whose index is not i.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func without(titles []string, i int) []string {
	result := make([]string, 0, len(titles)-1)
	for j, title := range titles {
		if j != i {
			result = append(result, title)
		}
	}
	return result
}

func main() {
	titles := []string{"Read", "Draft", "Review"}
	result := without(titles, 1)
	fmt.Println(titles, result)
}
Text
[Read Draft Review] [Read Review]

result starts with its own array, so appending to it can never write into titles. A shortcut you will see in other code, appending titles[i+1:] onto titles[:i], reuses the caller's array and shifts Review into the caller's index 1. It returns the right slice and quietly damages the original, the same kind of bug as the board's.

Was this article helpful?

Your response is saved on this device.