【问题标题】:Why does my variable not live long enough?为什么我的变量寿命不够长?
【发布时间】:2016-01-22 00:54:54
【问题描述】:

我有一段简单的代码应该按行将文件读入向量

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 方法有关。

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

【问题讨论】:

    标签: rust lifetime


    【解决方案1】:

    问题是string是在你的函数中创建的,当函数返回时会被销毁。您要返回的向量包含 string 的切片,但这些切片在您的函数之外无效。

    如果您并不十分担心性能,您可以从您的函数中返回一个Vec&lt;String&gt;。您只需将类型返回到Result&lt;Vec&lt;String&gt;, io::Error&gt; 并更改行

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

    let data: Vec<String> = string.split('\n').map(String::from).collect();
    

    【讨论】:

    • 谢谢,我知道这将是微不足道的。我想您也必须在最后一行将 Vec 类型更改为 String。
    • @ehsisthatsweird 你说得对,我错过了。顺便说一句,这里不需要类型注释,类型推断可以处理这种情况。
    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2018-12-20
    • 2019-05-04
    • 2015-05-26
    • 1970-01-01
    • 2017-10-16
    相关资源
    最近更新 更多