LoginSignup
1
0

More than 5 years have passed since last update.

Rustのイテレーターさっぱり分からん☆(^~^)

Last updated at Posted at 2019-03-31

ファイルの先頭行だけ読みたいというときに

for result in BufReader::new(File::open("test.txt").unwrap()).lines() {
    let first_line = result.unwrap();
    println!("Read line: `{}`.", first_line);
    return first_line;
}

みたいな感じでループを回そうものなら、このループは1回しか実行されないと clippy に指摘されてしまう。
だったら どうすればいいのか?

if let Some(first_line_result) = BufReader::new(File::open("text.txt").unwrap()).lines().next() {
    let first_line = first_line_result.unwrap();
    println!("Read first line: `{}`.", first_line);
    first_line
} else {
    "".to_string()
}

.lines() というのが Iterator を返すようなので、ループに渡す代わりに .next() を1回だけ実行すればいいのか。
イテレーターの使い方とか 必修だな。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0