Lately, I've noticed how python loops with range are extremely simple and powerful.
What if we expand capabilities of using go loops with range?
for v := range 25 {} // no key here can be assigned It goes from 0 to 25.
for v := range 1:25 {} It goes from 1 to 25.
There’s a package that allows you do to exactly this: github.com/bradfitz/iter.
Seems like we can do that today using
for v := range [26]struct{}
for v := range [26]struct{}[1]
A bit awkward, yes, but if we're going to extend for/range it's not clear that these are the specific steps we want to take.
There’s a package that allows you do to exactly this: github.com/bradfitz/iter.
How often got this package by various other packages imported?
IIRC Python's range function doesn't include the end value so range(25) only goes up to 24 which can be confusing. However, it can do steps by including an additional parameter.
Personally, I prefer the traditional C-style for statement for numerical ranges:
for v := 0; v < 25; v++ {}
It's always clear what it's doing and, if the need arises, it has various fancy tricks up its sleeve such as multiple iteration variables with different steps.
Re multiple iteration variables #30917
It would be good to provide a step option too:
for v := range 1:25:2 {} It goes from 1,3,5,7 to 25.
Some language including BASIC does have a to keyword which is understood, it may have been explored or not a popular keyword in Go.
for v := 0 to 25 {}
@proyb6 looks great. Fine by me. I would go with that as well, but range should be included
How does Swift do it?
How does Swift do it?
Like this:
// includes end point, implicit step of 1
for i in 0...25 {}
// excludes end point, implicit step of 1
for i in 0..<25 {}
// includes end point, explicit step of 2
for i in stride(from: 0, through: 25, by: 2) {}
// excludes end point, explicit step of 2
for i in stride(from: 0, to: 25, by: 2) {}
For some unfathomable reason, they got rid of the traditional C-style for loop in version 3.0 and ended up with the above verbosity to do a simple step!
EDIT: Sorry, I originally had the last two versions the wrong way around but I've now corrected it. Just demonstrates how clear they are.
Most helpful comment
IIRC Python's
rangefunction doesn't include the end value sorange(25)only goes up to 24 which can be confusing. However, it can do steps by including an additional parameter.Personally, I prefer the traditional C-style
forstatement for numerical ranges:It's always clear what it's doing and, if the need arises, it has various fancy tricks up its sleeve such as multiple iteration variables with different steps.