summaryrefslogtreecommitdiff
path: root/minigrep/src
diff options
context:
space:
mode:
author53hornet <53hornet@gmail.com>2019-02-25 21:15:40 -0500
committer53hornet <53hornet@gmail.com>2019-02-25 21:15:40 -0500
commitb7dd584bca69dc729d77b11b6a8378b8be0af647 (patch)
treee9460283f474d53961bddefb2e684f9b20516c74 /minigrep/src
parenta0070916ef13387461a11bb26d5c798b07121165 (diff)
downloadlearning-rust-b7dd584bca69dc729d77b11b6a8378b8be0af647.tar.xz
learning-rust-b7dd584bca69dc729d77b11b6a8378b8be0af647.zip
Added lifetimes; split code into library for minigrep.
Diffstat (limited to 'minigrep/src')
-rw-r--r--minigrep/src/lib.rs29
-rw-r--r--minigrep/src/main.rs38
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);
}
-
}
+