如何让 Rust 的临时值活得更久?

How to make Rust temporary value live longer?

我还在学习 Rust 并且有以下代码。

use std::collections::BTreeMap;

#[derive(Debug)]
struct MyStruct {
    a: String,
    b: String,
}

fn main() {
    let mut hash = BTreeMap::new();

    let data = vec![
        MyStruct {
            a: "entry1".to_string(),
            b: "entry1 body".to_string(),
        },
        MyStruct {
            a: "entry2".to_string(),
            b: "entry2 body".to_string(),
        }
    ];

    let re = regex::Regex::new(r#".(\d)"#).unwrap();
    for item in &data {
        for m in re.captures_iter(&item.b) {
            hash.insert(&m[1].parse::<i32>().unwrap(), &item.a);
        }
    }

    println!("{:#?}", hash);
}

它产生一个错误:

error[E0716]: temporary value dropped while borrowed
  --> src\main.rs:26:26
   |
26 |             hash.insert(&m[1].parse::<i32>().unwrap(), &item.a);
   |             ----         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^          - temporary value is freed at the end of this statement
   |             |            |
   |             |            creates a temporary which is freed while still in use
   |             borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

正确的修复方法是什么?我试图将 &m[1].parse::<i32>().unwrap() 放入变量但无济于事。

BTreeMap 结构应该是插入的数据和键的所有者,或者数据和键应该具有 'static 生命周期(与 HashMap 和其他集合相同)。在这种情况下,使用的键是 i32,它具有为其定义的 Copy 特征,因此只需删除 & 引用即可将 i32 值作为键传入。对于数据,您要么想要克隆字符串而不是 & 借用,但您也可以重写循环以使用 data 向量并传递 item.b 字符串值而不用需要克隆。