我正在努力弄清楚 Rust 的借贷/终身/所有权属性。即,当使用缓冲读取器并尝试拆分行时。编码
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let f = File::open("foo.txt").expect("file not found");
let f = BufReader::new(f);
for line in f.lines() {
let split: Vec<&str> = {
let ln: String = line.unwrap();
ln.split(' ').collect()
};
}
}
或任何变化(有或没有指定变量类型,徒劳的尝试使其可变等)导致:
'ln' does not live long enough; borrowed value must only be valid for the static lifetime...
但试图假装延长寿命并通过切片从线路中获取一些数据
let nm = line;
name = &line[..];
甚至只是尝试对split()
未修改的行变量进行操作会导致:
cannot index into a value of type 'std::result::Result<std::string::String, std::io::Error>'
“借来的价值不够长”似乎归咎于错误的事情表明生命周期持续足够长以将每个单词放入自己的字符串中,但是修改我在操场上的原始代码以包含嵌套的 for 循环仍然会导致
error[E0597]: borrowed value does not live long enough
--> src/main.rs:11:18
|
11 | for w in line.unwrap().split_whitespace() {
| ^^^^^^^^^^^^^ temporary value does not live long enough
...
14 | }
| - temporary value dropped here while still borrowed
15 | }
| - temporary value needs to live until here
|
= note: consider using a `let` binding to increase its lifetime
在参考line.unwrap()
最终,我在这里对 Rust 的生命周期或借用属性有什么误解?