Rust 使用迭代器适配器简化代码
I/O 项目中其他可以利用迭代器的地方是 search 函数,示例 13-28 中重现了第十二章结尾示例 12-19 中此函数的定义。
原始实现
文件名:src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub filename: String,
}
impl Config {
pub fn new(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let filename = args[2].clone();
Ok(Config { query, filename })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.filename)?;
Ok(())
}
pub <>(query: &, contents: & ) <& > {
= ::();
contents.() {
line.(query) {
results.(line);
}
}
results
}
tests {
super::*;
() {
= ;
= ;
([], (query, contents));
}
}

