The slices Package
Start with The slices Package
The generic slices package offers operations such as cloning, sorting, searching and comparing slice data.
What you’ll learn
- Explain the main purpose of the slices package.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
slices.Clone returns a shallow copy of a slice’s elements with independent underlying storage (for a non-nil slice). slices.Sort sorts ordered elements and slices.Contains checks membership. Nested pointers or other referential values in a shallow clone may still point at shared objects.
Go 1.23 added iterator-oriented helpers such as slices.Values and slices.Sorted; these are introduced later in the course. Prefer the collection functions matching your actual Go version.
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"
"slices"
)
func main() {
original := []int{4, 1, 3}
result := slices.Clone(original)
slices.Sort(result)
fmt.Println("Original:", original)
fmt.Println("Sorted copy:", result)
fmt.Println("Contains 3:", slices.Contains(result, 3))
}
Output
Original: [4 1 3]
Sorted copy: [1 3 4]
Contains 3: trueTrace what the program does
Clone gives the result independent slice storage. Sorting it yields [1 3 4], leaving the original order [4 1 3] unchanged. Contains reports true for 3.
Avoid common mistakes
- Clone is shallow when element values themselves refer to mutable state.
- slices.Sort changes its argument in place.
Try it yourself
Make a copy of three integers, reverse the copy with slices.Reverse, and compare it with the original.
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 The slices Package 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.