Home > Backend Development > Golang > How to Iterate Over Integer Ranges in Go?

How to Iterate Over Integer Ranges in Go?

Mary-Kate Olsen
Release: 2024-12-08 05:39:14
Original
1044 people have browsed it

How to Iterate Over Integer Ranges in Go?

Iterating Over Integer Ranges in Go

The Go language provides the range keyword to iterate over maps and slices. This powerful feature enables developers to efficiently traverse collections. However, what if you need to iterate over a range of integers?

Go's Recent Solution (Go 1.22 and Above)

As of Go 1.22, Go introduced an elegant solution to iterate over integer ranges:

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

This syntax iterates over integers from 0 to 9. Note that it excludes the value equal to the integer specified (in this case, 10).

Pre-Go 1.22 Solution: Idiomatic For Loop

For versions of Go before 1.22, the established approach is to use a traditional for loop:

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

This loop iterates over the integers from 1 to 10, inclusive.

The above is the detailed content of How to Iterate Over Integer Ranges in Go?. For more information, please follow other related articles on the PHP Chinese website!

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