is there any extra cost on boundary check using for?
Actually, what I mean is to repeat some code.
println!("some code");
println!("some code");
println!("some code");
// code above can fold as
loop 3 {
println!("come code");
};
And what more important is it's more clear than for . @DanielKeep Can I achive this by define loop! macro? as I know macro cannot capture n then repeat special times.
There's no static unrolling. That's an optimisation LLVM will do if it feels it's necessary.
If n is an actual literal, you could do it with a proc macro (which I don't believe are stabilised in function form yet). If it's not a literal, you can't do it.
Just use a for loop unless you can demonstrate that it's actually an issue.
I have already know how many times i need to repeat, so I don't want boundary check.
And, I think for i in 0..n is not clear enough to express repeat n times. For example for i in 1..n+1 do the same thing but express different meaning.
Here, I know that I want to print "Jump" 10 times.... I still have to specify 0-9 aka i < 10. That's just how programming works. Alternatively, I could specify:
Same thing, really. How else can I print jump 10 times aside from either writing a recursive solution or just copy/pasting printf("Jump\n"); into the source-code 10 times???
Sure, I could #define some macro which just pastes printf 10 times, but what's the point?
I'm not sure why this is an issue, and I'd just go with @DanielKeep's suggestions since it's pretty canonical and readable in rust. But just as a basic Rust exercise, here are a couple ways to not care about 0..n vs 1..n+1.
The loopn! (loop is a keyword) you asked for:
macro_rules! loopn {
($n:expr, $body:block) => {
for _ in 0..$n {
$body
}
}
}
Alternatively, a helper function supporting an iterator-based approach:
I strongly encourage getting used to ..'s half-openness -- it's far better in algorithms because it splits elegantly: if you divide low..high into low..mid and mid..high, you have all the same items with no overlap and no error-prone ±1 adjustments. This has been known since at least 1982: E.W. Dijkstra Archive: Why numbering should start at zero (EWD 831)
I was offering the inclusive range as an alternative to adding 1 on both sides. Personally, I wouldn't add 1 in the first place, and would stick to the exclusive range.