玩弄铁 rust ,陷入一个基本的分配错误。
下面是我的代码:
fn parse_file_lines(filename: &str) -> Vec<&str> {
let mut file_lines: Vec<&str> = Vec::new();
if let Ok(lines) = read_lines(filename) {
lines.for_each(|line| match line {
Ok(l) => {
// perform some logic here...
file_lines.push(&l)
}
Err(_) => todo!(),
})
}
return file_lines;
}
fn read_lines(filename: &str) -> io::Result<io::Lines<io::BufReader<File>>> {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
返回此编译器错误:
error[E0597]: `l` does not live long enough
--> src/main.rs:17:38
|
14 | let mut file_lines: Vec<&str> = Vec::new();
| -------------- lifetime `'1` appears in the type of `file_lines`
...
17 | Ok(l) => file_lines.push(&l),
| ----------------^^-
| | | |
| | | `l` dropped here while still borrowed
| | borrowed value does not live long enough
| argument requires that `l` is borrowed for `'1`
我知道我的scopes are off,但不知道为什么-这是漫长的一天🥹
谢谢!
1条答案
按热度按时间dgjrabp21#
std::io::Lines
生成拥有的String
,而不是借用的&str
,因此您不能删除它们并将对它们的引用存储在Vec
中。而是将拥有的
String
存储在Vec
: