Slice Manipulation
Slice Indexing and Slicing
Basic Slice Syntax
slice[start:end] // Elements from start to end-1
slice[start:] // Elements from start to end
slice[:end] // Elements from beginning to end-1
slice[:] // Entire slice
Practical Examples
numbers := []int{0, 1, 2, 3, 4, 5}
subset := numbers[2:4] // [2, 3]
Slice Modification Techniques
Inserting Elements
func insert(slice []int, index int, value int) []int {
slice = append(slice[:index], append([]int{value}, slice[index:]...)
return slice
}
Deleting Elements
func remove(slice []int, index int) []int {
return append(slice[:index], slice[index+1:]...)
}
Advanced Slice Operations
Slice Filtering
func filterEven(numbers []int) []int {
var result []int
for _, num := range numbers {
if num % 2 == 0 {
result = append(result, num)
}
}
return result
}
Slice Manipulation Patterns
graph TD
A[Slice Manipulation] --> B[Indexing]
A --> C[Insertion]
A --> D[Deletion]
A --> E[Filtering]
Memory Management
Operation |
Memory Impact |
Performance |
Append |
May reallocate |
O(1) amortized |
Copy |
Creates new slice |
O(n) |
Reslicing |
No new allocation |
O(1) |
Common Pitfalls
Slice Sharing
original := []int{1, 2, 3, 4, 5}
shared := original[:3]
shared[0] = 99 // Modifies original slice
- Preallocate slice capacity when possible
- Use
copy()
for efficient slice copying
- Minimize slice reallocations
LabEx Optimization Tip
When practicing slice manipulation in LabEx environments, always profile your code to understand memory and performance characteristics.
Advanced Techniques
Slice as Function Parameters
func processSlice(slice []int) []int {
// Modify and return slice
return slice
}
Multi-dimensional Slices
matrix := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
Error Handling
Preventing Slice Bounds Errors
func safeAccess(slice []int, index int) (int, error) {
if index < 0 || index >= len(slice) {
return 0, fmt.Errorf("index out of bounds")
}
return slice[index], nil
}