3 ms·
IIRC for loops compile down to a while loop with the same body, that drives the given iterator with .next(), until it returns None. Since the .next() implement
by dist1ll 2y ago
IIRC for loops compile down to a while loop with the same body, that drives the given iterator with .next(), until it returns None.
Since the .next() implementation of std::ops::Range is essentially an i++, you'll quickly arrive at a similar representation as classic C for-loop.
- tialaramex 2y agoRust only "really" has one loop, the one named loop. Loop is an infinite loop that you can break out of (using the break keyword of course). All the other syntax, including both "for" and "while" loops and the related but technically different "while let" loop, while useful to humans to communicate intent, aren't semantically different - and so they're transformed early in compilation, they are just "syntax sugar" and are de-sugared into rather elaborate loops with their exit condition now a loop break condition etc. But yes, as in C++ and similar languages, the iterators generate the same machine code as you'd have gotten for writing the C-style for loop from the 1970s, it's just that in Rust you literally can't write that loop.
- bee_rider 2y agoNow I’ve become confused as to what it means for a language to have a thing. Hypothetically if you do for i in 1..10 { println!("{i}"); } (From earlier) the compiler should have enough information to fully unroll the loop if it feels like it. So it is a different syntax from the programmer’s point of view. Maybe it goes through some “this is a loop” stage inside the compiler. But then hypothetically the assembly output could… end up not even having a loop at all (fully unrolled, no jump back, haha).
- steveklabnik 2y agoWhat your parent is saying is that the compiler treats that loop as { let result = match IntoIterator::into_iter(1..10) { mut iter => loop { let next; match iter.next() { Some(val) => next = val, None => break, }; let i = next; let () = { println!("{i}"); }; }, }; result } (95% sure I got that correct) And so in some sense, "loop" is more primitive than "for". > But then hypothetically the assembly output could… end up not even having a loop at all Absolutely, with any of these loops, the compiler may not emit a loop in assembly. And in this case, that seems to be true: https://godbolt.org/z/7Gq69Gvre https://godbolt.org/z/7Gq69Gvre