错误[E0597]:借用的值在While循环中的寿命不足

问题描述 投票:0回答:2

我对Rust真的很陌生,我很难解决这个错误,但是只有在注释掉while语句时才会发生,基本上我是从控制台询问值并将其存储在HashMap中:

use std::collections::HashMap;
use std::io;

fn main() {
    let mut customers = HashMap::new();
    let mut next_customer = true;
    while next_customer {
        let mut input_string = String::new();
        let mut temp_vec = Vec::with_capacity(3);
        let mut vec = Vec::with_capacity(2);
        println!("Insert new customer f.e = customer id,name,address:");
        io::stdin().read_line(&mut input_string);
        input_string = input_string.trim().to_string();
        for s in input_string.split(",") {
            temp_vec.push(s);
        }
        vec.push(temp_vec[1]);
        vec.push(temp_vec[2]);
        let mut key_value = temp_vec[0].parse::<i32>().unwrap();
        customers.insert(key_value, vec);
        next_customer = false;
    }
    println!("DONE");
}

代码导致错误

error[E0597]: `input_string` does not live long enough
  --> src/main.rs:14:18
   |
14 |         for s in input_string.split(",") {
   |                  ^^^^^^^^^^^^ borrowed value does not live long enough
...
20 |         customers.insert(key_value, vec);
   |         --------- borrow later used here
21 |         next_customer = false;
22 |     }
   |     - `input_string` dropped here while still borrowed
rust
2个回答
0
投票

问题是您传递了对将被删除的基础&str值的引用。一种方法是取出输入字符串,修剪并分割,然后将其克隆到另一个向量中。


0
投票

正如其他人所说,问题在于要放入客户映射中的值的生存期和/或类型。

© www.soinside.com 2019 - 2024. All rights reserved.