by Pxtl · 3y ago · 0 comments
Like (pseudocode)
var i = 0
for(item in items) {
item.DoThing(i)
i+=1
}
Does rust not allow that kind of mutation and access of a variable from outside the loop within the loop?https://play.rust-lang.org/?version=stable&mode=debug&editio...
struct Item(u32);
impl Item {
fn do_thing(&self, i: usize) {
println!("The value of `i` is: {i}");
}
}
fn main() {
let items = vec![Item(1), Item(2), Item(3)];
for (i, item) in items.iter().enumerate() {
item.do_thing(i);
}
}I think what they were pointing out (and I agree with) is that the mixing of combinators and imperative-style for loops that's going on in the post doesn't feel very natural. Typically if you would _either_ do
blah
.into_iter()
.filter(|x| x.some_condition())
.for_each(|x| x.do_something());
or for x in blah {
if !x.some_condition() {
continue;
}
x.do_something();
}
But `for x in blah.into_iter().filter(...` is a bit unusual. let mut i = 0;
for item in items {
item.method(i);
i += 1;
}
I don't know why you'd it that way, but Rust definitely isn't stopping you from doing that.e: and as running example: https://play.rust-lang.org/?version=stable&mode=debug&editio...
Compare all the crazy things people build out of channels in go, or a similar tendency in python to over-do the generator expressions.
lol 3 people said the same thing at the same time. rust strike force assemble