【问题标题】:Lack of lifetime of line from buffered reader prevents splitting line缓冲读取器的线路寿命不足会阻止拆分线路
【发布时间】:2018-08-31 03:33:46
【问题描述】:

我正在努力弄清楚 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>'

"borrowed value does not live long enough" seems to blame the wrong thing 建议生命周期足够长,可以将每个单词放入自己的字符串中,但是修改我在 the Playground 上的原始代码以包含嵌套的 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 的生命周期或借用属性有什么误解?

【问题讨论】:

标签: rust lifetime borrowing


【解决方案1】:

您的原始代码在编译时给出的错误是:

error[E0597]: `ln` does not live long enough
  --> src/main.rs:11:13
   |
11 |             ln.split(' ').collect()
   |             ^^ borrowed value does not live long enough
12 |         };
   |         - `ln` dropped here while still borrowed
13 |     }
   |     - borrowed value needs to live until here

error: aborting due to previous error

根据@shepmasters cmets,最好在发布问题时提供完整的错误信息。

不管怎样,它突出了问题:

let split: Vec<&str> = {
    let ln: String = line.unwrap();
    ln.split(' ').collect()
};

您正在创建一个Vec,其中包含对str 切片的引用;切片不拥有从中切片的数据,它们实际上是指向必须由另一个变量拥有的数据的指针。因此,它们被切片的变量必须比切片的寿命更长。

在您用来初始化Vec 的表达式中,您创建了一个String,其中包含您正在处理的文本行。这个字符串的范围是变量ln 是初始化表达式——一旦你离开这个范围,它就会被删除。

然后你 split 字符串,它返回一个迭代器到字符串切片,每个子字符串一个。但请记住,迭代器返回的是切片,它们是指向Stringln 中的子字符串的指针。这些切片不允许超过ln 本身。

希望您现在可以看到问题所在。一旦退出初始化表达式,ln 就会被删除,但 Vec 仍将包含 str 切片。他们指的是什么?

修复非常简单。为什么要在该块内声明ln?事实上,为什么在那里有一个障碍?这有效:

for line in f.lines() {
    let ln: String = line.unwrap();
    let split: Vec<&str> = ln.split(' ').collect();
    // Now do something with split
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-29
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多