0

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 の存続期間または借用プロパティについて、ここで私が誤解しているのは何ですか?

4

1 に答える 1