At work someone ran into an issue that surprised them with Python. This prints "message 2" three times:
funs_to_execute = []
for i in range(3):
funs_to_execute.append(lambda: print(f"message {i}"))
for fun in funs_to_execute:
fun()
I've written very little rust but I have been interested to start learning it. I decided to see what this code might look like in rust:
fn main() {
let mut vec = Vec::new();
for i in 0..3 {
vec.push(|| println!("message {}", i));
}
for fun in vec.iter() {
fun();
}
}
Which of course fails to compile because it can identify that the i
in the capture "does not live long enough".
In Python the fix is typically something like this:
funs_to_execute = []
for i in range(3):
funs_to_execute.append(lambda i=i: print(f"message {i}"))
for fun in funs_to_execute:
fun()
So we essentially save off the value of i
for each iteration by having it be set to the default value of an argument of the lambda.
My question is: How would you fix this Rust code to print "message 0", "message 1", "message 2"? I tried a few things and I wasn't able to figure it out.