I have a data structure consisting of 3 levels of collections which I want to flatten:
use std::collections::HashMap;
struct Model {
fields: HashMap<String, Vec<Field>>,
}
struct Field {
field_type: String,
info: Vec<FieldInfo>,
}
struct FieldInfo {
pub info: String,
pub value: f64,
}
fn do_action(model: &Model) {
let _flattened: Vec<&dyn std::marker::Sync> = (&model.fields)
.into_iter()
.flat_map(|fields| {
let v: Vec<&dyn std::marker::Sync> = fields
.1
.iter()
.flat_map(|field| {
let v: Vec<&dyn std::marker::Sync> = field
.info
.iter()
.flat_map(|field_info| {
let vec: Vec<&dyn std::marker::Sync> = vec![
&fields.0,
&field.field_type,
&field_info.info,
&field_info.value,
];
vec
})
.collect();
v
})
.collect();
v
})
.collect();
}
I got the following error message when trying to compile the code:
error[E0373]: closure may outlive the current function, but it borrows `fields`, which is owned by the current function
--> src/lib.rs:24:27
|
24 | .flat_map(|field| {
| ^^^^^^^ may outlive borrowed value `fields`
...
30 | &fields.0,
| ------ `fields` is borrowed here
|
note: closure is returned here
--> src/lib.rs:41:13
|
41 | v
| ^
help: to force the closure to take ownership of `fields` (and any other referenced variables), use the `move` keyword
|
24 | .flat_map(move |field| {
| ^^^^^^^^^^^^
The suggested solution with move
closure does not work in my case. What would be a workaround?