Slice Length and Capacity
Start with Slice Length and Capacity
The length of a slice tells you how many elements it currently contains. Its capacity tells you how far that slice can be extended within its current underlying storage.
What you’ll learn
- Explain the main purpose of slice length and capacity.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use len(s) and cap(s) to inspect both values. With make([]int, 2, 5), indexes 0 and 1 are accessible, while three additional positions can become part of the slice after appending or reslicing within valid bounds.
Capacity is measured from the slice’s first element to the end of the available backing array segment. Reslicing from a later position typically reduces capacity even if the underlying array has not changed.
Visualize how it works
Read the labels and compare which positions are part of the visible value and which belong to the underlying representation.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
values := make([]int, 2, 5)
values[0], values[1] = 8, 9
fmt.Println("Original:", len(values), cap(values))
shorter := values[1:2]
fmt.Println("Resliced:", len(shorter), cap(shorter))
values = append(values, 10)
fmt.Println("Appended:", len(values), cap(values), values)
}
Output
Original: 2 5
Resliced: 1 4
Appended: 3 5 [8 9 10]Trace what the program does
The original slice has two elements and capacity five. The new slice starts at backing-array index 1, giving length one and capacity four. Appending 10 to the original slice increases its length to three but stays within capacity five, so no growth allocation is needed.
Avoid common mistakes
- Capacity is not a count of currently accessible elements; indexes must stay below len(s).
- Do not assume capacity always equals the backing array’s full length after reslicing.
Try it yourself
Start with make([]int, 0, 4). Append three numbers and inspect len and cap after each append.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Slice Length and Capacity in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.