Rust Lang Book Ch.12 An I/O Project: Building a Command Line Program
src/lib.rs
use std::error::Error; use std::fs; struct Config { pub query: String, pub filename: String, pub case_sensitive: bool, } impl Config { fn new(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments");//返回string literal,所以可以用'static,也就是说生成了之后就一直有效 } let query = args[1].clone(); let filename = args[2].clone(); // CASE_INSENSITIVE=1时为true let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); Ok(Config { query, filename }) } } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } fn run(config: Config) -> Result<(), Box<dyn Error>> { //Box<dyn Error> 返回一个能够实现Error特性的类型 dyn: dynamic let contents = fs::read_to_string(config.filename)?;//错误传递 let results = if config.case_sensitive { search(&config.query, &contents) } else { search_case_insensitive(&config.query, &contents) };//if{}else{}是一个expression for line in results { println!("{}", line); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } }
src/main.rs
use std::env; use std::process; use minigrep::Config; fn main() { let args: Vec<String> = env::args().collect(); //std::env::args如果接收到invalid Unicode就会panic。如果包含这样的字符,可以使用std::env::args_os来代替,用OsString来兼容这些字符 let config = Config::new(&args).unwrap_or_else(|err| {
//如果static string "not enough arguments"作为err这个变量被返回了,那就执行接下来的逻辑 eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); println!("Searching for {}", config.query); println!("In file {}", config.filename); if let Err(e) = run(config) { eprintln!("Application error: {}", e); process::exit(1); } }