If arrays in Go are like a row of lockers, slices are like a magical row of lockers that can shrink and grow as needed!
In this guide, we’ll cover:
- What slices are and why they’re better than arrays.
- How to create, modify, and manipulate slices.
- Common slice pitfalls and best practices.
What is a Slice?
A slice is a dynamic, flexible version of an array. Unlike arrays, slices can grow and shrink as needed. Think of it like an expandable suitcase—you start with a small one, but if you shop too much, it magically grows to fit everything!
Declaring a Slice
package main
import "fmt"
func main() {
var numbers []int // A slice of integers (empty at first)
fmt.Println(numbers) // []
}
Unlike arrays, slices don’t have a fixed size.
Initializing a Slice
Using a Literal
func main() {
numbers := []int{10, 20, 30}
fmt.Println(numbers) // [10 20 30]
}
Using make()
func main() {
numbers := make([]int, 5) // Creates a slice with 5 elements (all set to 0)
fmt.Println(numbers) // [0 0 0 0 0]
}
Adding Elements to a Slice
The append()
function lets you add elements dynamically:
func main() {
numbers := []int{1, 2, 3}
numbers = append(numbers, 4, 5, 6)
fmt.Println(numbers) // [1 2 3 4 5 6]
}
Slicing a Slice
You can extract parts of a slice just like slicing a cake!
func main() {
nums := []int{10, 20, 30, 40, 50}
part := nums[1:4] // Gets elements from index 1 to 3
fmt.Println(part) // [20 30 40]
}
Looping Through a Slice
Using for
func main() {
nums := []int{100, 200, 300}
for i := 0; i < len(nums); i++ {
fmt.Println(nums[i])
}
}
Using range
func main() {
nums := []int{100, 200, 300}
for index, value := range nums {
fmt.Println("Index:", index, "Value:", value)
}
}
The Capacity of a Slice
Slices have a length (current elements) and a capacity (total elements before resizing is needed).
func main() {
nums := make([]int, 3, 5) // Length 3, Capacity 5
fmt.Println("Length:", len(nums), "Capacity:", cap(nums))
}
Common Pitfalls
- Appending Modifies the Original Slice (sometimes unexpectedly!).
- Out of Bounds Errors still apply if you go beyond the slice range.
- Slices Share the Same Underlying Array (modifying one might affect others!).
Slices are like arrays but way more flexible. If you need a dynamic data structure, use slices instead of arrays! Now go forth and slice your data like a chef! Happy coding!
0 Comments