Slicing Operations
Start with Slicing Operations
A slicing expression selects a half-open portion of an array or slice. The end index is excluded, which makes the resulting length easy to calculate.
What you’ll learn
- Explain the main purpose of slicing operations.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The expression items[1:4] includes original indexes 1, 2 and 3, so its length is 4-1=3. Omitting the start defaults to zero; omitting the end defaults to the current length. Slicing usually creates a new view rather than copying elements.
A full slice expression a[low:high:max] can restrict the resulting capacity, helping avoid unexpected sharing during future append operations. Slice bounds must satisfy the language’s rules or execution panics.
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() {
values := []int{10, 20, 30, 40, 50}
middle := values[1:4]
first := values[:2]
last := values[3:]
middle[0] = 99
fmt.Println("Middle:", middle)
fmt.Println("First:", first)
fmt.Println("Last:", last)
fmt.Println("Original:", values)
}
Output
Middle: [99 30 40]
First: [10 99]
Last: [40 50]
Original: [10 99 30 40 50]Trace what the program does
The middle view begins at index 1 and contains three values. Changing its first element writes to original index 1. The first view also includes original index 1, so it observes 99. The last view begins at original index 3 and is unaffected.
Avoid common mistakes
- The high bound is exclusive, not inclusive.
- Slicing typically shares elements; it is not a cloning operation.
Try it yourself
Create the slice values[2:5], predict its length and then modify its last element.
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 Slicing Operations 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.