Go Range

Iterating over collections with ease

πŸ” What is Go Range?

Go range keyword provides an elegant way to iterate over arrays, slices, maps, strings, and channels, automatically handling indexes and values for cleaner, more readable code.


// Simple range example
numbers := []int{10, 20, 30}
for index, value := range numbers {
    fmt.Printf("Index: %d, Value: %d\n", index, value)
}
                                    

Output:

Index: 0, Value: 10

Index: 1, Value: 20

Index: 2, Value: 30

Range with Different Types

πŸ“Š

Arrays & Slices

Iterate over ordered collections

arr := [3]int{1, 2, 3}
for i, v := range arr {
    fmt.Println(i, v)
}
πŸ—ΊοΈ

Maps

Iterate over key-value pairs

m := map[string]int{"a": 1, "b": 2}
for k, v := range m {
    fmt.Println(k, v)
}
πŸ”€

Strings

Iterate over characters (runes)

str := "Hello"
for i, char := range str {
    fmt.Printf("%d: %c\n", i, char)
}
πŸ“‘

Channels

Receive values from channels

ch := make(chan int)
for value := range ch {
    fmt.Println(value)
}

πŸ”Ή Range with Arrays and Slices

Most common use of range - iterating over arrays and slices:

package main

import "fmt"

func main() {
    fruits := []string{"apple", "banana", "orange"}
    
    // Get both index and value
    fmt.Println("With index and value:")
    for i, fruit := range fruits {
        fmt.Printf("Index %d: %s\n", i, fruit)
    }
    
    // Get only values (ignore index with _)
    fmt.Println("\nOnly values:")
    for _, fruit := range fruits {
        fmt.Printf("Fruit: %s\n", fruit)
    }
}

Output:

With index and value:

Index 0: apple

Index 1: banana

Index 2: orange


Only values:

Fruit: apple

Fruit: banana

Fruit: orange

πŸ”Ή Range with Maps

Iterate over key-value pairs in maps:

package main

import "fmt"

func main() {
    ages := map[string]int{
        "Alice": 25,
        "Bob":   30,
        "Carol": 35,
    }
    
    // Get both key and value
    fmt.Println("Name and Age:")
    for name, age := range ages {
        fmt.Printf("%s is %d years old\n", name, age)
    }
    
    // Get only keys
    fmt.Println("\nOnly names:")
    for name := range ages {
        fmt.Printf("Name: %s\n", name)
    }
}

Output:

Name and Age:

Alice is 25 years old

Bob is 30 years old

Carol is 35 years old


Only names:

Name: Alice

Name: Bob

Name: Carol

πŸ”Ή Range with Strings

Iterate over characters (runes) in strings:

package main

import "fmt"

func main() {
    message := "Hello, δΈ–η•Œ"
    
    // Range over string gives index and rune
    fmt.Println("Character by character:")
    for i, char := range message {
        fmt.Printf("Index %d: %c (Unicode: %d)\n", i, char, char)
    }
    
    // Count characters
    count := 0
    for range message {
        count++
    }
    fmt.Printf("\nTotal characters: %d\n", count)
}

Output:

Character by character:

Index 0: H (Unicode: 72)

Index 1: e (Unicode: 101)

Index 2: l (Unicode: 108)

Index 3: l (Unicode: 108)

Index 4: o (Unicode: 111)

Index 5: , (Unicode: 44)

Index 6: (Unicode: 32)

Index 7: δΈ– (Unicode: 19990)

Index 10: η•Œ (Unicode: 30028)


Total characters: 9

πŸ”Ή Range with Only Index

Sometimes you only need the index, not the value:

package main

import "fmt"

func main() {
    numbers := []int{100, 200, 300, 400, 500}
    
    // Print only indices
    fmt.Println("Available indices:")
    for i := range numbers {
        fmt.Printf("Index: %d\n", i)
    }
    
    // Use index to access elements
    fmt.Println("\nAccessing by index:")
    for i := range numbers {
        fmt.Printf("numbers[%d] = %d\n", i, numbers[i])
    }
}

Output:

Available indices:

Index: 0

Index: 1

Index: 2

Index: 3

Index: 4


Accessing by index:

numbers[0] = 100

numbers[1] = 200

numbers[2] = 300

numbers[3] = 400

numbers[4] = 500

πŸ”Ή Range with Break and Continue

Control flow within range loops:

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    
    fmt.Println("Finding even numbers (stop at 8):")
    for i, num := range numbers {
        if num > 8 {
            fmt.Printf("Stopping at index %d\n", i)
            break
        }
        
        if num%2 != 0 {
            continue // Skip odd numbers
        }
        
        fmt.Printf("Even number found: %d\n", num)
    }
}

Output:

Finding even numbers (stop at 8):

Even number found: 2

Even number found: 4

Even number found: 6

Even number found: 8

Stopping at index 8

🧠 Test Your Knowledge

What does range return when used with a slice?