Go Slices

Dynamic arrays that can grow and shrink in Go

🔄 What are Go Slices?

Slices are dynamic arrays in Go that can change size during runtime. They're more flexible than arrays and are the preferred way to work with collections in Go programming.


// Create a slice
numbers := []int{1, 2, 3, 4, 5}
numbers = append(numbers, 6) // Add element
fmt.Println(numbers) // Output: [1 2 3 4 5 6]
                                    

Output:

[1 2 3 4 5 6]

Key Slice Concepts

📈

Dynamic Size

Slices can grow and shrink as needed

slice := []int{1, 2}
slice = append(slice, 3) // Now [1, 2, 3]
🔗

Reference Type

Slices reference underlying arrays

arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4] // [2, 3, 4]
📏

Length & Capacity

Slices have both length and capacity

fmt.Println(len(slice))  // Length
fmt.Println(cap(slice))  // Capacity
✂️

Slicing

Create sub-slices from existing slices

subSlice := slice[1:3] // Elements 1 to 2

🔹 Creating Slices

Multiple ways to create slices in Go:

package main

import "fmt"

func main() {
    // Method 1: Slice literal
    fruits := []string{"apple", "banana", "orange"}
    
    // Method 2: Make function
    numbers := make([]int, 5)      // Length 5, all zeros
    scores := make([]int, 3, 10)   // Length 3, capacity 10
    
    // Method 3: From array
    arr := [5]int{1, 2, 3, 4, 5}
    slice := arr[1:4]              // [2, 3, 4]
    
    // Method 4: Empty slice
    var empty []int                // nil slice
    
    fmt.Println("Fruits:", fruits)
    fmt.Println("Numbers:", numbers)
    fmt.Println("Scores:", scores)
    fmt.Println("Slice:", slice)
    fmt.Println("Empty:", empty)
}

Output:

Fruits: [apple banana orange]
Numbers: [0 0 0 0 0]
Scores: [0 0 0]
Slice: [2 3 4]
Empty: []

🔹 Adding Elements

Use the append function to add elements to slices:

package main

import "fmt"

func main() {
    // Start with empty slice
    var numbers []int
    fmt.Println("Initial:", numbers)
    
    // Add single element
    numbers = append(numbers, 10)
    fmt.Println("After adding 10:", numbers)
    
    // Add multiple elements
    numbers = append(numbers, 20, 30, 40)
    fmt.Println("After adding more:", numbers)
    
    // Add another slice
    moreNumbers := []int{50, 60}
    numbers = append(numbers, moreNumbers...)
    fmt.Println("After adding slice:", numbers)
    
    // Check length and capacity
    fmt.Printf("Length: %d, Capacity: %d\n", len(numbers), cap(numbers))
}

Output:

Initial: []
After adding 10: [10]
After adding more: [10 20 30 40]
After adding slice: [10 20 30 40 50 60]
Length: 6, Capacity: 8

🔹 Slice Operations

Common operations you can perform on slices:

package main

import "fmt"

func main() {
    colors := []string{"red", "green", "blue", "yellow", "purple"}
    
    // Slicing operations
    fmt.Println("Original:", colors)
    fmt.Println("First 3:", colors[:3])        // [red green blue]
    fmt.Println("Last 2:", colors[3:])         // [yellow purple]
    fmt.Println("Middle:", colors[1:4])        // [green blue yellow]
    
    // Copy slice
    colorsCopy := make([]string, len(colors))
    copy(colorsCopy, colors)
    fmt.Println("Copy:", colorsCopy)
    
    // Remove element (remove "blue" at index 2)
    colors = append(colors[:2], colors[3:]...)
    fmt.Println("After removal:", colors)
    
    // Insert element (insert "orange" at index 1)
    colors = append(colors[:1], append([]string{"orange"}, colors[1:]...)...)
    fmt.Println("After insertion:", colors)
}

Output:

Original: [red green blue yellow purple]
First 3: [red green blue]
Last 2: [yellow purple]
Middle: [green blue yellow]
Copy: [red green blue yellow purple]
After removal: [red green yellow purple]
After insertion: [red orange green yellow purple]

🧠 Test Your Knowledge

Which function is used to add elements to a slice?