我有一段简单的代码,应该按行将文件读入向量
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
,但我真的想返回一个向量。
最佳答案
问题是 string
在您的函数中创建,并在函数返回时销毁。您要返回的向量包含 string
的切片,但这些在您的函数之外将无效。
如果您不是很担心性能,您可以返回 Vec<String>
从你的功能。您只需将类型返回到 Result<Vec<String>, io::Error>
并更改行
let data: Vec<&str> = string.split('\n').collect();
到
let data: Vec<String> = string.split('\n').map(String::from).collect();
关于rust - 为什么我的变量生命周期不够长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33286213/