借值读线,生锈编程后寿命不足

问题描述

嗨,我一直在寻找这个问题的答案,但是我找不到真正相似的东西:我正在尝试使用用户从命令行输入的字符串来调整字符串向量的大小,但是编译器告诉我,存储字符串的变量超出范围。这是代码

fn add_employee(h: &mut HashMap<&str,Vec<&str>>) {
    println!("Choose a department:");
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    for (key,value) in h {
        if key.to_string() == input {              // idk why but with input it works
            println!("Enter a name to add to this department:");
            let mut name = String::new();
            io::stdin()
                .read_line(&mut name)
                .expect("Failed to read line");
            value.resize(&value.len() + 1,&name); //here is where i get an error on the 
        }                                          //name variable saying it's out of scope
        input.clear();
    }
}

解决方法

首先,我们不要仅仅为了找到所需的条目而对整个HashMap进行迭代-这是非常昂贵的,并且完全破坏了HashMap的目的:您最好还是持有{{ 1}}对!请改用HashMap::get_mut

(key,val)

接下来,无需显式调整其大小即可插入向量中

if let Some(value) = h.get_mut(input.as_str()) {
    ...
}

最后,我们要把什么推到向量上?类型签名建议使用字符串切片value.push(...); ,但这些仅仅是寿命有限的借用。但是,我们已阅读的&str仅存在于内存中,直到声明它的作用域的末尾(name块)为止,然后将其丢弃。如果要将借位存储在向量中,则基础值必须在内存中保留的时间至少与向量一样长。

您更有可能要将 owned 字符串值(即if)推入向量中-但这将涉及更改类型签名:

String