The range keyword in Go is a powerful tool used for iterating over various data structures like slices, arrays, maps, and strings. However, one of its simplest and more recent additions (in Go 1.22) is the ability to range over integers directly.
Instead of writing a traditional C-style for loop to iterate a specific number of times, you can use range with an integer:
for i := range 5 {
fmt.Println(i)
}
// Prints: 0, 1, 2, 3, 4
This creates a loop that runs 5 times, with i taking values from 0 to 4.
When you use range with an integer n, it generates a sequence from 0 to n-1:
for i := range 3 {
fmt.Println("Iteration:", i)
}
// Output:
// Iteration: 0
// Iteration: 1
// Iteration: 2
The loop variable starts at 0 and increments by 1 each iteration, just like a traditional for loop.
Sometimes you just want to repeat an action a certain number of times without caring about the counter. You can use the blank identifier _ to ignore the index:
for _ = range 3 {
fmt.Println("Hello!")
}
// Prints "Hello!" three times
Or even simpler, omit the variable entirely:
for range 5 {
fmt.Println("Repeating...")
}
// Prints "Repeating..." five times
All of these accomplish the same thing:
// Using range - cleanest for simple counting
for i := range 5 {
fmt.Println(i)
}
// C-style for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Conditional loop
i := 0
for i < 5 {
fmt.Println(i)
i++
}
The range version is the most concise when you just need to iterate a specific number of times starting from 0.
While this lesson focuses on ranging over integers, range is incredibly versatile and can iterate over:
// Slices
numbers := []int{10, 20, 30}
for index, value := range numbers {
fmt.Println(index, value)
}
// Maps
ages := map[string]int{"Alice": 25, "Bob": 30}
for name, age := range ages {
fmt.Println(name, age)
}
We'll explore these uses in future lessons!
For this challenge, create a function called printSquares that accepts a parameter n (a uint).
The function should:
range to iterate from 0 to n-1The function signature is:
func printSquares(n uint) {
// Your code here
}
For example, calling printSquares(5) should print:
0
1
4
9
16