为什么我的变量不够长寿?

时间:2015-10-22 16:41:27

标签: rust lifetime

我有一段简单的代码,可以通过行

将文件读入矢量
use std::io::{self, Read};
use std::fs::File;

fn file_to_vec(filename: &str) -> Result<Vec<&str>, io::Error> {
    let mut file = try!(File::open(filename));
    let mut string = String::new();
    try!(file.read_to_string(&mut string));
    string.replace("\r", "");

    let data: Vec<&str> = string.split('\n').collect();

    Ok(data)
}

fn main() {}

我收到以下错误:

error[E0597]: `string` does not live long enough
  --> src/main.rs:10:27
   |
10 |     let data: Vec<&str> = string.split('\n').collect();
   |                           ^^^^^^ does not live long enough
...
13 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 4:1...
  --> src/main.rs:4:1
   |
4  | / fn file_to_vec(filename: &str) -> Result<Vec<&str>, io::Error> {
5  | |     let mut file = try!(File::open(filename));
6  | |     let mut string = String::new();
7  | |     try!(file.read_to_string(&mut string));
...  |
12 | |     Ok(data)
13 | | }
   | |_^

为什么我一直收到此错误?我该如何解决?我想它与split方法有关。

我可以返回字符串,然后将其拆分为main函数中的Vec,但我真的想要返回一个向量。

1 个答案:

答案 0 :(得分:5)

问题是在函数中创建了dt1$Mean <- with(dt1, ave(pres==1, walk, date)) ,并在函数返回时被销毁。您要返回的矢量包含 <Button Height="30" Width="200"> <DockPanel> <Image Source="ImagePath"/> <Label Content="Label"/> </DockPanel> </Button> 的切片,但这些切片在您的函数之外无效。

如果您对性能不是非常担心,可以从函数返回string。您只需将类型返回string并更改行

即可
Vec<String>

Result<Vec<String>, io::Error>