我有一段简单的代码,可以按行将文件读入矢量
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() {}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
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 | | }
| |_^
Run Code Online (Sandbox Code Playgroud)
为什么我一直收到这个错误?我该如何解决?我想这与split方法有关.
我可以返回字符串然后将其拆分为Vecmain函数中的a,但我真的想要返回一个向量.
问题是string在函数中创建,并在函数返回时被销毁.要返回的向量包含切片string,但这些切片在函数外部无效.
如果您对性能不是非常担心,可以Vec<String>从功能中返回.您只需返回类型Result<Vec<String>, io::Error>并更改该行
let data: Vec<&str> = string.split('\n').collect();
Run Code Online (Sandbox Code Playgroud)
至
let data: Vec<String> = string.split('\n').map(String::from).collect();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
991 次 |
| 最近记录: |