此问题在此处已有答案:
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);
}
}
1条答案
按热度按时间pengsaosao1#
在留言里
这意味着方法
lines
在traitBufRead
中,并且该trait是为BufReader
实现的。