Slice Basics in Go
What is a Slice in Go?
In Go, a slice is a dynamic, flexible view into an underlying array. Unlike arrays, slices can grow and shrink in size, making them more versatile for many programming scenarios. A slice consists of three key components:
- A pointer to the underlying array
- The length of the slice
- The capacity of the slice
Slice Declaration and Initialization
There are multiple ways to create a slice in Go:
// Method 1: Using slice literal
fruits := []string{"apple", "banana", "orange"}
// Method 2: Using make() function
numbers := make([]int, 5) // Creates a slice of 5 integers
dynamicSlice := make([]int, 0, 10) // Length 0, capacity 10
Slice Memory Structure
graph TD
A[Slice] --> B[Pointer]
A --> C[Length]
A --> D[Capacity]
B --> E[Underlying Array]
Key Slice Operations
Operation |
Description |
Example |
Append |
Add elements |
slice = append(slice, newElement) |
Slicing |
Extract subset |
newSlice := originalSlice[start:end] |
Length |
Get slice size |
len(slice) |
Capacity |
Get slice capacity |
cap(slice) |
Slice vs Array
The primary differences between slices and arrays:
- Arrays have fixed length
- Slices are dynamic
- Slices are more memory-efficient
- Slices are passed by reference
Code Example
package main
import "fmt"
func main() {
// Slice declaration and manipulation
numbers := []int{1, 2, 3, 4, 5}
// Appending elements
numbers = append(numbers, 6, 7)
// Slicing
subset := numbers[2:5]
fmt.Println("Original slice:", numbers)
fmt.Println("Subset:", subset)
fmt.Println("Slice length:", len(numbers))
fmt.Println("Slice capacity:", cap(numbers))
}
Slices in Go are lightweight and efficient. When you use append()
, Go automatically manages memory allocation, which helps prevent common memory-related errors.
By understanding these slice basics, you'll be well-prepared to use this powerful data structure in your Go programming with LabEx.