ZetCode

Golang range keyword

last modified May 7, 2025

This tutorial explains how to use the range keyword in Go. We'll cover iteration basics with practical examples of ranging over collections.

The range keyword provides iteration over arrays, slices, maps, strings, and channels. It returns index/value pairs for ordered collections.

In Go, range simplifies loop syntax when working with collections. It handles the iteration logic automatically, making code cleaner and safer.

Basic range over a slice

The simplest use of range iterates over a slice. This example shows how to access both index and value.

basic_range.go
package main

import "fmt"

func main() {
    fruits := []string{"apple", "banana", "cherry"}
    
    for index, fruit := range fruits {
        fmt.Printf("Index: %d, Value: %s\n", index, fruit)
    }
}

The loop iterates through the slice, assigning index to index and value to fruit. Range handles the iteration bounds automatically.

Range with maps

range works with maps by returning key/value pairs. This example demonstrates iterating over a map's entries.

map_range.go
package main

import "fmt"

func main() {
    ages := map[string]int{
        "Alice": 25,
        "Bob":   30,
        "Carol": 28,
    }
    
    for name, age := range ages {
        fmt.Printf("%s is %d years old\n", name, age)
    }
}

Map iteration order is not guaranteed. Each run may produce different output ordering. Range simplifies map traversal syntax.

Ignoring index or value

You can ignore either the index or value using _. This example shows both cases.

ignore_range.go
package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40, 50}
    
    // Ignore index
    for _, value := range numbers {
        fmt.Println(value)
    }
    
    // Ignore value
    for index := range numbers {
        fmt.Println(index)
    }
}

The underscore _ discards unwanted values. This makes code cleaner when you only need one part of the pair.

Range with strings

When ranging over strings, Go iterates over Unicode code points. This example demonstrates character iteration.

string_range.go
package main

import "fmt"

func main() {
    greeting := "Hello, 世界"
    
    for index, runeValue := range greeting {
        fmt.Printf("Index: %d, Rune: %c\n", index, runeValue)
    }
}

The loop processes each Unicode character separately. Note that some characters may occupy multiple bytes in UTF-8 encoding.

Range with channels

range can iterate over channel values until the channel is closed. This example shows channel iteration.

channel_range.go
package main

import "fmt"

func main() {
    ch := make(chan string, 2)
    ch <- "first"
    ch <- "second"
    close(ch)
    
    for value := range ch {
        fmt.Println(value)
    }
}

The loop reads from the channel until it's closed. Range simplifies channel consumption by handling the close condition automatically.

Range with pointers to arrays

When ranging over array pointers, Go automatically dereferences them. This example demonstrates this behavior.

pointer_range.go
package main

import "fmt"

func main() {
    arr := [3]int{1, 2, 3}
    ptr := &arr
    
    for index, value := range ptr {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

The pointer ptr is automatically dereferenced during iteration. This makes working with array pointers more convenient.

Practical example: Summing values

This practical example demonstrates using range to calculate the sum of values in a slice.

sum_range.go
package main

import "fmt"

func main() {
    numbers := []int{5, 10, 15, 20, 25}
    sum := 0
    
    for _, num := range numbers {
        sum += num
    }
    
    fmt.Printf("Sum: %d\n", sum)
}

The loop ignores the index using _ and accumulates values in sum. Range makes the iteration clean and concise.

Source

Go language specification

This tutorial covered the range keyword in Go with practical examples of iterating over different collection types.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Golang tutorials.