Home >Backend Development >Golang >Can Go's `range` Keyword Iterate Over Integer Ranges?

Can Go's `range` Keyword Iterate Over Integer Ranges?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 14:52:17633browse

Can Go's `range` Keyword Iterate Over Integer Ranges?

Ranging Over Integers in Go

Go's range keyword efficiently iterates over data structures like maps and slices. However, can it be used to iterate over a range of integers?

Question:

Is it possible to iterate over a range of numbers in Go using a syntax similar to:

for i := range [1..10] {
    fmt.Println(i)
}

Or is there a method like Ruby's Range class to represent ranges of integers?

Answer:

As of Go 1.22 (anticipated release in February 2024), you can achieve this using a simplified approach:

for i := range 10 {
    fmt.Println(i + 1)
}

It's important to note that ranging over an integer in Go iterates from 0 to one less than that integer.

Prior to Go 1.22, the standard approach was to use a traditional for loop:

for i := 1; i <= 10; i++ {
    fmt.Println(i)
}

This loop iterates from 1 to 10, inclusive.

The above is the detailed content of Can Go's `range` Keyword Iterate Over Integer Ranges?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn