After reading the official Rust book, I plan to convert my tiny Nim chess game to Rust over Christmas holiday. The chess game uses many named range constants with for loops. In Nim we can write
# named range example
const Launch = 1 .. 9
proc main =
for t in Launch:
echo t
echo "Go!"
main()
which prints the numbers 1 to 9 and finally "Go!".
// Named range equivalent in Rust
const LAUNCH: (i32, i32) = (1, 10); // In Rust, the end of the range is exclusive
fn main() {
for t in LAUNCH.0..LAUNCH.1 {
println!("{}", t);
}
println!("Go!");
}
or
const LAUNCH_START: i32 = 1;
const LAUNCH_END: i32 = 10; // Exclusive
fn main() {
for t in LAUNCH_START..LAUNCH_END {
println!("{}", t);
}
println!("Go!");
}
Great. I was indeed looking for such a simple solution, but was not able to find it in the book, or other resources. Actually I tried something similar, but I guess I used an invalid syntax. Would the solution from 2e71828 with the explicit iterator offer some extra benefit?
Well if you need the .rev() then you have to do it like @2e71828, because a std::iter::Rev cannot be constant initialized, meaning you can't use it in a const context.
And maybe it is a bit more clear in @2e71828 's version that you get a new Iterator each time you call the function. At least for me it wasn't immediatly clear what would happen with the constant.