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

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

Barbara Streisand
Release: 2024-12-11 14:52:17
Original
632 people have browsed it

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)
}
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template