Mastering Slice Operations
Now that we have a basic understanding of Go slices, let's dive deeper into mastering various slice operations. These operations are crucial for effectively working with slices and leveraging their flexibility.
Appending to Slices
One of the most common operations with slices is appending new elements. The append()
function is used to add elements to the end of a slice. When the underlying array's capacity is exceeded, a new array is allocated, and the data is copied to the new array.
mySlice := []int{1, 2, 3}
mySlice = append(mySlice, 4, 5, 6)
In the example above, a new slice is created with the additional elements 4
, 5
, and 6
.
Slicing Slices
Slicing a slice allows you to create a new slice that references a subset of the original slice's elements. The syntax for slicing is mySlice[start:end]
, where start
is the index of the first element to include, and end
is the index of the first element to exclude.
mySlice := []int{1, 2, 3, 4, 5}
newSlice := mySlice[2:4]
In this example, newSlice
will be a slice containing the elements 3
and 4
from the original mySlice
.
Slice Length and Capacity
Slices have two important properties: length and capacity. The length of a slice represents the number of elements it contains, while the capacity is the total number of elements the underlying array can hold.
You can access the length and capacity of a slice using the built-in len()
and cap()
functions, respectively.
mySlice := make([]int, 3, 5)
fmt.Println("Length:", len(mySlice)) // Output: Length: 3
fmt.Println("Capacity:", cap(mySlice)) // Output: Capacity: 5
Understanding the relationship between length and capacity is crucial for optimizing slice performance, which we'll explore in the next section.