In Go, a slice is a flexible and powerful way to work with sequences of data. Think of it as an array with some added capabilities, like being able to change size. Accessing elements of a slice in Go is done using indices, just like with arrays. In this article, we'll cover how to access slice elements, from beginner to advanced examples.
Basic Slice Access
Let's start with the basics: creating a slice and accessing its elements using indices.
package main
import "fmt"
func main() {
// Create a slice of integers
numbers := []int{10, 20, 30, 40, 50}
// Access slice elements by index
fmt.Println(numbers[0]) // Output: 10
fmt.Println(numbers[2]) // Output: 30
fmt.Println(numbers[4]) // Output: 50
}
In this example, we have a slice named numbers containing five elements. We access the elements using zero-based index notation. Note that trying to access an index out of the slice bounds will cause a runtime panic.
Intermediate Usage with Loops
Accessing elements in a loop is a common pattern when working with slices.
package main
import "fmt"
func main() {
// Create a slice of strings
fruits := []string{"Apple", "Banana", "Cherry", "Date"}
// Iterate over all elements using a for loop
for i := 0; i < len(fruits); i++ {
fmt.Printf("Fruit %d: %s\n", i, fruits[i])
}
}
Here, we use a for loop to iterate over the slice and access each element by its index.
Advanced Slicing with Range
The range keyword offers a more concise way to iterate over slices in Go, providing index and value in a single step.
package main
import "fmt"
func main() {
// Create a slice of floats
prices := []float64{19.99, 29.99, 4.99, 7.49}
// Use range to iterate over the slice
for index, price := range prices {
fmt.Printf("Price of item %d: %.2f\n", index, price)
}
}
In this example, using range, we efficiently access both the index and the value of each element in the slice, simplifying the loop structure.
Advanced Boundaries and the copy Function
More complex slice manipulations might involve copying sections of one slice to another. Accessing normally should respect boundaries to prevent panics.
package main
import "fmt"
func main() {
// Declare a source slice
source := []string{"Red", "Green", "Blue"}
// Declare a destination slice with enough length
dest := make([]string, 2)
// Copy elements from source (index 1 to 3) to destination
copy(dest, source[1:3])
fmt.Println("Destination:", dest) // Output: [Green Blue]
}
Here, we use the copy function to demonstrate copying elements from a segment of a slice to another.
Conclusion
Understanding how to access and manipulate slice elements by index is a fundamental skill in Go. Through these examples, we've explored several methodologies ranging from basic indexing to advanced techniques like using range and copy. Practice these techniques, and you'll find working with slices in Go both powerful and flexible.