5 ms·
For literals, clippy will catch this by default: error: this range is empty so it will yield no values --> src/main.rs:2:9 | 2 | let x = 5..0; |
by estebank 6y ago
For literals, clippy will catch this by default:
error: this range is empty so it will yield no values
--> src/main.rs:2:9
|
2 | let x = 5..0;
| ^^^^
|
= note: `#[deny(clippy::reversed_empty_ranges)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#reversed_empty_ranges
help: consider using the following if you are attempting to iterate over this range in reverse
|
2 | let x = (0..5).rev();
| ^^^^^^^^^^^^
- pornel 6y agoMay be worth moving to rustc, because that's not just bad style, that's incorrect code.
- estebank 6y agoI don't disagree but it feels like the bulk of the likely problema would be when not dealing with literals.
- rtpg 6y agoI disagree, sometimes you end up building empty ranges in your code for valid reasons (as a result of math, for example). special casing a check on literals feels a bit like saying you can create an empty non-mutable vector.
- baby 6y agoI disagree, if this happens you want to document these edge-cases by failing early, this is very bad code if you don't and let the loop happen when most reviewers would have no idea if the result would be an unexpected behavior or not.
- estebank 6y agoIf I had a need for that I would write a surprised snake (0..0) instead.
- carlmr 6y agoExactly. (5..0) is almost surely a developer that expects the range 5, 4, 3, 2, 1
- auggierose 6y agoThis tripped me up a few times in Swift in the beginning, when I did a range `lowerBound ..< higherBound`, or `lowerBound ... higherBound`, and assuming that in those cases where actually `lowerBound > higherBound`, which can often happen naturally, it would default to the empty range. Still think empty range would be the sensible thing here, but at least Swift throws an exception, so after an initial wtf it wasn't a problem.