rustHow do you reverse a range in Rust?
Reversing a range in Rust is done using the rev()
method. This method takes an iterator and returns an iterator that yields the same elements in reverse order.
Example code
let mut range = 0..10;
let reversed_range = range.rev();
for x in reversed_range {
println!("{}", x);
}
Output example
9
8
7
6
5
4
3
2
1
0
Code explanation
let mut range = 0..10;
: This creates a range from 0 to 10.let reversed_range = range.rev();
: This creates a reversed range from 10 to 0 using therev()
method.for x in reversed_range {
: This iterates over the reversed range.println!("{}", x);
: This prints the current element of the reversed range.
Helpful links
More of Rust
- How to match the end of a line in a Rust regex?
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to use an enum in a Rust HashMap?
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to get an entry from a HashSet in Rust?
- How to modify an existing entry in a Rust HashMap?
- How to replace strings using Rust regex?
See more codes...