为什么要求在读取行中声明BufRead样本的铁 rust [duplicate]

inn6fuwd  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(95)

此问题在此处已有答案

Why do I need to import a trait to use the methods it defines for a type?(1个答案)
昨天关门了。
为什么我们在例子中需要std::io::BufRead,没有它,'lines'将是未定义的方法。
https://riptutorial.com/rust/example/4275/read-a-file-line-by-line

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let filename = "src/main.rs";
    // Open the file in read-only mode (ignoring errors).
    let file = File::open(filename).unwrap();
    let reader = BufReader::new(file);

    // Read the file line by line using the lines() iterator from std::io::BufRead.
    for (index, line) in reader.lines().enumerate() {
        let line = line.unwrap(); // Ignore errors.
        // Show the line and its number.
        println!("{}. {}", index + 1, line);
    }
}
pengsaosao

pengsaosao1#

在留言里

= 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;

这意味着方法lines在trait BufRead中,并且该trait是为BufReader实现的。

相关问题