使用flat_map将数据结构的三个级别展平为特征对象向量时,“关闭可能会超过当前函数的寿命”

问题描述

我有一个数据结构,该结构由3个要展平的集合级别组成:

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();
}

Playground

尝试编译代码时收到以下错误消息:

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| {
   |                           ^^^^^^^^^^^^

在我的情况下,建议的move闭包解决方案不起作用。有什么解决方法

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)