3 ms·
It's actually better if you have immutability here, languages which try to instead have a single variable for the values, mutating that variable each time aroun
by tialaramex 4y ago
It's actually better if you have immutability here, languages which try to instead have a single variable for the values, mutating that variable each time around the loop, get into some trouble.
Compare Rust's for loop:
for k in 0..10 {
// k is an immutable variable, brought into existence for one iteration
// next time around the loop that's a different immutable k
}
Versus the C for loop:
for (k = 0; k < 10; ++k) {
// k is a long-lived mutable variable, we can change k inside the loop and it'll remember!
}
We can tell Rust we want a mutable variable, if we want, but it's not the same:
for mut k in 0..10 {
// k is a mutable variable...
// but still brought into existence for each iteration
// changing will work in this scope... but it won't last
}
- widforss 4y agoCool, I didn't know that Rust did that (or have forgotten)! But it sure looks like a map where we throw away the result. What I mean with that is that the loop construct must be served the iterations from an iterator, which may or may not use immutable data. I don't think you can make an immutable while loop, for example? EDIT: Also, you better have a side-effect in that construct, otherwise it has no effect, right?