almost finished with ch12.3

This commit is contained in:
2025-02-14 00:05:48 +00:00
parent cef18e5127
commit 4a7a034870
3 changed files with 622 additions and 4 deletions

View File

@ -1,14 +1,97 @@
use std::env;
use std::fs;
use std::process;
use std::error::Error;
fn main() {
let args: Vec<String> = env::args().collect();
// dbg!(args);
let query = &args[1];
let file_path = &args[2];
// let query = &args[1];
// let file_path = &args[2];
println!("Searching for {query}");
println!("In the file {file_path}");
// refactor 1
// let (query, file_path) = parse_config(&args);
// refactor 2
// let config = parse_config(&args)
// refactor 3
// let config = Config::new(&args);
// recfactor 6
let config = Config::build(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {err}");
process::exit(1);
});
println!("Searching for {}", config.query);
println!("In the file {}", config.file_path);
// refactor 7
// // --snip--
// let contents = fs::read_to_string(config.file_path).expect("Should have been able to read the file");
// println!("With text:\n{contents}");
run(config);
}
// refactor 7
fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
println!("With text:\n{contents}")
Ok(())
}
// refactor 3
struct Config {
query: String,
file_path: String,
}
// refactor 1
// fn parse_config(args: &[String]) -> (&str, &str) {
// let query = &args[1];
// let file_path = &args[2];
// (query, file_path)
// }
// refactor 2
// fn parse_config(args: &[String]) -> Config {
// let query = args[1].clone();
// let file_path = args[2].clone();
// Config { query, file_path }
// }
// refactor 3
impl Config {
// // refactor 3
// fn new(args: &[String]) -> Config {
// // refactor 4
// if args.len() < 3 {
// panic!("not enough arguments");
// }
// let query = args[1].clone();
// let file_path = args[2].clone();
// Config { query, file_path }
// }
// refactor 5
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();
Ok(Config { query, file_path })
}
}