Go Slices: Dynamic Arrays for Efficient Data Handling
Learn about Go slices, a flexible data structure for storing and manipulating collections of elements. Discover how to create, access, iterate, and modify slices, and understand the key concepts of length and capacity.
Understanding Slices
A slice in Go is a dynamic view into an underlying array. It provides a powerful and efficient way to work with collections of data. Unlike arrays, slices are not fixed in size and can grow or shrink as needed.
Declaring Slices
There are three primary ways to create a slice:
Literal syntax:
Syntax
slice := []int{1, 2, 3}
Output
[1 2 3]
From an array:
Syntax
arr := [5]int{10, 20, 30, 40, 50}
slice := arr[1:4] // Creates a slice from index 1 to 3 (exclusive)
Output
[20 30 40]
Using the make function:
Syntax
slice := make([]int, 4, 6) // Creates a slice with length 4 and capacity 6
Output
[0 0 0 0]
Slice Length and Capacity
Length: The number of elements in the slice.
Capacity: The maximum number of elements a slice can hold without reallocation.
Syntax
package main
import "fmt"
func main() {
slice := []int{1, 2, 3}
fmt.Println("Length:", len(slice))
fmt.Println("Capacity:", cap(slice))
}
Output
Length: 3
Capacity: 3
Accessing Slice Elements
You can access elements using their index, similar to arrays:
Syntax
slice := []int{10, 20, 30}
fmt.Println(slice[1]) // Output: 20
Output
20
Modifying Slice Elements
You can modify elements directly:
Syntax
slice[0] = 5
fmt.Println(slice) // Output: [5 20 30]
Output
[5 20 30]
Slicing a Slice
You can create new slices from existing slices:
Syntax
slice := []int{10, 20, 30, 40, 50}
newSlice := slice[2:4] // Creates a slice with elements at index 2 and 3
fmt.Println(newSlice) // Output: [30 40]
Output
[30 40]
Appending to a Slice
Use the append function to add elements to a slice:
Syntax
slice := []int{1, 2, 3}
slice = append(slice, 4, 5)
fmt.Println(slice) // Output: [1 2 3 4 5]
Output
[1 2 3 4 5]
Iterating Over a Slice
Use a for loop or for-range loop to iterate over slice elements:
Syntax
slice := []int{10, 20, 30}
// Using for loop
for i := 0; i < len(slice); i++ {
fmt.Println(slice[i])
}
// Using for-range loop
for index, value := range slice {
fmt.Println(index, value)
}
Output
10
20
30
0 10
1 20
2 30
Key Points
- Slices are dynamic arrays with flexible length.
- Understand the difference between length and capacity.
- Use slicing to create sub-slices.
- Employ the append function to add elements.
- Iterate over slices using for or for-range loops.
By mastering slices, you'll be able to efficiently handle collections of data in your Go programs.