为何在Rust逐行读取文件示例中必须声明std::io::BufRead?
为什么示例中必须引入
std::io::BufRead? lines()方法的定义归属:lines()是std::io::BufReadtrait中声明的方法,并非BufReader结构体本身自带的方法。reader.lines()的调用,本质是依赖BufReader对BufReadtrait的实现,才能使用这个trait里的方法。Rust的trait作用域规则:在Rust中,即便某个类型已经实现了某一trait,只要该trait未被引入当前代码的作用域,编译器就无法识别该trait下的方法,进而抛出“未定义方法”的错误。因此必须通过
use std::io::BufRead;将这个trait引入,才能让BufReader实例调用lines()。
示例代码
use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let filename = "src/main.rs"; // 以只读模式打开文件(忽略错误)。 let file = File::open(filename).unwrap(); let reader = BufReader::new(file); // 使用std::io::BufRead中的lines()迭代器逐行读取文件。 for (index, line) in reader.lines().enumerate() { let line = line.unwrap(); // 忽略错误。 // 显示行号与行内容。 println!("{}. {}", index + 1, line); } }
简言之,引入BufRead trait是为了让编译器找到lines()方法的定义,从而允许BufReader实例调用这个逐行读取的方法。
内容的提问来源于stack exchange,提问作者Daniel YC Lin
相关产品推荐
相关产品推荐

