我正在阅读command line applications in rust这本书,并尝试着做一些练习。
问题::我想使用BufReader
而不是read_to_string()
读取内存中文件的内容,但是我对如何使用它感到困惑。
错误消息: no method named read_lines found for type std::io::BufReader<&std::path::PathBuf> in the current scope
,这很有意义。在哪里可以找到BufReader
切线问题:BufReader
是一个类还是仅仅是一个由new
关键字构造的对象,例如javascript
?
use std::env;
use std::io::BufReader;
use structopt::StructOpt;
#[derive(StructOpt)]
struct Cli {
/// the pattern to look for
pattern: String,
/// the path to the file to read
#[structopt(parse(from_os_str))]
path: std::path::PathBuf,
}
fn help() {
println!(
"usage:
this is just a dummy help
message to see how functions work in rust"
);
}
fn main() {
let args = Cli::from_args();
// [NOTE]: This works
// [ ] Ex:2 Use BufReader instead of read_to_string()
let content = std::fs::read_to_string(&args.path).expect("Could not read file");
for line in content.lines() {
if line.contains(&args.pattern) {
println!("{:#?}", line);
}
}
// [NOTE]: What I am trying to do:
let mut reader = BufReader::new(&args.path);
// .expect("could not read file");
for line in reader.read_lines() {
if line.contains(&args.pattern) {
println!("{:#?}", line);
}
}
}