Home > Backend Development > Golang > How Do I Iterate Over a Range of Integers in Go?

How Do I Iterate Over a Range of Integers in Go?

Mary-Kate Olsen
Release: 2024-12-10 02:07:13
Original
605 people have browsed it

How Do I Iterate Over a Range of Integers in Go?

Iterating over a Range of Integers in Go

Iterating over data structures like maps and slices is straightforward in Go, but what if you want to traverse a sequence of integers? Is there a built-in mechanism or a way to emulate something like Ruby's Range class in Go?

Range over Integers from Go 1.22

Starting with Go version 1.22 (slated for release in February 2024), you can conveniently iterate over a range of integers using the following syntax:

for i := range 10 {
    fmt.Println(i + 1) // Ranging over an integer iterates from 0 to one less than that integer.
}
Copy after login

Idiomatic Approach for Prior Versions of Go

For Go versions before 1.22, the traditional way to iterate over a range of integers is to construct a manual loop:

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

This loop achieves the same functionality as the range-over syntax introduced in Go 1.22.

The above is the detailed content of How Do I Iterate Over a Range of Integers in Go?. 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