TAKOYAKING’s blog 一覧

TAKOYAKING’s blog

たこ焼き系

Rust: use std::io::prelude::*;

Rustでファイル操作をするときにpreludeとuseするのが気になったので、備忘録として残します。

std::io::prelude

std::io::prelude - Rust
よく使用されるioのtraitをimportしてくれる便利なもの

コード

以下のコードはファイルを読み込んでprintする

use std::fs;
use std::path::Path;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;

fn main() {
    cat().unwrap_or_else(|why| panic!(why));
}

fn cat() -> io::Result<()> {
    let path_name = "takoyaki.txt";
    let path = &Path::new(path_name);
    let f = fs::File::open(path)?;
    
    for result in BufReader::new(f).lines() {
        let l = result?;
        println!("{}", l);
    }
    Ok(())
}

これなら問題なく動きます。

もしuse std::io::prelude::*;を記述しなければ以下のようなエラーになる

error[E0599]: no method named `lines` found for struct `std::io::BufReader<std::fs::File>` in the current scope
  --> src/main.rs:17:42
   |
17 |     for (i, result) in BufReader::new(f).lines().enumerate() {
   |                                          ^^^^^ method not found in `std::io::BufReader<std::fs::File>`
   |
   = help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
   |
1  | use std::io::BufRead;
   |

回避方法は以下の2つのうちのどちらかを記述すればOkです。

  • use std::io::prelude::*;
  • use std::io::BufRead;

読み方

プレリュード?