错误[E0597]:借来的值在While循环中存活的时间不够长 [英] error[E0597]: borrowed value does not live long enough in While loop

查看:31
本文介绍了错误[E0597]:借来的值在While循环中存活的时间不够长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am really new to Rust, I am having trouble solving this error, but it only happens if I comment out the while statement , basicly I am asking values from the console and storing it in a 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

推荐答案

正如其他人所说,问题在于放入客户地图的值的生命周期和/或类型.

As others have said the problem lies with the lifetime and/or type of the values getting put into the customers map.

customers.insert(key_value, vec);
   |         --------- borrow later used here

当编译器决定给一个对象一个你没有预料到的类型时,通常会发生这种情况.要了解它在做什么,您可以强制类型,并查看它如何抱怨.将代码更改为:

Often this happens when the compiler has decided to give an object a type that you didn't expect. To find out what it's doing you can force the type, and see how it complains. Changing the code to:

    let mut customers: HashMap<(),()> = HashMap::new();

给我们两个相关的错误:

Gives us two relevant errors:

20 |         customers.insert(key_value, vec);
   |                          ^^^^^^^^^ expected `()`, found `i32`
...
20 |         customers.insert(key_value, vec);
   |                                     ^^^ expected `()`, found struct `std::vec::Vec`
   |
   = note: expected unit type `()`
                 found struct `std::vec::Vec<&str>`

所以编译器想要给我们的客户对象的类型是 HashMap

So the type that the compiler wants to give our customers object is HashMap<i32, Vec<&str>>

问题是 &str 生命周期必须在块内,因为我们没有将 String 存储在任何地方,而且它们不能有'static 生命周期,因为它们是用户输入.

The problem is that the &str lifetime has got to be inside the block as we don't store the Strings anywhere, and they can't have 'static lifetime since they're user input.

这意味着我们可能需要一个 HashMap>.

This means we probably want a HashMap<i32,Vec<String>>.

更改代码以使用其中之一会给我们一个关于 vec 没有正确类型的错误:它被推导出为 Vec<&str>,但是我们想要一个 Vec.

Changing the code to use one of those gives us an error about vec not having the right type: It's getting deduced as a Vec<&str>, but we want a Vec<String>.

我们有两个选择.

  1. 在我们使用 customers.insert(key_value, vec.iter().map(|s| s.to_string()).collect 将 vec 插入地图之前,将其转换为正确的类型()).(尽管为了清楚起见,您可能希望将其提取为变量).

  1. Convert the vec to the right type just before we insert it into the map using customers.insert(key_value, vec.iter().map(|s| s.to_string()).collect()). (Though you may want to extract it to a variable for clarity).

明确将vec的类型改为Vec

Explicitly change the type of vec to Vec<String>

选项 1有效".虽然选项 2 使我们走上了一条越来越接近 read_line 调用的类似更改的道路.

Option 1 "just works". While option 2 leads us down a path of making similar changes closer and closer to the read_line call.

决定选项 1 中的修复后,如果您发现它们过于嘈杂,您可以删除为解决此问题而添加的手动类型注释.

Once you've decided on the fix in option 1, you can remove the manual type annotations that were added to work out the fix, if you find them overly noisy.

这篇关于错误[E0597]:借来的值在While循环中存活的时间不够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆