Sling Academy
Home/Golang/Go - Iterating Collections: Using Range for Real-World Examples

Go - Iterating Collections: Using Range for Real-World Examples

Last updated: November 23, 2024

When programming in Go, you often encounter collections such as arrays, slices, and maps. A common task involves iterating through these collections to access or manipulate each element. Go provides a convenient keyword, range, specifically for this purpose. In this article, we’ll walk through real-world examples illustrating how range can be used to effectively iterate through different types of collections in Go.

Understanding range

The range keyword in Go iterates over various data structures such as arrays, slices, maps, and strings, conducting operations on each element. During iteration, range can provide index and value for arrays and slices, key and value for maps, and index and rune for strings.

Basic Example: Iterating Over Arrays

package main

import "fmt"

func main() {
    numbers := [3]int{10, 20, 30}

    for index, value := range numbers {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

This basic example demonstrates how range is employed to loop over an array called numbers. Here, both the index and the value of each element are printed.

Intermediate Example: Iterating Over Slices

package main

import "fmt"

func main() {
    fruits := []string{"Apple", "Banana", "Cherry"}

    for index, fruit := range fruits {
        fmt.Printf("Index: %d, Fruit: %s\n", index, fruit)
    }
}

Slices in Go provide a more powerful and flexible way to manage sequences of data compared to arrays. This intermediate example utilizes a slice of strings representing fruits, demonstrating how to utilize range to access each element.

Advanced Example: Iterating Over Maps

package main

import "fmt"

func main() {
    countryCapitals := map[string]string{
        "France":    "Paris",
        "Japan":     "Tokyo",
        "Australia": "Canberra",
    }

    for country, capital := range countryCapitals {
        fmt.Printf("The capital of %s is %s\n", country, capital)
    }
}

Maps in Go are key-value data structures, offering efficient lookups and being highly versatile for tasks like aggregating data. In this advanced example, the range keyword is used to iterate through a map where the keys are country names and the values are their capitals. This allows both keys and values to be accessed and printed.

Advanced Example: Iterating Over Strings

package main

import "fmt"

func main() {
    str := "Hello, 世界"

    for index, runeValue := range str {
        fmt.Printf("Index: %d, Rune: %c\n", index, runeValue)
    }
}

In Go, strings are sequences of bytes that can contain characters from UTF-8 character set. This advanced example shows how to iterate over a string containing both ASCII and non-ASCII characters. The index and the rune (which represents each Unicode character) are printed during each iteration.

Conclusion

The range keyword in Go is a powerful tool for accessing and manipulating collections like arrays, slices, maps, and strings. As we’ve seen, whether you’re working with simple arrays or complex data structures like maps, range delivers a clear and concise syntax for iterating, reducing the effort needed for common tasks while maintaining readability and efficiency.

Next Article: Fibonacci Series with Loops in Go

Previous Article: Building a Simple Calculator with Go's Control Flow

Series: Variables & Control Flow

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant