【问题标题】:How to make Rust temporary value live longer?如何让 Rust 临时值活得更久?
【发布时间】:2021-05-29 14:58:14
【问题描述】:

我还在学习 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

修复它的正确方法是什么?我尝试将&amp;m[1].parse::&lt;i32&gt;().unwrap() 放入变量中,但无济于事。

【问题讨论】:

  • 简单;不要借它! hash.insert(m[1].parse::&lt;i32&gt;().unwrap(), &amp;item.a);

标签: rust borrow-checker


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多