diff options
Diffstat (limited to 'minigrep/src')
-rw-r--r-- | minigrep/src/lib.rs | 29 | ||||
-rw-r--r-- | minigrep/src/main.rs | 38 |
2 files changed, 38 insertions, 29 deletions
diff --git a/minigrep/src/lib.rs b/minigrep/src/lib.rs new file mode 100644 index 0000000..78610ba --- /dev/null +++ b/minigrep/src/lib.rs @@ -0,0 +1,29 @@ +use std::error::Error; +use std::fs; + +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("Not enough arguments."); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + Ok(Config { query, filename }) + } + +} + +pub fn run(config: Config) -> Result<(), Box<dyn Error>> { + let contents = fs::read_to_string(config.filename)?; + dbg!(contents); + Ok(()) +} + diff --git a/minigrep/src/main.rs b/minigrep/src/main.rs index 1e04b5e..fc5ae9a 100644 --- a/minigrep/src/main.rs +++ b/minigrep/src/main.rs @@ -1,6 +1,8 @@ use std::process; use std::env; -use std::fs; + +use minigrep; +use minigrep::Config; fn main() { let args: Vec<String> = env::args().collect(); @@ -8,33 +10,11 @@ fn main() { println!("Problem parsing arguments: {}", err); process::exit(1); }); - - println!("Searching for {}", config.query); - println!("In file {}", config.filename); - - let contents = fs::read_to_string(config.filename) - .expect("something went wrong."); - - dbg!(contents); -} - -struct Config { - query: String, - filename: String, -} - -impl Config { - - - fn new(args: &[String]) -> Result<Config, &'static str> { - - if args.len() < 3 { - panic!("not enough args"); - } - - let query = args[1].clone(); - let filename = args[2].clone(); - Ok(Config { query, filename }) + println!("\nSearching for {}", config.query); + println!(" in file {}", config.filename); + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + process::exit(1); } - } + |