关于参考:借来的价值在循环中的寿命不够长

borrowed value does not live long enough in loop

我正在尝试解析文件并从函数返回 Vec<Vec<&str>>。但是在推送到向量时,我在文件读取循环中遇到了借用值错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use std::io::{self, BufReader, prelude::*};
use std::fs::File;

fn read() -> Vec<Vec<&'static str>> {
 let file = File::open("~/test").expect("failed to read file");
 let reader = BufReader::new(file);
 let mut main_vector: Vec<Vec<&str>> = Vec::new();
    for line in reader.lines() {
        match line {
            Ok(v) => {
                let mut sub_vector: Vec<&str> = Vec::new();
                for element in v.split_whitespace().collect::<Vec<&str>>() {
                    sub_vector.push(element);
                }
                main_vector.push(sub_vector);
            },
            Err(e) => panic!("failed to parse: {:?}", e),
        }
    }
    //return main_vector;
}

这是编译器错误:

1
2
3
4
5
6
7
8
9
10
error[E0597]: `v` does not live long enough
  --> src/main.rs:67:32
   |
67 |                 for element in v.split_whitespace().collect::<Vec<&str>>() {
   |                                ^ borrowed value does not live long enough
...
70 |                 main_vector.push(sub_vector);
   |                 -------------- borrow later used here
71 |             },
   |              - `v` dropped here while still borrowed

我认为这是关于参考和借用,但我仍然很难弄清楚这一点。


n


如果提供更多代码会更好,但我试图重现它并得到这个工作片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
type Error = i32;

struct Reader
{
    lines: Vec<Result<String, Error>>
}

impl Reader
{
    pub fn new() -> Self
    {
        Self{lines: vec![Ok("foo".into()), Ok("bar".into())]}
    }

    pub fn lines(&self) -> &[Result<String, Error>]
    {
        &self.lines
    }
}

fn main() {
    let reader = Reader::new();
    let mut main_vector: Vec<Vec<&str>> = Vec::new();
    for line in reader.lines() {
        match line {
            Ok(v) => {
                let mut sub_vector: Vec<&str> = Vec::new();
                for element in v.split_whitespace().collect::<Vec<&str>>() {
                    sub_vector.push(element);
                }
                main_vector.push(sub_vector);
            },
            Err(e) => panic!("failed to parse: {:?}", e),
        }
    }
}

你可以在 Rust Playground 上查看 https://play.rust-lang.org/?version=stable