On 10/23/2012 06:52 AM, Henri Sivonen wrote:
In C, Java, JS, etc., using |continue| in a |for| loop evaluates the
update expression before going back to the condition. That is, in a C
|for|, |continue| is a goto to the bottom of the loop and |continue|
in |while| is a goto to right before the condition.
What’s the correct way to write the equivalent of C/Java/JS for loop
in Rust without having to repeat the update expression before each
|loop;| statement (as one would have to when reformulating the loops
as a Rust |while| loop)?
Those kind of counters are typically encapsulated in iterator functions
that can be used with `for` so I guess this doesn't come up often. I'm
assuming you need to do this with `loop` specifically for the HTML
parser (since that is the only looping construct rust is currently
implementing labeled break/continue for).
I don't know a great solution. Maybe it could be put immediately after
the entrance to the loop, but not increment the first time through.
let i = LoopCounter(0, |val| val + 1);
loop {
i.update(); // Doesn't do anything the first time it's called
if i.get() == 10 { loop; }
}
struct LoopCounter<T> {
val: T,
update_fn: &fn(&T) -> T,
first: bool
}
impl<T> LoopCounter<T> {
fn update() {
if self.first { self.first = false }
else { self.val = self.update_fn(&self.val) }
}
}
impl<T: Copy> LoopCounter<T> {
fn get() -> T { copy self.val }
}
It's not pretty, but maybe good enough for transpiling?
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev