Understanding Slices
Swipe to show menu
What Are Slices in Go?
Slices in Go are dynamically-sized, flexible views into the elements of an array. Unlike arrays, which have a fixed size, slices can grow and shrink as needed. This makes slices a powerful tool for working with collections of data when you do not know the exact number of elements in advance.
A slice does not store any data itself. Instead, it describes a section of an underlying array, keeping track of its own length and capacity. This means you can create, modify, and share slices without copying the underlying data, making them efficient for many operations.
You will use slices frequently in Go for tasks such as:
- Storing and processing lists of items;
- Passing subsets of data to functions;
- Efficiently appending or removing elements.
Understanding how slices work is essential for writing effective, idiomatic Go code when dealing with collections.
main.go
1234567891011121314package main import "fmt" func main() { // Declare a slice of integers with values numbers := []int{1, 2, 3, 4, 5} fmt.Println("Numbers:", numbers) // Declare an empty slice of strings and initialize it later var fruits []string fruits = append(fruits, "apple", "banana", "cherry") fmt.Println("Fruits:", fruits) }
Slices vs. Arrays in Go
Understanding the difference between slices and arrays is essential for effective data management in Go.
Key Differences
- Reference vs. Value:
- Slices are references to underlying arrays; changes to slice elements affect the underlying array.
- Arrays are value types; assigning an array copies all elements, so changes to one array do not affect another.
- Size Flexibility:
- Slices have dynamic size; you can append elements, and the slice will grow as needed.
- Arrays have fixed size; you must specify their length at declaration, and this cannot change.
- Memory Usage:
- Slices use a small descriptor (pointer, length, capacity) and share storage with their array.
- Arrays allocate memory for every element, even if you only use part of it.
Example
// Array: fixed size
var arr = [3]int{1, 2, 3}
// Slice: dynamic size, referencing arr
slice := arr[:]
slice = append(slice, 4) // Creates a new underlying array if capacity exceeded
Summary: Use arrays when you need a fixed, unchanging collection of items. Use slices when you need flexibility and dynamic behavior.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat