上次实现的grep功能基本OK,基本流程是: 读取命令行参数 --> 放到数组中 --> clone数组中的参数,用来新建Config类型实例。
现在使用迭代器进行优化,Config::new直接接收一个迭代器。然后返回一个Config类型实例。
还有search功能的实现,我们是新建一个mutable数组,然后将符合条件的&str插入数组中。最后返回这个数组。
在函数式编程的思想中,我们要尽量减少mutable状态,这样使得代码更加清晰,而且有利于后面的并发增强。
考虑使用Iterator Adaptor返回一个新的迭代器来实现。
impl Config {
pub fn new(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(args) => args,
None => return Err("Lack of query string"),
};
let filename = match args.next() {
Some(args) => args,
None => return Err("Lack of filename string"),
};
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config{query, filename, ignore_case})
}
}
fn main() {
let config = Config::new(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parse arguments: {}", err);
process::exit(1);
});
//snip
}
pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
content.lines()
.filter(|x| x.contains(query)).collect()
}
同理:search_case_insentisive()也一样修改。
最终代码如下
use std::env;
use std::process;
use minigrep::Config;
fn main() {
let config = Config::new(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parse arguments: {}", err);
process::exit(1);
});
println!("query: {}, filename: {}", config.query, config.filename);
if let Err(e) = minigrep::run(config) {
eprintln!("Application Error: {}", e);
process::exit(1);
}
}
use std::error::Error;
use std::fs;
use std::env;
pub struct Config {
pub query: String,
pub filename: String,
pub ignore_case: bool,
}
impl Config {
pub fn new(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(args) => args,
None => return Err("Lack of query string"),
};
let filename = match args.next() {
Some(args) => args,
None => return Err("Lack of filename string"),
};
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config{query, filename, ignore_case})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let content = fs::read_to_string(config.filename)?;
// println!("With text:\n{}", content);
let result = if config.ignore_case {
search_case_insensitive(&config.query, &content)
} else {
search(&config.query, &content)
};
for line in result {
println!("{}", line);
}
Ok(())
}
pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
content.lines()
.filter(|x| x.contains(query)).collect()
}
pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
let query = query.to_lowercase();
content.lines()
.filter(|x| {
x.to_lowercase().contains(&query)
}).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "xwp";
let content = "\
Hello,rust!
xwp is handsome
You know!";
assert_eq!(vec!["xwp is handsome"], search(query, content));
}
#[test]
fn case_insensitive() {
let query = "xWp";
let content = "\
Hello,rust!
xwp is handsome
You KonW";
assert_eq!(vec!["xwp is handsome"], search_case_insensitive(query, content));
}
}