I get an error message 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() - 1).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 understand why this is happening, and I can fix it by putting the row value on the inner lambda:
let pair_sums = rows.iter() .flat_map(|row| { (0..row.len() - 1).zip(vec![row; row.len()]) .map(|(i, row)| row[i] + row[i + 1]) }) .collect::<Vec<_>>();
This is terrible and may not be the best solution. How can I refer to variables in the parent scope without having to pass them explicitly?
source share