创建项目
创建一个名称为minigrep的项目
cargo new minigrep
编写代码
测试文件文件
Youth is not a time of life; it is a state of mind;
it is not a matter of rosy cheeks, red lips and supple knees;
it is a matter of the will, a quality of the imagination, a vigor of the emotions;
it is the freshness of the deep springs of life.
main.rs文件内容
use std::env;
use std::process;
use minigrep::Config;
fn main() {
let args: Vec<String> = env::args().collect(); // 获取用户的输入
let config = Config::build(&args).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}"); // 输出错误到标准错误输出
process::exit(1); // 退出程序,返回码为1
});
if let Err(e) = minigrep::run(config) { // 匹配返回的错误
eprintln!("Application error: {e}"); // 输出错误到标准错误输出
process::exit(1);
}
}
lib.rs内容
use std::error::Error;
use std::fs;
use std::env;
pub struct Config {
pub query: String, // 搜索的字符串
pub file_path: String, // 打开的文件
pub ignore_case: bool, // 是否开启大小写敏感
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments"); // 参数小于三个报错
}
let query = args[1].clone(); // 获取搜索的字符串
let file_path = args[2].clone(); // 获取要打开的文件
let ignore_case = env::var("IGNORE_CASE").is_ok(); // 从环境变量中获取是否开启大小写敏感, is_ok有值返回true,没有返回false
Ok(Config {query, file_path, ignore_case})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> { // 使用特征对象返回错误
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
// 大小写敏感的搜索函数
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
}
// 编写一个测试用例
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "safe";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[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)
);
}
}
项目目录结构
测试
大小写敏感
➜ minigrep git:(master) ✗ cargo run -- Deep test.txt
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/minigrep Deep test.txt
大小写不敏感
➜ minigrep git:(master) ✗ IGNORE_CASE=1 cargo run -- Deep test.txt
Compiling minigrep v0.1.0 (/Users/tang/rust_project/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.85s
Running `target/debug/minigrep Deep test.txt`
it is the freshness of the deep springs of life.