Slice Fundamentals
What is a Slice in Go?
In Go, a slice is a dynamic, flexible view into an underlying array. Unlike arrays, slices can grow and shrink in size, making them more versatile for data manipulation. A slice consists of three key components:
- Pointer to the underlying array
- Length of the slice
- Capacity of the slice
Basic Slice Declaration and Initialization
// Create a slice using make()
numbers := make([]int, 5, 10) // length 5, capacity 10
// Create a slice from an array
arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4] // slice contains [2, 3, 4]
// Literal slice declaration
fruits := []string{"apple", "banana", "cherry"}
Slice Properties
Property |
Description |
Example |
Length |
Number of elements in the slice |
len(slice) |
Capacity |
Maximum number of elements the slice can hold |
cap(slice) |
Zero Value |
Nil slice with no underlying array |
var emptySlice []int |
Memory Representation
graph LR
A[Slice Header] --> B[Pointer to Underlying Array]
A --> C[Length]
A --> D[Capacity]
Common Slice Operations
// Appending elements
slice := []int{1, 2, 3}
slice = append(slice, 4, 5) // [1, 2, 3, 4, 5]
// Copying slices
original := []int{1, 2, 3}
copied := make([]int, len(original))
copy(copied, original)
Key Takeaways
- Slices are more flexible than arrays
- Slices are reference types
- Always check slice length and capacity
- Use
append()
for dynamic growth
- Be mindful of underlying array modifications
LabEx Tip
When learning slice management, practice is key. LabEx provides interactive Go programming environments to help you master slice manipulation techniques.