Multidimensional Slices
Start with Multidimensional Slices
A multidimensional slice is commonly a slice of slices. Unlike a fixed two-dimensional array, each row can have a different length.
What you’ll learn
- Explain the main purpose of multidimensional slices.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The type [][]int describes a slice whose elements are []int values. You can build a rectangular grid, but you can also make ragged rows with different element counts. Each inner slice has its own length and capacity.
Always use len(grid[row]) when iterating a row; assuming every row has the same size can cause out-of-bounds errors. Inner slices can also share backing storage if you deliberately construct them from one array.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
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() {
grid := [][]int{{1, 2}, {3}, {4, 5, 6}}
total := 0
for row := range grid {
for _, value := range grid[row] {
total += value
}
fmt.Println("Row", row, "length:", len(grid[row]))
}
fmt.Println("Total:", total)
}
Output
Row 0 length: 2
Row 1 length: 1
Row 2 length: 3
Total: 21Trace what the program does
The outer loop visits three inner slices. Their lengths are 2, 1 and 3. The inner loop adds every value once, producing a total of 21. No row is assumed to have the same length as another.
Avoid common mistakes
- Do not assume grid[0] and grid[1] always have identical lengths.
- A [][]int is a slice of slice descriptors; it is not guaranteed to be one contiguous rectangular allocation.
Try it yourself
Add a fourth row containing 7 and 8, and update the total. Then access the final element of each nonempty row.
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 Multidimensional Slices 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.