Creating Slices
Start with Creating Slices
Go offers slice literals, make, and slicing an existing array or slice. Each approach produces a slice value with a length and capacity.
What you’ll learn
- Explain the main purpose of creating slices.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use a literal for known contents, such as []string{"red", "blue"}. Use make([]int, length, capacity) when you need zero-initialized elements and optional spare capacity. Use array[start:end] to form a view into an existing array.
The zero value of a slice is nil, and a nil slice can be appended to. An empty non-nil slice also has length zero, but comparisons to nil can distinguish them in code.
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() {
literal := []int{4, 5}
allocated := make([]int, 2, 5)
numbers := [4]int{10, 20, 30, 40}
view := numbers[1:3]
fmt.Println("Literal:", literal)
fmt.Println("Allocated:", allocated)
fmt.Println("View:", view)
fmt.Println("Capacity:", cap(allocated))
}
Output
Literal: [4 5]
Allocated: [0 0]
View: [20 30]
Capacity: 5Trace what the program does
The literal starts with 4 and 5. The make call produces two visible zero elements and capacity five. Slicing numbers from index 1 up to, but not including, index 3 creates [20 30] without copying those elements.
Avoid common mistakes
make([]int, 2, 5)sets length 2, not length 5.- A slice made from an array shares that array’s underlying elements.
Try it yourself
Create a nil []int variable, append 7 to it, and compare it with an empty slice produced by make([]int, 0).
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 Creating 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.