Data structures & algorithms / Lesson 2

Arrays, slices, and boundaries

Trace length, capacity, shared storage, and safe boundaries through a runnable Go example.

A service takes the middle three values from a batch, changes the first value, and later finds that the original batch changed too. There is no mystery once we draw the storage: a Go slice can be a view into an existing array.

Track the values and the storage they belong to. The distinction matters when passing slices to functions, splitting a batch, or keeping part of a buffer.

Start with an array

[5]int50 creates an array of five integers. Its length is part of its type. Assigning an array to another array variable copies its values. A slice has type []int and refers to a section of an underlying array. Assigning a slice copies that description, so both slices can still refer to the same elements. The Go team’s slice guide explains this distinction. [1]

Our example starts with the array base and creates window := base[1:4]. The resulting values are [20 30 40]. Creating this window does not copy those integers.

Read the boundaries as gaps

The range [low:high) includes the lower position and excludes the upper one. Its length is high - low. Think of the numbers as gaps around elements:

The window base[1:4] includes original indices 1, 2, and 3
Original indexValueIn window?Window index
010No—
120Yes0
230Yes1
340Yes2
450No—

len(window) is 3: the number of accessible elements. cap(window) is 4: the extent from its starting position to the end of the underlying array. Indexing requires 0 ≤ i < len(window). Capacity is not permission to index element 3 directly. [2]

Reslicing can expose the remaining capacity: window[:4] is valid and includes the final 50. window[:] keeps its current length of 3. A missing upper bound defaults to length. Array slice bounds must stay within array length; a slice’s upper reslicing bound may reach its capacity. Invalid runtime bounds cause a panic. [3]

Trace shared storage one change at a time

1. Create the view

base = [10 20 30 40 50]
window = [20 30 40]

2. Write window[0] = 99

window[0] refers to base[1]. Now base = [10 99 30 40 50] and window = [99 30 40].

3. Keep track of the alias

Both names still reach those same three array elements. Passing window to a function does not automatically make them independent.

“Aliasing” means that more than one reference reaches the same storage. The mutation is visible through both views.

A function can change the caller’s elements through a slice parameter. Reassigning the parameter to a different slice is separate: it does not reassign the caller’s slice variable. Ask what the function mutates, rather than assuming that passing a value makes its referenced storage private.

Append with a deliberate storage boundary

When capacity is sufficient, append reuses the backing array. When it is insufficient, it allocates another array. The specification guarantees this choice, but does not fix the new capacity. [4] Do not infer independence from a particular growth factor observed on your machine.

Our window has spare capacity. To make the next nonempty append allocate, first limit its capacity to its length with a full slice expression:

clipped := window[:len(window):len(window)]
grown := append(clipped, 60)
grown[0] = 77

The third bound sets cap(clipped) to 3. Appending a fourth element therefore needs another backing array. After changing grown[0], grown is [77 30 40 60], while base remains [10 99 30 40 50]. [3]

Clipping capacity does not itself copy anything. Before the append, clipped[0] = 77 would still change base[1]. If you need independence immediately, allocate and copy:

copied := make([]int, len(window))
copiedCount := copy(copied, window)
copied[1] = 88

The copy has three elements. Changing its second element gives [99 88 40], while window stays [99 30 40]. copy returns the number of elements copied, limited by the shorter slice. [4] For these integers, copying elements gives independent values. Copying pointer elements would still leave the pointers referring to their original objects.

Handle empty inputs at the boundary

var missing []int is nil. empty := []int is non-nil. Both have length and capacity zero, support iteration, and accept appended values. Neither has a valid index 0. A nil check and a length check answer different questions. [1]

Equal bounds produce an empty range: base[:0] and base[5:5] are both valid. For a slice s, s[len(s):len(s)] is a useful empty tail. A loop using i < len(s) naturally handles zero elements. Replacing that condition with i <= len(s) attempts one invalid access.

Run the Go example

Save main.go and main_test.go together in an empty directory. The test checks the complete numbered output, including the empty ranges.

go run main.go
GO111MODULE=off go test -v
GO111MODULE=off go vet
package main

import "fmt"

func main() {
	base := [5]int{10, 20, 30, 40, 50}
	window := base[1:4]
	fmt.Printf("1. base=%v window=%v len=%d cap=%d\n",
		base, window, len(window), cap(window))

	window[0] = 99
	fmt.Printf("2. base=%v window=%v\n", base, window)

	// A full slice expression limits capacity; it does not copy elements.
	clipped := window[:len(window):len(window)]
	grown := append(clipped, 60)
	grown[0] = 77
	fmt.Printf("3. base=%v grown=%v\n", base, grown)

	copied := make([]int, len(window))
	copiedCount := copy(copied, window)
	copied[1] = 88
	fmt.Printf("4. base=%v window=%v copied=%v copied-count=%d\n",
		base, window, copied, copiedCount)

	var missing []int
	empty := []int{}
	fmt.Printf("5. nil: len=%d cap=%d is-nil=%t; empty: len=%d cap=%d is-nil=%t\n",
		len(missing), cap(missing), missing == nil,
		len(empty), cap(empty), empty == nil)

	fmt.Printf("6. base[:0]=%v base[5:5]=%v window[:4]=%v\n",
		base[:0], base[5:5], window[:4])
}

Expected output:

1. base=[10 20 30 40 50] window=[20 30 40] len=3 cap=4
2. base=[10 99 30 40 50] window=[99 30 40]
3. base=[10 99 30 40 50] grown=[77 30 40 60]
4. base=[10 99 30 40 50] window=[99 30 40] copied=[99 88 40] copied-count=3
5. nil: len=0 cap=0 is-nil=true; empty: len=0 cap=0 is-nil=false
6. base[:0]=[] base[5:5]=[] window[:4]=[99 30 40 50]

Check your understanding

1. Count the selected elements

For an eight-element array a, which indices appear in a[2:5], and what is the length?

Reveal answer: count the selected elements

Original indices 2, 3, and 4. The slice length is 5 - 2 = 3, and its own indices are 0, 1, and 2.

2. Capacity and indexing

Our window has length 3 and capacity 4. Can you read window[3] directly?

Reveal answer: capacity and indexing

No. It panics because index 3 is outside the current length. First form a longer slice, such as extended := window[:4], then read extended[3].

3. Copy or view?

A function must change its working integers without changing its caller’s input. Is working := input[:] enough?

Reveal answer: copy or view

No. That makes another view of the same elements. Allocate working := make([]int, len(input)), then call copy(working, input) before changing the integers.

Primary references

  1. Go Slices: usage and internals — arrays, views, and nil slices.
  2. Go specification: slice types — shared storage, length, and capacity.
  3. Go specification: slice expressions — half-open bounds and full slice expressions.
  4. Go specification: appending and copying slices — storage reuse and element copying.