What is Slice in Go: Simple Explanation and Examples
slice is a flexible, dynamic view into an array that lets you work with sequences of elements without fixed size. It provides a convenient way to handle collections by referencing parts of an underlying array with a length and capacity.How It Works
A slice in Go is like a window looking into a bigger array. Imagine you have a long row of boxes (the array), and a slice is a smaller frame that shows some of those boxes. You can see and change the boxes inside this frame, but the frame itself can move or grow to show more or fewer boxes.
Unlike arrays, slices don’t have a fixed size. They keep track of how many elements they show (length) and how many elements they can grow to show without needing a new array (capacity). When you add more elements than the capacity, Go automatically creates a bigger array and copies the data.
This makes slices very useful because you don’t have to decide the size upfront, and you can easily work with parts of data without copying everything.
Example
This example shows how to create a slice, add elements, and print its length and capacity.
package main import "fmt" func main() { // Create a slice of integers with length 3 and capacity 5 numbers := make([]int, 3, 5) numbers[0] = 10 numbers[1] = 20 numbers[2] = 30 fmt.Println("Slice:", numbers) fmt.Println("Length:", len(numbers)) fmt.Println("Capacity:", cap(numbers)) // Append adds elements and may increase capacity numbers = append(numbers, 40, 50) fmt.Println("After append:", numbers) fmt.Println("Length:", len(numbers)) fmt.Println("Capacity:", cap(numbers)) }
When to Use
Use slices whenever you need a flexible list of items that can grow or shrink during your program. They are perfect for handling collections like user inputs, data from files, or results from calculations.
For example, if you are reading lines from a file but don’t know how many lines there will be, slices let you store each line easily without predefining the size. Also, slices are efficient because they share the underlying array, so copying data is minimized.
Key Points
- Slices are dynamic views into arrays with length and capacity.
- They allow flexible and efficient handling of collections.
- Appending to slices can increase their capacity automatically.
- Slices share the underlying array, so changes affect the original data.