From b7dd584bca69dc729d77b11b6a8378b8be0af647 Mon Sep 17 00:00:00 2001 From: 53hornet <53hornet@gmail.com> Date: Mon, 25 Feb 2019 21:15:40 -0500 Subject: Added lifetimes; split code into library for minigrep. --- minigrep/src/lib.rs | 29 +++++++++++++++++++++++++++++ minigrep/src/main.rs | 38 +++++++++----------------------------- 2 files changed, 38 insertions(+), 29 deletions(-) create mode 100644 minigrep/src/lib.rs (limited to 'minigrep/src') 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 { + + 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> { + 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 = 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 { - - 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); } - } + -- cgit v1.2.3