接收命令行参数
/** 用于读取命令行参数的库 */
use std::env; //collect
fn main() {
let args: Vec<String> = env::args().collect();
println!("{:#?}", args);
let query: &String =&args[1];
let filename:&String=&args[2];
println!("Searching for {} in {}", query, filename);
}
详细代码
lib.rs
use std::error::Error;
use std::fs;
pub fn run(config: Config)->Result<(),Box<dyn Error>>{
let contents = fs::read_to_string(config.filename)?;
for line in search(&config.query,&contents){
println!("{}",line);
}
// println!("With the contents: {}", contents);
Ok(())
}
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("没有足够的参数")
}
let query = args[1].clone();
let filename=args[2].clone();
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
}
#[cfg(test)]
mod tests{
use super::*;
#[test]
fn one_result(){
let query="duct";
let contents="\\
Rust:\\
safe,fast,productive.
Pick Three.";
assert_eq!(vec!["safe,fast,productive."],search(query,contents));
}
}
main.rs
/** 用于读取命令行参数的库 */
use minigrep::Config;
use std::env; //collect
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let config =Config::new(&args).unwrap_or_else(|err| {
println!("{}", err);
process::exit(1);
});
if let Err(e) = minigrep::run(config){
print!("{}","无法读取文件内容");
process::exit(1);
}
}
TDD开发