I am getting an error inside a nested lambda.
let rows = vec![
vec![3, 6, 2, 8, 9, 0],
vec![0, 0, 1, 4, 5, 1],
];
let pair_sums = rows.iter()
.flat_map(|row| {
(0 ..= row.len()).map(|i| row[i] + row[i + 1])
})
.collect::<Vec<_>>();
println!("{:?}", pair_sums);
error[E0597]: `row` does not live long enough
--> src/main.rs:9:40
|
9 | (0..row.len() - 1).map(|i| row[i] + row[i + 1])
| --- ^^^ does not live long enough
| |
| capture occurs here
10 | })
| - borrowed value only lives until here
11 | .collect::<Vec<_>>();
| - borrowed value needs to live until here
I can sort of see why this is happening, and I can fix it by threading the value of row
through to the inner lambda:
let pair_sums = rows.iter()
.flat_map(|row| {
(0 ..= row.len()).zip(iter::repeat(row))
.map(|(i, row)| row[i] + row[i + 1])
})
.collect::<Vec<_>>();
This is horrible and can't be the best solution. How can I refer to variables in a parent scope without having to pass them along explicitly?