Introduction to Slices - Go Programming
What are Slices?
Slices are a key data type in Go, providing a more powerful interface to sequences than arrays. Unlike arrays, slices are dynamically-sized and more flexible. A slice is a segment of an array and can grow and shrink as needed.
Creating a Slice
There are several ways to create a slice in Go. One common method is to use the built-in make function:
slice := make([]int, 5)
This creates a slice of integers with an initial length of 5.
Slice Literals
Slices can also be created using slice literals, which is a more concise way to create and initialize a slice:
slice := []int{1, 2, 3, 4, 5}
This creates a slice with 5 elements, each initialized to corresponding values.
Accessing Slice Elements
You can access elements of a slice using the index operator, similar to arrays.
fmt.Println(slice[0]) // Outputs: 1
Modifying Slice Elements
Slice elements can be modified by specifying the index and assigning a new value:
slice[1] = 10
fmt.Println(slice) // Outputs: [1 10 3 4 5]
Appending to a Slice
Go provides the append function, which allows you to add new elements to a slice:
slice = append(slice, 6)
fmt.Println(slice) // Outputs: [1 10 3 4 5 6]
Slice Capacity and Length
Each slice has a length and a capacity. The length is the number of elements the slice contains, while the capacity is the number of elements in the underlying array, counting from the first element in the slice.
fmt.Println(len(slice)) // Outputs: 6
fmt.Println(cap(slice)) // Outputs: 6
Slicing a Slice
You can create a new slice by slicing an existing slice. This is done by specifying a range of indices.
newSlice := slice[1:4]
fmt.Println(newSlice) // Outputs: [10 3 4]
Note that the start index is inclusive, while the end index is exclusive.
Iterating Over a Slice
You can iterate over the elements of a slice using a for loop.
for i, v := range slice {
fmt.Println(i, v)
}
This loop prints both the index and the value of each element in the slice.
Example Program
Below is a complete example program that demonstrates various operations on slices.
package main
import "fmt"
func main() {
// Creating a slice
slice := []int{1, 2, 3, 4, 5}
// Accessing elements
fmt.Println(slice[0]) // Outputs: 1
// Modifying elements
slice[1] = 10
fmt.Println(slice) // Outputs: [1 10 3 4 5]
// Appending elements
slice = append(slice, 6)
fmt.Println(slice) // Outputs: [1 10 3 4 5 6]
// Slice capacity and length
fmt.Println(len(slice)) // Outputs: 6
fmt.Println(cap(slice)) // Outputs: 6
// Slicing a slice
newSlice := slice[1:4]
fmt.Println(newSlice) // Outputs: [10 3 4]
// Iterating over a slice
for i, v := range slice {
fmt.Println(i, v)
}
}