From 45598760187d2c71e47a854940db5cd4f8c2d454 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sat, 10 Dec 2016 14:08:03 -0500 Subject: [PATCH 01/25] Start code for the I/O project chapter --- src/SUMMARY.md | 2 +- src/ch12-00-an-io-project.md | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 src/ch12-00-an-io-project.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 06a3ab8dd..a61d2c99c 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -55,7 +55,7 @@ - [Running tests](ch11-02-running-tests.md) - [Test Organization](ch11-03-test-organization.md) -- [I/O]() +- [An I/O Project](ch12-00-an-io-project.md) - [`Read` & `Write`]() - [`std::fs`]() - [`std::path`]() diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md new file mode 100644 index 000000000..548a8f8af --- /dev/null +++ b/src/ch12-00-an-io-project.md @@ -0,0 +1,35 @@ +# An I/O Project + +`cargo new --bin greprs` + +Project requirements: + +- Take a search string and a filename as command line arguments +- Read the file +- Find lines in the file that contain the search string +- Print out those lines + +In order to do a good job, we will: + +- Organize code (using what we learned in modules, ch 7) +- Use strings (collections, ch 8) +- Handle errors (ch 9) +- Have tests (ch 11) + +Generics/traits/lifetimes? + +## Command line arguments + +* Use `std::env::args()` + +Filename: src/main.rs + +```rust +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + println!("{:?}", args); +} +``` + From dea608d34912514b35c9cab685f24fbd16111528 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sat, 10 Dec 2016 15:13:57 -0500 Subject: [PATCH 02/25] Make a few steps of adding on to the project --- src/ch12-00-an-io-project.md | 252 ++++++++++++++++++++++++++++++++++- 1 file changed, 251 insertions(+), 1 deletion(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 548a8f8af..357e97836 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -12,7 +12,7 @@ Project requirements: In order to do a good job, we will: - Organize code (using what we learned in modules, ch 7) -- Use strings (collections, ch 8) +- Use vectors and strings (collections, ch 8) - Handle errors (ch 9) - Have tests (ch 11) @@ -33,3 +33,253 @@ fn main() { } ``` +Run it with various arguments. The binary is the first argument: + +```text +$ cargo run + Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) + Finished debug [unoptimized + debuginfo] target(s) in 0.39 secs + Running `target/debug/greprs` +["target/debug/greprs"] + +$ cargo run needle haystack +...snip... +["target/debug/greprs", "needle", "haystack"] +``` + +Discard the binary name, next argument is the search string, next argument is +the filename we want to search in: + + + +Filename: src/main.rs + +```rust +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + + let search = args.get(1).expect( + "No search string or filename found. Usage: greprs " + ); + let filename = args.get(2).expect( + "No filename found. Usage: greprs " + ); + + println!("Searching for {}", search); + println!("In file {}", filename); +} +``` + +Trying it out: + +```text +$ cargo run +thread 'main' panicked at 'No search string or filename found. Usage: greprs ', ../src/libcore/option.rs:705 + +$ cargo run needle +thread 'main' panicked at 'No filename found. Usage: greprs ', ../src/libcore/option.rs:705 + +$ cargo run needle haystack +Searching for needle +In file haystack +``` + +## Reading a file + +File to search in: + +Filename: poem.txt + +```text +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us — don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! +``` + + + +Filename: src/main.rs + +```rust +use std::env; +use std::io::prelude::*; +use std::fs::File; + +fn main() { + let args: Vec = env::args().collect(); + + let search = args.get(1).expect( + "No search string or filename found. Usage: greprs " + ); + let filename = args.get(2).expect( + "No filename found. Usage: greprs " + ); + + println!("Searching for {}", search); + println!("In file {}", filename); + + let mut f = File::open(filename).expect("Could not open file."); + let mut contents = String::new(); + f.read_to_string(&mut contents).expect("Could not read file"); + + println!("With text:\n{}", contents); +} +``` + +```text +$ cargo run test poem.txt + Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) + Finished debug [unoptimized + debuginfo] target(s) in 0.36 secs + Running `target/debug/greprs test poem.txt` +Searching for test +In file poem.txt +With text: +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us — don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! +``` + +## Tests + +Make a src/lib.rs and start some tests. + +We want a function that will take a search term and contents, and return a +vector of lines from the contents that contain the search term. + + + +File: src/lib.rs + +```rust +pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + vec![] +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn one_result() { + let search = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!( + vec!["safe, fast, productive."], + grep(search, contents) + ); + } +} +``` + +```text +$ cargo test + Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) +...warnings... + Finished debug [unoptimized + debuginfo] target(s) in 0.43 secs + Running target/debug/deps/greprs-917c5edfc3cf199a + +running 1 test +test test::one_result ... FAILED + +failures: + +---- test::one_result stdout ---- + thread 'test::one_result' panicked at 'assertion failed: `(left == right)` (left: `["safe, fast, productive."]`, right: `[]`)', src/lib.rs:16 +note: Run with `RUST_BACKTRACE=1` for a backtrace. + + +failures: + test::one_result + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured + +error: test failed +``` + +Get the test passing: + +File: src/lib.rs + +```rust +pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = vec![]; + + for line in contents.lines() { + if line.contains(search) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn one_result() { + let search = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!( + vec!["safe, fast, productive."], + grep(search, contents) + ); + } +} +``` + +```text +$ cargo test + Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) + Finished debug [unoptimized + debuginfo] target(s) in 0.56 secs + Running target/debug/deps/greprs-917c5edfc3cf199a + +running 1 test +test test::one_result ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured + + Running target/debug/greprs-2f55ee8cd1721808 + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured + + Doc-tests greprs + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured +``` + From ce0853df16490e8209ac1c3edc84c90f99caac55 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sat, 10 Dec 2016 15:17:15 -0500 Subject: [PATCH 03/25] Hook together main and lib --- src/ch12-00-an-io-project.md | 41 ++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 357e97836..0ce67d566 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -283,3 +283,44 @@ running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured ``` +## Call the function from main + +Filename: src/main.rs + +```rust +extern crate greprs; + +use std::env; +use std::io::prelude::*; +use std::fs::File; + +fn main() { + let args: Vec = env::args().collect(); + + let search = args.get(1).expect( + "No search string or filename found. Usage: greprs " + ); + let filename = args.get(2).expect( + "No filename found. Usage: greprs " + ); + + let mut f = File::open(filename).expect("Could not open file."); + let mut contents = String::new(); + f.read_to_string(&mut contents).expect("Could not read file"); + + let results = greprs::grep(search, &contents); + + for line in results { + println!("{}", line); + } +} +``` + +```text +$ cargo run the poem.txt + Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) + Finished debug [unoptimized + debuginfo] target(s) in 0.38 secs + Running `target/debug/greprs the poem.txt` +Then there's a pair of us — don't tell! +To tell your name the livelong day +``` From 31eeae8be05fcc2f8487b900a99f75f5bd5d8cb6 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sat, 10 Dec 2016 15:57:05 -0500 Subject: [PATCH 04/25] Ignore code blocks that won't pass mdbook test --- src/ch12-00-an-io-project.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 0ce67d566..109845ba8 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -59,7 +59,7 @@ Should we do a match so that when someone gives Filename: src/main.rs -```rust +```rust,ignore use std::env; fn main() { @@ -116,7 +116,7 @@ welcome. /Carol --> Filename: src/main.rs -```rust +```rust,ignore use std::env; use std::io::prelude::*; use std::fs::File; @@ -287,7 +287,7 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured Filename: src/main.rs -```rust +```rust,ignore extern crate greprs; use std::env; From 0ae9662c704b1f9ede2c52020eb0d9c15e3478b7 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sun, 11 Dec 2016 11:52:55 -0500 Subject: [PATCH 05/25] Remove cargo build output --- src/ch12-00-an-io-project.md | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 109845ba8..8ccb9a672 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -37,9 +37,6 @@ Run it with various arguments. The binary is the first argument: ```text $ cargo run - Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) - Finished debug [unoptimized + debuginfo] target(s) in 0.39 secs - Running `target/debug/greprs` ["target/debug/greprs"] $ cargo run needle haystack @@ -144,9 +141,6 @@ fn main() { ```text $ cargo run test poem.txt - Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) - Finished debug [unoptimized + debuginfo] target(s) in 0.36 secs - Running `target/debug/greprs test poem.txt` Searching for test In file poem.txt With text: @@ -199,7 +193,6 @@ Pick three."; ```text $ cargo test - Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) ...warnings... Finished debug [unoptimized + debuginfo] target(s) in 0.43 secs Running target/debug/deps/greprs-917c5edfc3cf199a @@ -261,10 +254,6 @@ Pick three."; ```text $ cargo test - Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) - Finished debug [unoptimized + debuginfo] target(s) in 0.56 secs - Running target/debug/deps/greprs-917c5edfc3cf199a - running 1 test test test::one_result ... ok @@ -318,9 +307,6 @@ fn main() { ```text $ cargo run the poem.txt - Compiling greprs v0.1.0 (file:///Users/carolnichols/rust/greprs) - Finished debug [unoptimized + debuginfo] target(s) in 0.38 secs - Running `target/debug/greprs the poem.txt` Then there's a pair of us — don't tell! To tell your name the livelong day ``` From 0e74058c3849c0d48da6094da120fd9f22e17193 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 13 Dec 2016 09:15:35 -0500 Subject: [PATCH 06/25] Add code that uses an env var to do case insensitive search --- src/ch12-00-an-io-project.md | 133 ++++++++++++++++++++++++++++++++++- 1 file changed, 131 insertions(+), 2 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 8ccb9a672..10f272467 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -8,6 +8,7 @@ Project requirements: - Read the file - Find lines in the file that contain the search string - Print out those lines +- Have an environment variable setting to search without regards to case In order to do a good job, we will: @@ -50,8 +51,6 @@ the filename we want to search in: Filename: src/main.rs @@ -217,6 +216,9 @@ error: test failed Get the test passing: + + File: src/lib.rs ```rust @@ -310,3 +312,130 @@ $ cargo run the poem.txt Then there's a pair of us — don't tell! To tell your name the livelong day ``` + +## Working with Environment Variables + +### Implement a Case-Insensitive `grep` Function + +Filename: src/lib.rs + +```rust +pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = vec![]; + + for line in contents.lines() { + if line.contains(search) { + results.push(line); + } + } + + results +} + +pub fn grep_case_insensitive<'a>(search: &str, contents: &'a str) + -> Vec<&'a str> { + let mut results = vec![]; + let search = search.to_lowercase(); + + for line in contents.lines() { + if line.to_lowercase().contains(&search) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn case_sensitive() { + let search = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!( + vec!["safe, fast, productive."], + grep(search, contents) + ); + } + + #[test] + fn case_insensitive() { + let search = "rust"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + grep_case_insensitive(search, contents) + ); + } +} +``` + +### Have `main` Check the Environment Variable + +Filename: src/main.rs + +```rust,ignore +extern crate greprs; + +use std::env; +use std::io::prelude::*; +use std::fs::File; + +fn main() { + let args: Vec = env::args().collect(); + + let mut case_sensitive = true; + for (var, _) in env::vars() { + if var == "CASE_INSENSITIVE" { + case_sensitive = false; + } + } + + let search = args.get(1).expect( + "No search string or filename found. Usage: greprs " + ); + let filename = args.get(2).expect( + "No filename found. Usage: greprs " + ); + + let mut f = File::open(filename).expect("Could not open file."); + let mut contents = String::new(); + f.read_to_string(&mut contents).expect("Could not read file"); + + let results = if case_sensitive { + greprs::grep(search, &contents) + } else { + greprs::grep_case_insensitive(search, &contents) + }; + + for line in results { + println!("{}", line); + } +} +``` + +```text +$ cargo run to poem.txt +Are you nobody, too? +How dreary to be somebody! +``` + +```text +$ CASE_INSENSITIVE=1 cargo run to poem.txt +Are you nobody, too? +How dreary to be somebody! +To tell your name the livelong day +To an admiring bog! +``` From c59a629d9ae0bf0747e5bfb9a817411336d925dc Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 13 Dec 2016 09:55:51 -0500 Subject: [PATCH 07/25] Demonstrate output to stderr --- src/ch12-00-an-io-project.md | 142 +++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 10f272467..bb3f0cfc0 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -439,3 +439,145 @@ How dreary to be somebody! To tell your name the livelong day To an admiring bog! ``` + +## Write to `stderr` Instead of `stdout` + +Let's say we want to output statistics about how many lines have matched to `stderr`. + +Filename: src/main.rs + +```rust +extern crate greprs; + +use std::env; +use std::io::prelude::*; +use std::fs::File; + +fn main() { + let args: Vec = env::args().collect(); + + let mut stderr = std::io::stderr(); + + let mut case_sensitive = true; + for (var, _) in env::vars() { + if var == "CASE_INSENSITIVE" { + case_sensitive = false; + } + } + + let search = args.get(1).expect( + "No search string or filename found. Usage: greprs " + ); + let filename = args.get(2).expect( + "No filename found. Usage: greprs " + ); + + let mut f = File::open(filename).expect("Could not open file."); + let mut contents = String::new(); + f.read_to_string(&mut contents).expect("Could not read file"); + + let contents: Vec<&str> = contents.lines().collect(); + + let total_lines = contents.len(); + + let results = if case_sensitive { + greprs::grep(search, &contents) + } else { + greprs::grep_case_insensitive(search, &contents) + }; + + let matching_lines = results.len(); + + writeln!( + &mut stderr, + "{}/{} lines matched", + matching_lines, + total_lines + ).expect("Could not write to stderr"); + + for line in results { + println!("{}", line); + } +} +``` + +Filename: src/lib.rs + +```rust +pub fn grep<'a>(search: &str, contents: &[&'a str]) -> Vec<&'a str> { + let mut results = vec![]; + + for &line in contents { + if line.contains(search) { + results.push(line); + } + } + + results +} + +pub fn grep_case_insensitive<'a>(search: &str, contents: &[&'a str]) + -> Vec<&'a str> { + let mut results = vec![]; + let search = search.to_lowercase(); + + for &line in contents { + if line.to_lowercase().contains(&search) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn case_sensitive() { + let search = "duct"; + let contents: Vec<&str> = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape.".lines().collect(); + + assert_eq!( + vec!["safe, fast, productive."], + grep(search, &contents) + ); + } + + #[test] + fn case_insensitive() { + let search = "rust"; + let contents: Vec<&str> = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me.".lines().collect(); + + assert_eq!( + vec!["Rust:", "Trust me."], + grep_case_insensitive(search, &contents) + ); + } +} +``` + +Output: + +```text +$ cargo run to poem.txt +2/9 lines matched +Are you nobody, too? +How dreary to be somebody! +``` + +Redirecting stdout to a file, stderr still gets displayed: + +```text +$ cargo run to poem.txt > new_poem.txt +2/9 lines matched +``` From 245204cd1342ab787e21771ab65dd9c51984e6ff Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 13 Dec 2016 10:17:12 -0500 Subject: [PATCH 08/25] Have to ignore the mains --- src/ch12-00-an-io-project.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index bb3f0cfc0..504a2ecfb 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -446,7 +446,7 @@ Let's say we want to output statistics about how many lines have matched to `std Filename: src/main.rs -```rust +```rust,ignore extern crate greprs; use std::env; From f1257ec9b78c110cffbbc182193806820decc088 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 13 Dec 2016 15:31:30 -0500 Subject: [PATCH 09/25] Rework the examples using iterator methods --- src/ch12-00-an-io-project.md | 185 ++++++++++++++++------------------- 1 file changed, 83 insertions(+), 102 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 504a2ecfb..ab3a26e92 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -21,7 +21,13 @@ Generics/traits/lifetimes? ## Command line arguments -* Use `std::env::args()` +To get the arguments passed to the binary, use `std::env::args()`. This +function returns an *iterator*. We're going to use a bunch of iterators and +useful functions on them in this chapter, and chapter 16 will go into depth on +how iterators work. + +We can see all the items in the iterator by collecting them into a vector and +printing it out using debug formatting: Filename: src/main.rs @@ -45,13 +51,14 @@ $ cargo run needle haystack ["target/debug/greprs", "needle", "haystack"] ``` -Discard the binary name, next argument is the search string, next argument is -the filename we want to search in: +What we want to do is: - +We'll ignore any arguments after that, and we'll error if we don't get enough +arguments. Filename: src/main.rs @@ -59,12 +66,16 @@ Filename: src/main.rs use std::env; fn main() { - let args: Vec = env::args().collect(); + let mut args = env::args(); - let search = args.get(1).expect( + // Discard the name of the binary + args.next(); + + // `next` returns an `Option` + let search = args.next().expect( "No search string or filename found. Usage: greprs " ); - let filename = args.get(2).expect( + let filename = args.next().expect( "No filename found. Usage: greprs " ); @@ -73,7 +84,7 @@ fn main() { } ``` -Trying it out: +Try it out with no arguments, one argument, and two arguments: ```text $ cargo run @@ -118,12 +129,16 @@ use std::io::prelude::*; use std::fs::File; fn main() { - let args: Vec = env::args().collect(); + let mut args = env::args(); - let search = args.get(1).expect( + // Discard the name of the binary + args.next(); + + // `next` returns an `Option` + let search = args.next().expect( "No search string or filename found. Usage: greprs " ); - let filename = args.get(2).expect( + let filename = args.next().expect( "No filename found. Usage: greprs " ); @@ -214,24 +229,19 @@ test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured error: test failed ``` -Get the test passing: +Get the test passing by: - +1. Getting an iterator over each line of the contents with the `lines` function +2. Use the `filter` method and specify the condition a line should meet in + order to pass through the filter. +3. The condition is that the line contains the search string +4. Collect the results of the filtered iterator into a vector and return it File: src/lib.rs ```rust pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = vec![]; - - for line in contents.lines() { - if line.contains(search) { - results.push(line); - } - } - - results + contents.lines().filter(|line| line.contains(search)).collect() } #[cfg(test)] @@ -286,12 +296,16 @@ use std::io::prelude::*; use std::fs::File; fn main() { - let args: Vec = env::args().collect(); + let mut args = env::args(); - let search = args.get(1).expect( + // Discard the name of the binary + args.next(); + + // `next` returns an `Option` + let search = args.next().expect( "No search string or filename found. Usage: greprs " ); - let filename = args.get(2).expect( + let filename = args.next().expect( "No filename found. Usage: greprs " ); @@ -299,7 +313,7 @@ fn main() { let mut contents = String::new(); f.read_to_string(&mut contents).expect("Could not read file"); - let results = greprs::grep(search, &contents); + let results = greprs::grep(&search, &contents); for line in results { println!("{}", line); @@ -321,29 +335,15 @@ Filename: src/lib.rs ```rust pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = vec![]; - - for line in contents.lines() { - if line.contains(search) { - results.push(line); - } - } - - results + contents.lines().filter(|line| line.contains(search)).collect() } pub fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = vec![]; let search = search.to_lowercase(); - - for line in contents.lines() { - if line.to_lowercase().contains(&search) { - results.push(line); - } - } - - results + contents.lines().filter(|line| { + line.to_lowercase().contains(&search) + }).collect() } #[cfg(test)] @@ -394,8 +394,6 @@ use std::io::prelude::*; use std::fs::File; fn main() { - let args: Vec = env::args().collect(); - let mut case_sensitive = true; for (var, _) in env::vars() { if var == "CASE_INSENSITIVE" { @@ -403,17 +401,19 @@ fn main() { } } - let search = args.get(1).expect( + let mut args = env::args(); + + // Discard the name of the binary + args.next(); + + // `next` returns an `Option` + let search = args.next().expect( "No search string or filename found. Usage: greprs " ); - let filename = args.get(2).expect( + let filename = args.next().expect( "No filename found. Usage: greprs " ); - let mut f = File::open(filename).expect("Could not open file."); - let mut contents = String::new(); - f.read_to_string(&mut contents).expect("Could not read file"); - let results = if case_sensitive { greprs::grep(search, &contents) } else { @@ -454,21 +454,22 @@ use std::io::prelude::*; use std::fs::File; fn main() { - let args: Vec = env::args().collect(); - let mut stderr = std::io::stderr(); - let mut case_sensitive = true; - for (var, _) in env::vars() { - if var == "CASE_INSENSITIVE" { - case_sensitive = false; - } - } + let case_insensitive = env::vars().find(|&(ref var, _)| { + var == "CASE_INSENSITIVE" + }).is_some(); - let search = args.get(1).expect( + let mut args = env::args(); + + // Discard the name of the binary + args.next(); + + // `next` returns an `Option` + let search = args.next().expect( "No search string or filename found. Usage: greprs " ); - let filename = args.get(2).expect( + let filename = args.next().expect( "No filename found. Usage: greprs " ); @@ -476,23 +477,17 @@ fn main() { let mut contents = String::new(); f.read_to_string(&mut contents).expect("Could not read file"); - let contents: Vec<&str> = contents.lines().collect(); - - let total_lines = contents.len(); - - let results = if case_sensitive { - greprs::grep(search, &contents) + let results = if case_insensitive { + greprs::grep_case_insensitive(&search, &contents) } else { - greprs::grep_case_insensitive(search, &contents) + greprs::grep(&search, &contents) }; let matching_lines = results.len(); - writeln!( &mut stderr, - "{}/{} lines matched", - matching_lines, - total_lines + "{} lines matched", + matching_lines ).expect("Could not write to stderr"); for line in results { @@ -504,30 +499,16 @@ fn main() { Filename: src/lib.rs ```rust -pub fn grep<'a>(search: &str, contents: &[&'a str]) -> Vec<&'a str> { - let mut results = vec![]; - - for &line in contents { - if line.contains(search) { - results.push(line); - } - } - - results +pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + contents.lines().filter(|line| line.contains(search)).collect() } -pub fn grep_case_insensitive<'a>(search: &str, contents: &[&'a str]) +pub fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = vec![]; let search = search.to_lowercase(); - - for &line in contents { - if line.to_lowercase().contains(&search) { - results.push(line); - } - } - - results + contents.lines().filter(|line| { + line.to_lowercase().contains(&search) + }).collect() } #[cfg(test)] @@ -537,30 +518,30 @@ mod test { #[test] fn case_sensitive() { let search = "duct"; - let contents: Vec<&str> = "\ + let contents = "\ Rust: safe, fast, productive. Pick three. -Duct tape.".lines().collect(); +Duct tape."; assert_eq!( vec!["safe, fast, productive."], - grep(search, &contents) + grep(search, contents) ); } #[test] fn case_insensitive() { let search = "rust"; - let contents: Vec<&str> = "\ + let contents = "\ Rust: safe, fast, productive. Pick three. -Trust me.".lines().collect(); +Trust me."; assert_eq!( vec!["Rust:", "Trust me."], - grep_case_insensitive(search, &contents) + grep_case_insensitive(search, contents) ); } } From a52ff4465f27cc9da1e37cf60f086ea777eb5b7f Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 13 Dec 2016 16:00:49 -0500 Subject: [PATCH 10/25] Push more logic into lib instead of main --- src/ch12-00-an-io-project.md | 349 ++++++++++++++++++----------------- 1 file changed, 176 insertions(+), 173 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index ab3a26e92..45ba59108 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -15,10 +15,9 @@ In order to do a good job, we will: - Organize code (using what we learned in modules, ch 7) - Use vectors and strings (collections, ch 8) - Handle errors (ch 9) +- Use traits and lifetimes where appropriate (ch 10) - Have tests (ch 11) -Generics/traits/lifetimes? - ## Command line arguments To get the arguments passed to the binary, use `std::env::args()`. This @@ -53,17 +52,24 @@ $ cargo run needle haystack What we want to do is: -1. Discard the binary name -2. Get the search string, which will be in the next argument -3. Get the filename we want to search in as the next argument +1. Discard the binary name that will always be the first argument +2. Collect the rest of the arguments and store them in a configuration struct +3. Pass the configuration to a `run` function that returns a `Result` +4. If there were errors, print information about them and exit with 1. -We'll ignore any arguments after that, and we'll error if we don't get enough -arguments. +The reason we want to have a `run` function in `src/lib.rs` is that it will +make it easier to write tests and pass in different configurations, without +having to actually run our binary from the command line. Filename: src/main.rs ```rust,ignore +extern crate greprs; + +use greprs::Config; + use std::env; +use std::process; fn main() { let mut args = env::args(); @@ -71,16 +77,42 @@ fn main() { // Discard the name of the binary args.next(); - // `next` returns an `Option` - let search = args.next().expect( - "No search string or filename found. Usage: greprs " - ); - let filename = args.next().expect( - "No filename found. Usage: greprs " - ); + let config = Config { + arguments: args.collect(), + }; + + if let Err(e) = greprs::run(config) { + println!("Application error: {}", e); + process::exit(1); + } +} +``` + +The code in `src/lib.rs` now needs to define a `Config` struct and a `run` +function. The `run` function in `src/lib.rs` will: + +1. Get the search string, which will be in the next argument +2. Get the filename we want to search in as the next argument + +This function will ignore any arguments after that, and will return an error if +it doesn't get enough arguments. + +Filename: src/lib.rs + +```rust +pub struct Config { + pub arguments: Vec, +} + +pub fn run(config: Config) -> Result<(), String> { + let mut args = config.arguments.iter(); + + let search = args.next().ok_or("No search string or filename found")?; + let filename = args.next().ok_or("No filename found")?; println!("Searching for {}", search); println!("In file {}", filename); + Ok(()) } ``` @@ -88,10 +120,10 @@ Try it out with no arguments, one argument, and two arguments: ```text $ cargo run -thread 'main' panicked at 'No search string or filename found. Usage: greprs ', ../src/libcore/option.rs:705 +Application error: No search string or filename found $ cargo run needle -thread 'main' panicked at 'No filename found. Usage: greprs ', ../src/libcore/option.rs:705 +Application error: No filename found $ cargo run needle haystack Searching for needle @@ -121,35 +153,32 @@ short, but that has multiple lines and some repetition. We could search through code; that gets a bit meta and possibly confusing... Changes to this are most welcome. /Carol --> -Filename: src/main.rs +Filename: src/lib.rs -```rust,ignore -use std::env; -use std::io::prelude::*; +```rust use std::fs::File; +use std::io::prelude::*; +use std::error::Error; -fn main() { - let mut args = env::args(); +pub struct Config { + pub arguments: Vec, +} - // Discard the name of the binary - args.next(); +pub fn run(config: Config) -> Result<(), Box> { + let mut args = config.arguments.iter(); - // `next` returns an `Option` - let search = args.next().expect( - "No search string or filename found. Usage: greprs " - ); - let filename = args.next().expect( - "No filename found. Usage: greprs " - ); + let search = args.next().ok_or("No search string or filename found")?; + let filename = args.next().ok_or("No filename found")?; println!("Searching for {}", search); println!("In file {}", filename); - let mut f = File::open(filename).expect("Could not open file."); + let mut f = File::open(filename)?; let mut contents = String::new(); - f.read_to_string(&mut contents).expect("Could not read file"); + f.read_to_string(&mut contents)?; println!("With text:\n{}", contents); + Ok(()) } ``` @@ -171,23 +200,24 @@ To an admiring bog! ## Tests -Make a src/lib.rs and start some tests. +Start some tests in *src/lib.rs*. We want a function that will take a search term and contents, and return a -vector of lines from the contents that contain the search term. +vector of lines from the contents that contain the search term. Here's a +failing test: File: src/lib.rs ```rust -pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { vec![] } #[cfg(test)] mod test { - use super::*; + use grep; #[test] fn one_result() { @@ -229,7 +259,7 @@ test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured error: test failed ``` -Get the test passing by: +We're going to get the test passing by: 1. Getting an iterator over each line of the contents with the `lines` function 2. Use the `filter` method and specify the condition a line should meet in @@ -284,40 +314,40 @@ running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured ``` -## Call the function from main +## Call the `grep` function from the `run` function -Filename: src/main.rs +Filename: src/lib.rs -```rust,ignore -extern crate greprs; - -use std::env; -use std::io::prelude::*; +```rust use std::fs::File; +use std::io::prelude::*; +use std::error::Error; -fn main() { - let mut args = env::args(); +pub struct Config { + pub arguments: Vec, +} - // Discard the name of the binary - args.next(); +pub fn run(config: Config) -> Result<(), Box> { + let mut args = config.arguments.iter(); - // `next` returns an `Option` - let search = args.next().expect( - "No search string or filename found. Usage: greprs " - ); - let filename = args.next().expect( - "No filename found. Usage: greprs " - ); + let search = args.next().ok_or("No search string or filename found")?; + let filename = args.next().ok_or("No filename found")?; - let mut f = File::open(filename).expect("Could not open file."); + let mut f = File::open(filename)?; let mut contents = String::new(); - f.read_to_string(&mut contents).expect("Could not read file"); + f.read_to_string(&mut contents)?; - let results = greprs::grep(&search, &contents); + let results = grep(&search, &contents); for line in results { println!("{}", line); } + + Ok(()) +} + +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + contents.lines().filter(|line| line.contains(search)).collect() } ``` @@ -329,7 +359,11 @@ To tell your name the livelong day ## Working with Environment Variables -### Implement a Case-Insensitive `grep` Function +Enhancement we want to add: allow the user of our program to set an environment +variable in their terminal session to do searches that match on case exactly or +not. + +### Implement and Test a Case-Insensitive `grep` Function Filename: src/lib.rs @@ -348,7 +382,7 @@ pub fn grep_case_insensitive<'a>(search: &str, contents: &'a str) #[cfg(test)] mod test { - use super::*; + use {grep, grep_case_insensitive}; #[test] fn case_sensitive() { @@ -384,45 +418,71 @@ Trust me."; ### Have `main` Check the Environment Variable +And put the result in the configuration that gets passed to `run`. + Filename: src/main.rs ```rust,ignore extern crate greprs; +use greprs::Config; + use std::env; -use std::io::prelude::*; -use std::fs::File; +use std::process; fn main() { - let mut case_sensitive = true; - for (var, _) in env::vars() { - if var == "CASE_INSENSITIVE" { - case_sensitive = false; - } - } - let mut args = env::args(); // Discard the name of the binary args.next(); - // `next` returns an `Option` - let search = args.next().expect( - "No search string or filename found. Usage: greprs " - ); - let filename = args.next().expect( - "No filename found. Usage: greprs " - ); + let case_insensitive = env::vars().find(|&(ref var, _)| { + var == "CASE_INSENSITIVE" + }).is_some(); - let results = if case_sensitive { - greprs::grep(search, &contents) + let config = Config { + arguments: args.collect(), + case_insensitive: case_insensitive, + }; + + if let Err(e) = greprs::run(config) { + println!("Application error: {}", e); + process::exit(1); + } +} +``` + +Modify `run` to decide which `grep` function to call based on the configuration. + +Filename: src/lib.rs + +```rust +pub struct Config { + pub arguments: Vec, + pub case_insensitive: bool, +} + +pub fn run(config: Config) -> Result<(), Box> { + let mut args = config.arguments.iter(); + + let search = args.next().ok_or("No search string or filename found")?; + let filename = args.next().ok_or("No filename found")?; + + let mut f = File::open(filename)?; + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + let results = if config.case_insensitive { + grep_case_insensitive(&search, &contents) } else { - greprs::grep_case_insensitive(search, &contents) + grep(&search, &contents) }; for line in results { println!("{}", line); } + + Ok(()) } ``` @@ -442,123 +502,66 @@ To an admiring bog! ## Write to `stderr` Instead of `stdout` -Let's say we want to output statistics about how many lines have matched to `stderr`. +Let's say we want to output any errors to `stderr` instead of `stdout`. Right now, if we run: + +```text +$ cargo run > output.txt +``` + +The contents of *output.txt* will be: + +```text +Application error: No search string or filename found +``` + +Even if we're saving the output to a file, we want to see errors on the screen. Filename: src/main.rs ```rust,ignore extern crate greprs; +use greprs::Config; + use std::env; +use std::process; use std::io::prelude::*; -use std::fs::File; fn main() { - let mut stderr = std::io::stderr(); - - let case_insensitive = env::vars().find(|&(ref var, _)| { - var == "CASE_INSENSITIVE" - }).is_some(); - let mut args = env::args(); // Discard the name of the binary args.next(); - // `next` returns an `Option` - let search = args.next().expect( - "No search string or filename found. Usage: greprs " - ); - let filename = args.next().expect( - "No filename found. Usage: greprs " - ); + let case_insensitive = env::vars().find(|&(ref var, _)| { + var == "CASE_INSENSITIVE" + }).is_some(); - let mut f = File::open(filename).expect("Could not open file."); - let mut contents = String::new(); - f.read_to_string(&mut contents).expect("Could not read file"); - - let results = if case_insensitive { - greprs::grep_case_insensitive(&search, &contents) - } else { - greprs::grep(&search, &contents) + let config = Config { + arguments: args.collect(), + case_insensitive: case_insensitive, }; - let matching_lines = results.len(); - writeln!( - &mut stderr, - "{} lines matched", - matching_lines - ).expect("Could not write to stderr"); + if let Err(e) = greprs::run(config) { + let mut stderr = std::io::stderr(); - for line in results { - println!("{}", line); + writeln!( + &mut stderr, + "Application error: {}", + e + ).expect("Could not write to stderr"); + + process::exit(1); } } ``` -Filename: src/lib.rs - -```rust -pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - contents.lines().filter(|line| line.contains(search)).collect() -} - -pub fn grep_case_insensitive<'a>(search: &str, contents: &'a str) - -> Vec<&'a str> { - let search = search.to_lowercase(); - contents.lines().filter(|line| { - line.to_lowercase().contains(&search) - }).collect() -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn case_sensitive() { - let search = "duct"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three. -Duct tape."; - - assert_eq!( - vec!["safe, fast, productive."], - grep(search, contents) - ); - } - - #[test] - fn case_insensitive() { - let search = "rust"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three. -Trust me."; - - assert_eq!( - vec!["Rust:", "Trust me."], - grep_case_insensitive(search, contents) - ); - } -} -``` - -Output: +Now the output when we don't pass any arguments but redirect stdout to a file +is: ```text -$ cargo run to poem.txt -2/9 lines matched -Are you nobody, too? -How dreary to be somebody! +$ cargo run > output.txt +Application error: No search string or filename found ``` -Redirecting stdout to a file, stderr still gets displayed: - -```text -$ cargo run to poem.txt > new_poem.txt -2/9 lines matched -``` +and the file is empty. From 196b7ff6f88a7ad5edc5db6e1d5e7df021defc88 Mon Sep 17 00:00:00 2001 From: steveklabnik Date: Mon, 19 Dec 2016 17:50:23 -0500 Subject: [PATCH 11/25] do some writing --- src/ch12-00-an-io-project.md | 1072 +++++++++++++++++++++++++++------- 1 file changed, 852 insertions(+), 220 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 45ba59108..fa1f06acc 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -1,16 +1,32 @@ # An I/O Project -`cargo new --bin greprs` +We've learned a lot over the last few chapters. Let's take that new knowledge +and apply it by building a project together. Along the way, we'll learn a bit +more about Rust's standard library. -Project requirements: +So what should we build? One that uses Rust's strengths. A great use of Rust is +for command-line tools: Rust's speed, safety, and 'single binary' output make +it a good choice for this kind of task. So we'll make our own version of a +classic command line tool: `grep`. `grep` is short for "*g*lobally search a +*r*egular *e*xpression and *p*rint." In other words, it does this: -- Take a search string and a filename as command line arguments -- Read the file -- Find lines in the file that contain the search string -- Print out those lines -- Have an environment variable setting to search without regards to case -In order to do a good job, we will: +- Takes a filename and a string as arguments. +- Reads the file. +- Finds lines in the file that contain the string argument. +- Prints out those lines. + +In addition, we'll add one extra feature: an environment variable that will +allow us to search for the text in a case-insensitive way. + +There's another great reason to use `grep` as an example project: a very +fully-featured version of `grep` has already been created in Rust by a +community member, Andrew Gallant. It's called `ripgrep`, and it's very, +very fast. While our version of `grep` will be fairly simple, you'll have +some of the basic knowledge to check out that project if you want to see +something more real-world. + +This project will bring together a number of things we learned previously: - Organize code (using what we learned in modules, ch 7) - Use vectors and strings (collections, ch 8) @@ -18,15 +34,36 @@ In order to do a good job, we will: - Use traits and lifetimes where appropriate (ch 10) - Have tests (ch 11) +Let's make our project with, as always, `cargo new`: + +```text +$ cargo new --bin greprs + Created binary (application) `greprs` project +$ cd greprs +``` + +We're calling our version of `grep` 'greprs', so that we don't confuse any of +our users that it's the more fully-featured version of `grep` you may already +have installed on your system. + ## Command line arguments -To get the arguments passed to the binary, use `std::env::args()`. This -function returns an *iterator*. We're going to use a bunch of iterators and -useful functions on them in this chapter, and chapter 16 will go into depth on -how iterators work. +Our first task is to have `greprs` accept its two command-line arguments. There +are some existing libraries on crates.io that can help us do this, but since +we're learning, we'll implement this ourselves. -We can see all the items in the iterator by collecting them into a vector and -printing it out using debug formatting: +To do this, we'll need to call a function provided in Rust's standard library: +`std::env::args`. This function returns an *iterator* of the command-line +arguments that were given to our program. We haven't discussed iterators yet; +chapter 16 will cover them fully. For our purposes, though, we don't need to +understand much about them. We only need to understand two things: + +1. Iterators produce a series of values by repeatedly calling a `next()` + function. +2. We can call the `collect` function on an iterator to turn it into a vector + of the elements of the iterator. + +Let's give it a try. Filename: src/main.rs @@ -39,7 +76,22 @@ fn main() { } ``` -Run it with various arguments. The binary is the first argument: +You'll notice a few things about this code. First, we have a `use` statement to +bring the `std::env` module into scope. When using a function that's nested in +more than one level of module, like `std::env::args` is, it's conventional to +use `use` to bring the parent module into scope, rather than the function +itself. `env::args` is less ambiguous than a lone `args`. Also, if we end up +using more than one function in `std::env`, we only need a single `use`. + +On the first line of `main`, we call `env::args`, and then immediately use +`collect` to create a vector out of it. We're also explicitly annotating `args` +here: `collect` can be used to create many kinds of collections, and so Rust +won't be able to infer what kind of type we want, so the annotation is +required. We very rarely need to annotate types in Rust, but `collect` is a +one function where you very often need to. + +Finally, we print out the vector with the debug formatter, `:?`. Let's try +running our code with various arguments: ```text $ cargo run @@ -50,89 +102,64 @@ $ cargo run needle haystack ["target/debug/greprs", "needle", "haystack"] ``` -What we want to do is: +You'll notice one interesting thing: the name of the binary is the first +argument. The reasons for this are out of the scope of this chapter, but it's +something we'll have to remember. -1. Discard the binary name that will always be the first argument -2. Collect the rest of the arguments and store them in a configuration struct -3. Pass the configuration to a `run` function that returns a `Result` -4. If there were errors, print information about them and exit with 1. - -The reason we want to have a `run` function in `src/lib.rs` is that it will -make it easier to write tests and pass in different configurations, without -having to actually run our binary from the command line. +Now that we have a way to access all of the arguments, let's find the ones we +care about, and pull them out into their own variables: Filename: src/main.rs -```rust,ignore -extern crate greprs; - -use greprs::Config; - +```rust use std::env; -use std::process; fn main() { - let mut args = env::args(); + let args: Vec = env::args().collect(); - // Discard the name of the binary - args.next(); - - let config = Config { - arguments: args.collect(), - }; - - if let Err(e) = greprs::run(config) { - println!("Application error: {}", e); - process::exit(1); - } -} -``` - -The code in `src/lib.rs` now needs to define a `Config` struct and a `run` -function. The `run` function in `src/lib.rs` will: - -1. Get the search string, which will be in the next argument -2. Get the filename we want to search in as the next argument - -This function will ignore any arguments after that, and will return an error if -it doesn't get enough arguments. - -Filename: src/lib.rs - -```rust -pub struct Config { - pub arguments: Vec, -} - -pub fn run(config: Config) -> Result<(), String> { - let mut args = config.arguments.iter(); - - let search = args.next().ok_or("No search string or filename found")?; - let filename = args.next().ok_or("No filename found")?; + let search = &args[1]; + let filename = &args[2]; println!("Searching for {}", search); println!("In file {}", filename); - Ok(()) } ``` -Try it out with no arguments, one argument, and two arguments: +Remember, the program's name is the first argument, so we don't need `args[0]`. +Let's try running this program again: ```text -$ cargo run -Application error: No search string or filename found - -$ cargo run needle -Application error: No filename found - -$ cargo run needle haystack -Searching for needle -In file haystack +$ cargo run test sample.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe test sample.txt` +Searching for test +In file sample.txt ``` +Great! There's one problem, though. Let's try giving it no arguments: + +```text +steve@becoming ~/tmp/greprs (master) +$ cargo run + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe` +thread 'main' panicked at 'index out of bounds: the len is 1 +but the index is 1', ../src/libcollections\vec.rs:1307 +note: Run with `RUST_BACKTRACE=1` for a backtrace. +``` + +Because our vector only has one element, but we tried to access the second +element, our program panics with a message about the out-of-bound access. While +this error message is _accurate_, it's not meaningful to users of our program +at all. We could fix this problem right now, but let's push forward: we'll +improve this situation before we're finished. + ## Reading a file -File to search in: +Now that we have some variables containing the information that we need, let's +try using them. The next step is to open the file that we want to search. To do +that, we need a file. Create one called `poem.txt` at the root level of your +project, and fill it up with some Emily Dickinson: Filename: poem.txt @@ -153,38 +180,53 @@ short, but that has multiple lines and some repetition. We could search through code; that gets a bit meta and possibly confusing... Changes to this are most welcome. /Carol --> -Filename: src/lib.rs +With that in place, let's edit `main.rs` to open the file: + +Filename: src/main.rs ```rust +use std::env; use std::fs::File; use std::io::prelude::*; -use std::error::Error; -pub struct Config { - pub arguments: Vec, -} +fn main() { + let args: Vec = env::args().collect(); -pub fn run(config: Config) -> Result<(), Box> { - let mut args = config.arguments.iter(); - - let search = args.next().ok_or("No search string or filename found")?; - let filename = args.next().ok_or("No filename found")?; + let search = &args[1]; + let filename = &args[2]; println!("Searching for {}", search); println!("In file {}", filename); - let mut f = File::open(filename)?; + let mut f = File::open(filename).expect("file not found"); + let mut contents = String::new(); - f.read_to_string(&mut contents)?; + f.read_to_string(&mut contents).expect("something went wrong reading the file"); println!("With text:\n{}", contents); - Ok(()) } ``` +We've added a few things. First of all, we need some more `use` statements to +bring in the relevant parts of the standard library: we need `std::fs::File` +for dealing with files, and `std::io::prelude::*` contains various traits that +are useful when doing I/O, including file I/O. In the same way that Rust has a +general prelude that brings certain things into scope automatically, the +`std::io` module has its own prelude of common things you'll need. Unlike the +default prelude, we must explicitly `use` the prelude in `std::io`. + +In `main`, we've added three things: first, we open our file with `File::open`. +Second, we create a `String`, and then call `read_to_string` on our file, +placing the contents of the file into the string. Finally, we print out the +contents. + +Let's try running it: + ```text -$ cargo run test poem.txt -Searching for test +$ cargo run the poem.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe the poem.txt` +Searching for the In file poem.txt With text: I'm nobody! Who are you? @@ -198,15 +240,485 @@ To tell your name the livelong day To an admiring bog! ``` +Great! Our code is working. However, it's got a few flaws. Because our program +is still small, they're not a huge deal, but as our program grows, it will be +harder and harder to fix them in a clean way. Let's do the refactoring now, +instead of waiting. The refactoring will be much easier to do with only this +small amount of code. + +So what are these problems? There are four. The first is opening the file: +we've used `expect` to print out an error message if opening the file fails, +but it only says "file not found". There are a number of ways that opening a +file can fail, but we're always assuming that it's due to the file being +missing. For example, the file could exist, but we don't have permission to +open it: right now, we print an error message that says the wrong thing! +Secondly, our use of `expect` over and over recalls our earlier issue with the +`panic!`s on indexing: while it _works_, it's a bit unprincipled, and we're +doing it all throughout our program. It would be nice to put our error handling +in one spot. Finally, our `main` function now does two things: it parses +arguments, and opens up files. For such a small function, this isn't a problem, +but as we keep growing our program inside of `main`, it will get larger and +larger. This also ties into our fourth problem: while `search` and `filename` +are configuration variables to our program, things like `f` and `contents` are +used to do our program's logic. The longer `main` gets, the more variables +we're going to bring into scope, and the more variables we have in scope, the +harder it is to keep track of which ones we need and for which purpose. + +These problems are common to many similar kinds of projects, and so the Rust +community has developed a pattern for dealing with them. This pattern is useful +for organizing any binary project you'll build in Rust, and so we can do this +refactoring a bit earlier, since we know that our project fits the pattern. +It looks like this: + +1. Split your program into both a `main.rs` and a `lib.rs`. +2. Place your command-line parsing logic into `main.rs`. +3. Place your program's logic into `lib.rs`. +4. The job of the `main` function is: + * parse arguments + * set up any other configuration + * call a `run` function in `lib.rs` + * if `run` returns an error, handle that error + + +Whew! It sounds like a lot more than it is, honestly. It's all about separating +concerns: `main.rs` handles actually running the program, and `lib.rs` handles +all of the actual logic of the task at hand. This pattern has additional +benefits that we won't talk about just yet. Let's re-work our program into this +pattern. First, let's split out a function to parse arguments. Here's the new +start of `main`: + +```rust,ignore +fn main() { + let args: Vec = env::args().collect(); + + let (search, filename) = parse_config(&args); + + println!("Searching for {}", search); + println!("In file {}", filename); +``` + +And the definition of `parse_config`: + +```rust,ignore +fn parse_config(args: &[String]) -> (&str, &str) { + let search = &args[1]; + let filename = &args[2]; + + (search, filename) +} +``` + +This may seem like overkill, but we're working in small steps. After making +this change, run the program again to verify that things still work. It's good +to do this often. + + + +Now that we have a function, let's improve it. Our code has a smell: we return +a tuple, but then immediately break that tuple up into individual parts again. +This isn't bad on its own, but there's one other thing: we called our function +`parse_config`. That is, these two variables should really be bound together, +as they're both part of a configuration. + +> Note: some people call this smell "primitive obsession." + +Let's introduce a struct to hold all of our configuration. It will look like +this: + +```rust +struct Config { + search: String, + filename: String, +} +``` + +And we can refactor `parse_string` like this: + +```rust,ignore +fn parse_config(args: &[String]) -> Config { + let search = args[1].clone(); + let filename = args[2].clone(); + + Config { + search: search, + filename: filename, + } +} +``` + +We're now returning a `Config`, but there's one other change. We used to be +returning string slices, but our `Config` contains `String`s. And since we have +a slice of `String`s, we can't take ownership of them, as that violates Rust's +borrowing rules. There are a number of different things we could do in this +situation, but for now, we'll take the "easy but less efficient" route, and +call `clone`. This will make a full copy of the string's data, but it makes our +code very straightforward. There's a tendency amongst many Rustaceans to really +dislike calls to `clone` to fix ownership problems, due to that lack of +efficiency. In chapter XX on iterators, we'll learn the tricks we need to make +this more efficient. But for now, it's okay to copy a few strings to keep +making progress. We're only going to be making this copy one time, and our +filename and search string are both very small. It's better to have a working +program and have it be a bit inefficient then to try to hyper-optimize code on +your first pass. As you get more experienced with Rust, it'll be easier to skip +this step, but for now, just call `clone`. It's fine. + +Whew, sorry about that little digression! Before our program works, we need to +update `main` as well: + +```rust,ignore +let config = parse_config(&args); + +println!("Searching for {}", config.search); +println!("In file {}", config.filename); + +let mut f = File::open(config.filename).expect("file not found"); +``` + +We now have a single `config` variable, and so we need to update everything to +use it instead of the old variables. + +This is getting pretty good! Give your program another run to make sure it's +still working. We have two more refactorings to do here, though! Let's think +about `parse_config`. It's a function that creates a `Config`. We already know +a convention for this: a `new` method. Let's transform `parse_config` into one: + +```rust,ignore +impl Config { + fn new(args: &[String]) -> Config { + let search = args[1].clone(); + let filename = args[2].clone(); + + Config { + search: search, + filename: filename, + } + } +} +``` + +The only changes here are putting it into an `impl` block and changing the name +to `new`. Easy! We do need to update the callsite in `main` too, though: + +```rust,ignore +let config = Config::new(&args); +``` + +Try compiling this again to make sure it works. + +Here's our last refactoring: remember how accessing the vector with incorrect +indices panics and gives a bad error message? Let's fix that! To do that, we +can check that our slice is long enough: + +```rust,ignore +fn new(args: &[String]) -> Config { + if args.len() < 3 { + panic!("not enough arguments"); + } +``` + +With these extra few lines of code in `new`, let's try running our program with +incorrect arguments: + +```bash +$ cargo run + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe` +thread 'main' panicked at 'not enough arguments', src\main.rs:29 +note: Run with `RUST_BACKTRACE=1` for a backtrace. +``` + +This is a bit better! We at least have a reasonable panic message here. +However, we also have a bunch of extra information here that we don't want to +give to our users. We can do better. To do that, we need to change the type +signature of `new`. Right now, because it returns only a `Config`, there's no +way to indicate that an error happened while creating our `Config`. So instead, +we can use `Result`, like this: + +```rust,ignore +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let search = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { + search: search, + filename: filename, + }) + } +} +``` + +Our `new` function now gives us a `Result`, with a `&'static str` as our error +message. Remember, this is the type of string literals, which is what our error +message is right now. + +We've made two changes in the body: instead of `panic!`ing, we now return an +`Err`, and we wrapped our return value in an `Ok`. This makes it conform to the +new type signature. + +Finally, we make some changes in `main`. Up top, we need a new `use` line: + +```rust,ignore +use std::process; +``` + +And then in the main function itself: + +```rust,ignore +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); +``` + +Here, we see a new method on `Result`: `unwrap_or_else`. This method does +something similar to `unwrap`; that is, if the `Result` is `Ok`, it +returns the inner value `Ok` is wrapping. But unlike `unwrap`, if the value is +an `Err`, it instead calls a closure, passing the inner value of the `Err` to +it. This lets us do some custom, non-`panic!` error handling. + +Said error handling is only two lines: we print out the error, and then call +`std::process::exit`. That function will stop our program's execution +immediately, and return the number passed to it as a return code. By convention, +a zero means success and any other value means failure. So in the end, this has +similar characteristics to our `panic!`-based handling from before, but we no +longer get all the extra output. Let's try it: + +```bash +$ cargo run + Compiling greprs v0.1.0 (file:///C:/Users/steve/tmp/greprs) + Finished debug [unoptimized + debuginfo] target(s) in 0.48 secs + Running `target\debug\greprs.exe` +Problem parsing arguments: not enough arguments +``` + +Great! This is much nicer. Now that we're done with fixing up our configuration +parsing, let's do some work on our program's logic. Let's create a new function, +and then call it from `main`: + +```rust,ignore +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.search); + println!("In file {}", config.filename); + + run(config); +} + +fn run(config: Config) { + let mut f = File::open(config.filename).expect("file not found"); + + let mut contents = String::new(); + f.read_to_string(&mut contents).expect("something went wrong reading the file"); + + println!("With text:\n{}", contents); +} +``` + +The contents of `run` are the previous lines that were in `main`, and we take a +`Config` as an argument. Now that we have a separate function, we can do +something very similar to what we did with `Config::new`: let's have it return +a `Result` instead of `panic!`ing with `expect`. First, we need to add a +line at the top: + +```rust +use std::error::Error; +``` + +And then change our `run()` function to look like this: + +```rust,ignore +fn run(config: Config) -> Result<(), Box> { + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + println!("With text:\n{}", contents); + + Ok(()) +} +``` + +We have three big changes here. The first is the return type: `Result<(), +Box>`. Previously, our function returned nothing, aka `()`, so that's +still our `Ok` case. For our error type, we're going to use `Box`. This +is called a "trait object," which we'll be covering in chapter XX. For now, +think of it like this: a `Box` means "I just want some kind of error, +I don't care what specific kind." We could do something more specialized, but +this is the most straightforward thing for now. + +Secondly, we've removed our calls to `expect` in favor of `?`, like we talked +about in chapter XX. Rather than `panic!` on an error, this will instead return +the result from the function we're in, as we talked about in that chapter. + +Finally, we have to return an `Ok` value from this function, and since we have +declared its type as `()` in our function signature, we need `Ok(())`. This +looks a bit strange at first, but using `()` in this way is the idiomatic way +to say "we are calling `run` for its side effects only, it doesn't return a +value of anything interesting." + +This will compile, but with a warning: + +```text +warning: unused result which must be used, #[warn(unused_must_use)] on by default + --> src\main.rs:39:5 + | +39 | run(config); + | ^^^^^^^^^^^^ +``` + +Rust is trying to tell us that we're ignoring our result, which may fail. Let's +handle that now. It similar to the way we handled failure with `Config::new`, +but slightly different: + +```rust,ignore +if let Err(e) = run(config) { + println!("Application error: {}", e); + + process::exit(1); +} +``` + +Instead of `unwrap_or_else`, we use `if let` to see if `run` returns an `Err` +value. Why? The distinction is a bit subtle. With `Config::new`, we cared about +two things: + +1. Detecting any errors that happen +2. Getting a `Config` if no errors happened + +In this case, because `run` returns a `()` in the success case, the only thing +we care about is the first case: detecting an error. If we used +`unwrap_or_else`, we'd have to save its return value, which would be `()`. +That's not very useful. + +The bodies are the same in both cases though: we print out an error and exit. + +This is looking pretty good! There's one more thing we haven't done yet: split +things up into a `lib.rs` as well. Let's do that now. Move `run` from `main.rs` +to a new file, `src/lib.rs`. You'll also need to move the relevant `use` +statements, as well as `Config`: + +```rust,ignore +use std::error::Error; +use std::fs::File; +use std::io::prelude::*; + +pub struct Config { + pub search: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let search = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { + search: search, + filename: filename, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box>{ + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + println!("With text:\n{}", contents); + + Ok(()) +} +``` + +Notice we also made liberal use of `pub`: on `Config`, its `new` function, +and its elements. In addition, on `run`. + +Now, for `main.rs`. We need to add in our `lib.rs` through `extern crate`, +use `Config`, and prefix the `run` function with our crate name: + +```rust,ignore +extern crate greprs; + +use std::env; +use std::process; + +use greprs::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.search); + println!("In file {}", config.filename); + + if let Err(e) = greprs::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} +``` + +With that, everything should work again. Give it a few `cargo run`s and make +sure you haven't broken anything. Whew! That all was a lot of work, but we've +set ourselves up for success in the future. Almost all of our work will be +done in the library from here on out, but we've set up a way to handle errors +in a much nicer fashion, and we've made our code slightly more modular. + +Let's take advantage of this newfound modularity by doing something that would +have been hard with our old code, but is easy with our new code: write some +tests! + ## Tests -Start some tests in *src/lib.rs*. +We need to write a function, `grep`, that takes our search term and the text to +search, and procudes a list of search results. Let's remove that `println!` from +`run` (and probably from `main.rs` as well, as we don't really need those anymore +either), and call this function with the options we've collected. We'll add a +dummy implementation of the function, and some tests. Here's our new `run` +function: -We want a function that will take a search term and contents, and return a -vector of lines from the contents that contain the search term. Here's a -failing test: +File: src/lib.rs - +```rust +pub fn run(config: Config) -> Result<(), Box>{ + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + grep(&config.search, &contents); + + Ok(()) +} +``` + +And then our new definitions of `grep` and a test: File: src/lib.rs @@ -235,6 +747,51 @@ Pick three."; } ``` +Being able to do this test is enabled by all that modularization work we did +in the previous sections. By separating the code that relies on dealing with +the environment from our core logic, we can write very straightforward tests +that don't need to load files or deal with command-line arguments. Nice! + +Before we run the test, let's talk about this type signature: + +```rust,ignore +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { +``` + +We need an explicit lifetime on `grep`, which is what the `<'a>` business is +all about. But why? And what does it do? + +Remember, the `'a`s are used to connect the lifetimes of different arguments to +our function. So in this case, we're saying that the vector we're returning is +going to have `&str`s that reference `contents`, not `search`. This is +important! Given that slices and references need to always be valid, if Rust +thought that we were making string slices of `search`, rather than `contents`, +it would do its safety checking incorrectly. If we tried to compile this +function without lifetimes, Rust would fail to compile it: + +```text +error[E0106]: missing lifetime specifier + --> src\lib.rs:37:46 + | +37 | fn grep(search: &str, contents: &str) -> Vec<&str> { + | ^ expected lifetime parameter + | + = help: this function's return type contains a borrowed value, but the + signature does not say whether it is borrowed from `search` or + `contents` +``` + +Rust can't possibly know which of the two arguments we need, so it needs us to +tell it. Since `contents` is the string that contains all of our text, we know +that's the one that our results will refer to, not the search string. And so, +we use the lifetime syntax to connect the two. + +The above situation is a little tricky at first, but it gets easier over time! +Practice makes perfect. Don't feel bad if you need to re-read the above +section, and maybe go back and compare with chapter XX's lifetimes section. + +Now that we understand that, let's try running our test: + ```text $ cargo test ...warnings... @@ -259,41 +816,60 @@ test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured error: test failed ``` -We're going to get the test passing by: +Great, our test fails, exactly as we expected. Let's get the test to pass! It's +failing because we always return an empty vector. Here's what we have to do +to implement `grep`: -1. Getting an iterator over each line of the contents with the `lines` function -2. Use the `filter` method and specify the condition a line should meet in - order to pass through the filter. -3. The condition is that the line contains the search string -4. Collect the results of the filtered iterator into a vector and return it +1. Iterate through each line of the contents. +2. Check if the line contains our search string. + * If it does, add it to the list of values we're returning. + * If not, do nothing +3. Return our list of results. -File: src/lib.rs +Let's take each step at a time. First, iterating through lines. Strings have +a helpful method to handle this, conveniently named `lines`: -```rust -pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - contents.lines().filter(|line| line.contains(search)).collect() -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn one_result() { - let search = "duct"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three."; - - assert_eq!( - vec!["safe, fast, productive."], - grep(search, contents) - ); +```rust,ignore +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + for line in contents.lines() { + // do something with line } } ``` +We can use a `for` loop along with the `lines` method to get each line in turn. +Next, let's see if our line contains the search string. Luckily, strings have a +helpful method named `contains` that does this for us! It looks like this: + +```rust,ignore +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + for line in contents.lines() { + if line.contains(search) { + // do something with line + } + } +} +``` + +Finally, we need a way to store these lines that contian our search string. +For that, we can make a vector: + +```rust,ignore +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(search) { + results.push(line); + } + } + + results +} +``` + +Let's give it a try: + ```text $ cargo test running 1 test @@ -314,72 +890,63 @@ running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured ``` -## Call the `grep` function from the `run` function +Great! It works. However, we can do better. This code isn't bad, but it's very +focused on the fiddly details of each step. We can do better, but to do so, we +need to learn more about iterators and how they work. We'll come back to this +example in that chapter and see how to improve it. -Filename: src/lib.rs +Now that `grep` is working, we need to do one last thing inside of `run`: we never +printed out the results! Try this: -```rust -use std::fs::File; -use std::io::prelude::*; -use std::error::Error; +```rust,ignore +pub fn run(config: Config) -> Result<(), Box>{ + let mut f = File::open(config.filename)?; -pub struct Config { - pub arguments: Vec, -} - -pub fn run(config: Config) -> Result<(), Box> { - let mut args = config.arguments.iter(); - - let search = args.next().ok_or("No search string or filename found")?; - let filename = args.next().ok_or("No filename found")?; - - let mut f = File::open(filename)?; let mut contents = String::new(); f.read_to_string(&mut contents)?; - let results = grep(&search, &contents); - - for line in results { + for line in grep(&config.search, &contents) { println!("{}", line); } Ok(()) } - -fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - contents.lines().filter(|line| line.contains(search)).collect() -} ``` +We've added a `for` loop to print out each of the lines we get back from +`grep`. Now it all should be working! Let's try it out: + ```text $ cargo run the poem.txt -Then there's a pair of us — don't tell! + Compiling greprs v0.1.0 (file:///C:/Users/steve/tmp/greprs) + Finished debug [unoptimized + debuginfo] target(s) in 0.38 secs + Running `target\debug\greprs.exe the poem.txt` +Then there's a pair of us - don't tell! To tell your name the livelong day + +$ cargo run a poem.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe a poem.txt` +I'm nobody! Who are you? +Then there's a pair of us - don't tell! +They'd banish us, you know. +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! ``` +Excellent! We've built our own version of a classic tool, and learned a lot about +how to structure applications. We've also learned a bit about file input and output, +and command-line parsing. + ## Working with Environment Variables -Enhancement we want to add: allow the user of our program to set an environment -variable in their terminal session to do searches that match on case exactly or -not. - -### Implement and Test a Case-Insensitive `grep` Function - -Filename: src/lib.rs - -```rust -pub fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - contents.lines().filter(|line| line.contains(search)).collect() -} - -pub fn grep_case_insensitive<'a>(search: &str, contents: &'a str) - -> Vec<&'a str> { - let search = search.to_lowercase(); - contents.lines().filter(|line| { - line.to_lowercase().contains(&search) - }).collect() -} +Let's add one more feature: case insensitive searching. In addtion, this setting won't +be a command-line option: it'll be an environment variable instead. But first, let's +build out the functionality. Let's add a new test, and re-name our existing one: +```rust,ignore #[cfg(test)] mod test { use {grep, grep_case_insensitive}; @@ -416,90 +983,155 @@ Trust me."; } ``` -### Have `main` Check the Environment Variable -And put the result in the configuration that gets passed to `run`. +### Implement and Test a Case-Insensitive `grep` Function -Filename: src/main.rs - -```rust,ignore -extern crate greprs; - -use greprs::Config; - -use std::env; -use std::process; - -fn main() { - let mut args = env::args(); - - // Discard the name of the binary - args.next(); - - let case_insensitive = env::vars().find(|&(ref var, _)| { - var == "CASE_INSENSITIVE" - }).is_some(); - - let config = Config { - arguments: args.collect(), - case_insensitive: case_insensitive, - }; - - if let Err(e) = greprs::run(config) { - println!("Application error: {}", e); - process::exit(1); - } -} -``` - -Modify `run` to decide which `grep` function to call based on the configuration. +We also need to define a new function, `grep_case_insensitive`. We +can do this easily: it's almost the same as `grep`, but with one +minor change: Filename: src/lib.rs ```rust -pub struct Config { - pub arguments: Vec, - pub case_insensitive: bool, +fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(search) { + results.push(line); + } + } + + results } +``` -pub fn run(config: Config) -> Result<(), Box> { - let mut args = config.arguments.iter(); +All we need to change is add a call to `to_lowercase`. Now, we'll ignore the case +of our contents when searching. Let's see if it works: - let search = args.next().ok_or("No search string or filename found")?; - let filename = args.next().ok_or("No filename found")?; +```text + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running target\debug\deps\greprs-e58e9b12d35dc861.exe - let mut f = File::open(filename)?; - let mut contents = String::new(); - f.read_to_string(&mut contents)?; +running 2 tests +test test::case_insensitive ... ok +test test::case_sensitive ... ok - let results = if config.case_insensitive { - grep_case_insensitive(&search, &contents) +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured + + Running target\debug\greprs-8a7faa2662b5030a.exe + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured + + Doc-tests greprs + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured +``` + +Great! Now, we have to actually use it inside of our library. First, let's +add a configuration option for it: + +```rust +pub struct Config { + pub search: String, + pub filename: String, + pub case_sensitive: bool, +} +``` + +And then check for that option inside of `run`: + +```rust,ignore + let results = if config.case_sensitive { + grep(&config.search, &contents) } else { - grep(&search, &contents) + grep_case_insensitive(&config.search, &contents) }; for line in results { println!("{}", line); } +``` - Ok(()) +We check our configuration, and call the correct function for its setting. +We save the result to a variable, and then do the printing. + +Finally, we need to actually check the environment for the variable. This means +two things. First, we add a `use` line at the top of `lib.rs`: + +```rust +use std::env; +``` + +And then using the `vars` method from it inside of `new`: + +```rust +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let search = args[1].clone(); + let filename = args[2].clone(); + + let mut case_sensitive = true; + + for (name, _) in env::vars() { + if name == "CASE_INSENSITIVE" { + case_sensitive = false; + } + } + + Ok(Config { + search: search, + filename: filename, + case_sensitive: case_sensitive, + }) + } } ``` +Here, we call `env::vars`, which is kind of like `env::args`. The difference? +It returns an iterator of environment variables, rather than command-line +arguments. Instead of using `collect` to create a vector of all of the +environment variables, we instead use a `for` loop. `env::vars` returns tuples: +the name of the environment varaible, and then its value. We never care about +the values, so we use a `_` to let Rust know that. Finally, we have a +`case_sensitive` variable, which is set to true by default. If we ever find a +`CASE_INSENSITIVE` environment variable, we set it to false instead. + +Let's give it a try! + ```text $ cargo run to poem.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe to poem.txt` Are you nobody, too? How dreary to be somebody! ``` ```text $ CASE_INSENSITIVE=1 cargo run to poem.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe to poem.txt` Are you nobody, too? How dreary to be somebody! To tell your name the livelong day To an admiring bog! ``` +Excellent! Some programs are configurable through environement variables, and some +allow both arguments _and_ environment variables, and decide that one or the other takes +precedence. But now you know how to handle either strategy. + +There's a lot more stuff in `std::env` for dealing with environment variables; check out +its documentation for more goodies. + ## Write to `stderr` Instead of `stdout` Let's say we want to output any errors to `stderr` instead of `stdout`. Right now, if we run: From f3e052020a67999bf64289aa3c4c297e2b217ad0 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Fri, 23 Dec 2016 14:35:00 -0500 Subject: [PATCH 12/25] Doing that thing i do --- src/ch12-00-an-io-project.md | 588 ++++++++++++++++++++++------------- 1 file changed, 379 insertions(+), 209 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index fa1f06acc..43fb85659 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -5,11 +5,11 @@ and apply it by building a project together. Along the way, we'll learn a bit more about Rust's standard library. So what should we build? One that uses Rust's strengths. A great use of Rust is -for command-line tools: Rust's speed, safety, and 'single binary' output make -it a good choice for this kind of task. So we'll make our own version of a -classic command line tool: `grep`. `grep` is short for "*g*lobally search a -*r*egular *e*xpression and *p*rint." In other words, it does this: - +for command line tools: Rust's speed, safety, 'single binary' output, and +cross-platform support make it a good language choice for this kind of task. So +we'll make our own version of a classic command line tool: `grep`. `grep` is +short for "*g*lobally search a *r*egular *e*xpression and *p*rint." In the +simplest use case, it does this: - Takes a filename and a string as arguments. - Reads the file. @@ -17,24 +17,27 @@ classic command line tool: `grep`. `grep` is short for "*g*lobally search a - Prints out those lines. In addition, we'll add one extra feature: an environment variable that will -allow us to search for the text in a case-insensitive way. +allow us to search for the string argument in a case-insensitive way. There's another great reason to use `grep` as an example project: a very fully-featured version of `grep` has already been created in Rust by a community member, Andrew Gallant. It's called `ripgrep`, and it's very, very fast. While our version of `grep` will be fairly simple, you'll have -some of the basic knowledge to check out that project if you want to see +some of the background knowledge to understand that project if you want to see something more real-world. This project will bring together a number of things we learned previously: -- Organize code (using what we learned in modules, ch 7) -- Use vectors and strings (collections, ch 8) -- Handle errors (ch 9) -- Use traits and lifetimes where appropriate (ch 10) -- Have tests (ch 11) +- Organize code (using what we learned in modules, Chapter 7) +- Use vectors and strings (collections, Chapter 8) +- Handle errors (Chapter 9) +- Use traits and lifetimes where appropriate (Chapter 10) +- Have tests (Chapter 11) -Let's make our project with, as always, `cargo new`: +Additionally, we'll briefly introduce closures, iterators, and trait objects, +which Chapters XX, YY, and ZZ respectively are about to cover in detail. + +Let's create a new project with, as always, `cargo new`: ```text $ cargo new --bin greprs @@ -43,29 +46,31 @@ $ cd greprs ``` We're calling our version of `grep` 'greprs', so that we don't confuse any of -our users that it's the more fully-featured version of `grep` you may already -have installed on your system. +our users into thinking that it's the more fully-featured version of `grep` +they may already have installed on their system. -## Command line arguments +## Accepting Command Line Arguments -Our first task is to have `greprs` accept its two command-line arguments. There +Our first task is to have `greprs` accept its two command line arguments. There are some existing libraries on crates.io that can help us do this, but since we're learning, we'll implement this ourselves. -To do this, we'll need to call a function provided in Rust's standard library: -`std::env::args`. This function returns an *iterator* of the command-line +We'll need to call a function provided in Rust's standard library: +`std::env::args`. This function returns an *iterator* of the command line arguments that were given to our program. We haven't discussed iterators yet; -chapter 16 will cover them fully. For our purposes, though, we don't need to -understand much about them. We only need to understand two things: +Chapter 16 will cover them fully. For our purposes, though, we don't need to +understand much about how they work in order to use them. We only need to +understand two things: -1. Iterators produce a series of values by repeatedly calling a `next()` +1. Iterators produce a series of values by repeatedly calling a `next` function. 2. We can call the `collect` function on an iterator to turn it into a vector - of the elements of the iterator. + containing all of the elements the iterator produces. -Let's give it a try. +Let's give it a try as shown in Listing 12-1: -Filename: src/main.rs +
+Filename: src/main.rs ```rust use std::env; @@ -76,22 +81,31 @@ fn main() { } ``` -You'll notice a few things about this code. First, we have a `use` statement to -bring the `std::env` module into scope. When using a function that's nested in -more than one level of module, like `std::env::args` is, it's conventional to -use `use` to bring the parent module into scope, rather than the function -itself. `env::args` is less ambiguous than a lone `args`. Also, if we end up -using more than one function in `std::env`, we only need a single `use`. +
-On the first line of `main`, we call `env::args`, and then immediately use -`collect` to create a vector out of it. We're also explicitly annotating `args` -here: `collect` can be used to create many kinds of collections, and so Rust +Listing 12-1: Collect the command line arguments into a vector and print them out + +
+
+ + + +First, we have a `use` statement to bring the `std::env` module into scope. +When using a function that's nested in more than one level of module, like +`std::env::args` is, it's conventional to use `use` to bring the parent module +into scope, rather than the function itself. `env::args` is less ambiguous than +a lone `args`. Also, if we end up using more than one function in `std::env`, +we only need a single `use`. + +On the first line of `main`, we call `env::args`, and immediately use `collect` +to create a vector out of it. We're also explicitly annotating the type of +`args` here: `collect` can be used to create many kinds of collections. Rust won't be able to infer what kind of type we want, so the annotation is -required. We very rarely need to annotate types in Rust, but `collect` is a -one function where you very often need to. +required. We very rarely need to annotate types in Rust, but `collect` is one +function where you often need to. Finally, we print out the vector with the debug formatter, `:?`. Let's try -running our code with various arguments: +running our code with no arguments, and then with two arguments: ```text $ cargo run @@ -104,12 +118,13 @@ $ cargo run needle haystack You'll notice one interesting thing: the name of the binary is the first argument. The reasons for this are out of the scope of this chapter, but it's -something we'll have to remember. +something we'll have to remember to account for. Now that we have a way to access all of the arguments, let's find the ones we -care about, and pull them out into their own variables: +care about and save them in variables as shown in Listing 12-2: -Filename: src/main.rs +
+Filename: src/main.rs ```rust use std::env; @@ -125,8 +140,20 @@ fn main() { } ``` +
+ +Listing 12-2: Create variables to hold the search argument and filename argument + +
+
+ + + Remember, the program's name is the first argument, so we don't need `args[0]`. -Let's try running this program again: +We've decided that the first argument will be the string we're searching for, +so we put a reference to the first argument in the variable `search`. The +second argument will be the filename, so we put a reference to the second +argument in the variable `filename`. Let's try running this program again: ```text $ cargo run test sample.txt @@ -139,7 +166,6 @@ In file sample.txt Great! There's one problem, though. Let's try giving it no arguments: ```text -steve@becoming ~/tmp/greprs (master) $ cargo run Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs Running `target\debug\greprs.exe` @@ -148,20 +174,20 @@ but the index is 1', ../src/libcollections\vec.rs:1307 note: Run with `RUST_BACKTRACE=1` for a backtrace. ``` -Because our vector only has one element, but we tried to access the second -element, our program panics with a message about the out-of-bound access. While -this error message is _accurate_, it's not meaningful to users of our program -at all. We could fix this problem right now, but let's push forward: we'll -improve this situation before we're finished. +Because our vector only has one element, the program's name, but we tried to +access the second element, our program panics with a message about the +out-of-bound access. While this error message is _accurate_, it's not +meaningful to users of our program at all. We could fix this problem right now, +but let's push forward: we'll improve this situation before we're finished. -## Reading a file +## Reading a File Now that we have some variables containing the information that we need, let's try using them. The next step is to open the file that we want to search. To do that, we need a file. Create one called `poem.txt` at the root level of your project, and fill it up with some Emily Dickinson: -Filename: poem.txt +Filename: poem.txt ```text I'm nobody! Who are you? @@ -180,9 +206,11 @@ short, but that has multiple lines and some repetition. We could search through code; that gets a bit meta and possibly confusing... Changes to this are most welcome. /Carol --> -With that in place, let's edit `main.rs` to open the file: +With that in place, let's edit *src/main.rs* and add code to open the file as +shown in Listing 12-3: -Filename: src/main.rs +
+Filename: src/main.rs ```rust use std::env; @@ -207,20 +235,35 @@ fn main() { } ``` +
+ +Listing 12-3: Read the contents of the file specified by the second argument + +
+
+ + + We've added a few things. First of all, we need some more `use` statements to bring in the relevant parts of the standard library: we need `std::fs::File` for dealing with files, and `std::io::prelude::*` contains various traits that are useful when doing I/O, including file I/O. In the same way that Rust has a general prelude that brings certain things into scope automatically, the -`std::io` module has its own prelude of common things you'll need. Unlike the -default prelude, we must explicitly `use` the prelude in `std::io`. +`std::io` module has its own prelude of common things you'll need when working +with I/O. Unlike the default prelude, we must explicitly `use` the prelude in +`std::io`. -In `main`, we've added three things: first, we open our file with `File::open`. -Second, we create a `String`, and then call `read_to_string` on our file, -placing the contents of the file into the string. Finally, we print out the -contents. +In `main`, we've added three things: first, we get a handle to the file and +open it by using the `File::open` function and passing it the name of the file +specified in the second argument. Second, we create a mutable, empty `String` +in the variable `contents`, then call `read_to_string` on our file handle with +our `contents` string as the argument; `contents` is where `read_to_string` +will place the data it reads. Finally, we print out the entire file contents, +which is a way for us to be sure our program is working so far. -Let's try running it: +Let's try running this code, specifying any string for the first argument (since +we haven't implemented the searching part yet) and our *poem.txt* file as the +second argument: ```text $ cargo run the poem.txt @@ -241,51 +284,62 @@ To an admiring bog! ``` Great! Our code is working. However, it's got a few flaws. Because our program -is still small, they're not a huge deal, but as our program grows, it will be -harder and harder to fix them in a clean way. Let's do the refactoring now, -instead of waiting. The refactoring will be much easier to do with only this -small amount of code. +is still small, these flaws aren't a huge deal, but as our program grows, it +will be harder and harder to fix them in a clean way. Let's do the refactoring +now, instead of waiting. The refactoring will be much easier to do with only +this small amount of code. -So what are these problems? There are four. The first is opening the file: -we've used `expect` to print out an error message if opening the file fails, -but it only says "file not found". There are a number of ways that opening a -file can fail, but we're always assuming that it's due to the file being -missing. For example, the file could exist, but we don't have permission to -open it: right now, we print an error message that says the wrong thing! -Secondly, our use of `expect` over and over recalls our earlier issue with the -`panic!`s on indexing: while it _works_, it's a bit unprincipled, and we're -doing it all throughout our program. It would be nice to put our error handling -in one spot. Finally, our `main` function now does two things: it parses -arguments, and opens up files. For such a small function, this isn't a problem, -but as we keep growing our program inside of `main`, it will get larger and -larger. This also ties into our fourth problem: while `search` and `filename` -are configuration variables to our program, things like `f` and `contents` are -used to do our program's logic. The longer `main` gets, the more variables +So what are these problems? There are four. The first problem is where we open +the file: we've used `expect` to print out an error message if opening the file +fails, but the error message only says "file not found". There are a number of +ways that opening a file can fail, but we're always assuming that it's due to +the file being missing. For example, the file could exist, but we might not have +permission to open it: right now, we print an error message that says the wrong +thing! + +Secondly, our use of `expect` over and over is similar to the earlier issue we +noted with the `panic!` on indexing if we don't pass any command line +arguments: while it _works_, it's a bit unprincipled, and we're doing it all +throughout our program. It would be nice to put our error handling in one spot. + +The third problem is that our `main` function now does two things: it parses +arguments, and it opens up files. For such a small function, this isn't a huge +problem. However, as we keep growing our program inside of `main`, the number of +separate tasks in the `main` function will get larger and larger. As one +function gains many responsibilities, it gets harder to reason about, harder to +test, and harder to change without breaking one of its parts. + +This also ties into our fourth problem: while `search` and `filename` are +configuration variables to our program, variables like `f` and `contents` are +used to perform our program's logic. The longer `main` gets, the more variables we're going to bring into scope, and the more variables we have in scope, the -harder it is to keep track of which ones we need and for which purpose. +harder it is to keep track of which ones we need for which purpose. -These problems are common to many similar kinds of projects, and so the Rust -community has developed a pattern for dealing with them. This pattern is useful -for organizing any binary project you'll build in Rust, and so we can do this -refactoring a bit earlier, since we know that our project fits the pattern. -It looks like this: +These organizational problems are common to many similar kinds of projects, so +the Rust community has developed a pattern for organizing the separate +concerns. This pattern is useful for organizing any binary project you'll build +in Rust, so we can justify doing this refactoring a bit earlier, since we know +that our project fits the pattern. The pattern looks like this: -1. Split your program into both a `main.rs` and a `lib.rs`. -2. Place your command-line parsing logic into `main.rs`. -3. Place your program's logic into `lib.rs`. +1. Split your program into both a *main.rs* and a *lib.rs*. +2. Place your command line parsing logic into *main.rs*. +3. Place your program's logic into *lib.rs*. 4. The job of the `main` function is: * parse arguments * set up any other configuration - * call a `run` function in `lib.rs` + * call a `run` function in *lib.rs* * if `run` returns an error, handle that error +Whew! The pattern sounds more complicated than it is, honestly. It's all about +separating concerns: *main.rs* handles actually running the program, and +*lib.rs* handles all of the actual logic of the task at hand. Let's re-work our +program into this pattern. First, let's extract a function whose purpose is +only to parse arguments. Listing 12-4 shows the new start of `main` that calls +a new function `parse_config`, which we're still going to define in +*src/main.rs*: -Whew! It sounds like a lot more than it is, honestly. It's all about separating -concerns: `main.rs` handles actually running the program, and `lib.rs` handles -all of the actual logic of the task at hand. This pattern has additional -benefits that we won't talk about just yet. Let's re-work our program into this -pattern. First, let's split out a function to parse arguments. Here's the new -start of `main`: +
+Filename: src/main.rs ```rust,ignore fn main() { @@ -293,53 +347,76 @@ fn main() { let (search, filename) = parse_config(&args); - println!("Searching for {}", search); - println!("In file {}", filename); -``` + // ...snip... +} -And the definition of `parse_config`: - -```rust,ignore fn parse_config(args: &[String]) -> (&str, &str) { let search = &args[1]; let filename = &args[2]; - + (search, filename) } ``` +
+ +Listing 12-4: Extract a `parse_config` function from `main` + +
+
+ + + This may seem like overkill, but we're working in small steps. After making -this change, run the program again to verify that things still work. It's good -to do this often. +this change, run the program again to verify that the argument parsing still +works. It's good to check your progress often, so that you have a better idea +of which change caused a problem, should you encounter one. + -Now that we have a function, let's improve it. Our code has a smell: we return -a tuple, but then immediately break that tuple up into individual parts again. -This isn't bad on its own, but there's one other thing: we called our function -`parse_config`. That is, these two variables should really be bound together, -as they're both part of a configuration. +Now that we have a function, let's improve it. Our code still has an indication +that there's a better design possible: we return a tuple, but then immediately +break that tuple up into individual parts again. This code isn't bad on its +own, but there's one other sign we have room for improvement: we called our +function `parse_config`. The `config` part of the name is saying the two values +we return should really be bound together, since they're both part of one +configuration value. -> Note: some people call this smell "primitive obsession." +> Note: some people call this antipattern of using primitive values when a +> complex type would be more appropriate *primitive obsession*. -Let's introduce a struct to hold all of our configuration. It will look like -this: +Let's introduce a struct to hold all of our configuration. Listing 12-5 shows +the addition of the `Config` struct definition, the refacting of `parse_config`, +and updates to `main`: + +
+Filename: src/main.rs ```rust +fn main() { + let args: Vec = env::args().collect(); + + let config = parse_config(&args); + + println!("Searching for {}", config.search); + println!("In file {}", config.filename); + + // ...snip... +} + struct Config { search: String, filename: String, } -``` -And we can refactor `parse_string` like this: - -```rust,ignore fn parse_config(args: &[String]) -> Config { let search = args[1].clone(); let filename = args[2].clone(); - + Config { search: search, filename: filename, @@ -347,43 +424,68 @@ fn parse_config(args: &[String]) -> Config { } ``` -We're now returning a `Config`, but there's one other change. We used to be -returning string slices, but our `Config` contains `String`s. And since we have -a slice of `String`s, we can't take ownership of them, as that violates Rust's -borrowing rules. There are a number of different things we could do in this -situation, but for now, we'll take the "easy but less efficient" route, and -call `clone`. This will make a full copy of the string's data, but it makes our -code very straightforward. There's a tendency amongst many Rustaceans to really -dislike calls to `clone` to fix ownership problems, due to that lack of -efficiency. In chapter XX on iterators, we'll learn the tricks we need to make -this more efficient. But for now, it's okay to copy a few strings to keep -making progress. We're only going to be making this copy one time, and our -filename and search string are both very small. It's better to have a working -program and have it be a bit inefficient then to try to hyper-optimize code on -your first pass. As you get more experienced with Rust, it'll be easier to skip -this step, but for now, just call `clone`. It's fine. +
-Whew, sorry about that little digression! Before our program works, we need to -update `main` as well: +Listing 12-5: Refactoring `parse_config` to return an instance of a `Config` +struct -```rust,ignore -let config = parse_config(&args); +
+
-println!("Searching for {}", config.search); -println!("In file {}", config.filename); + -let mut f = File::open(config.filename).expect("file not found"); -``` +The signature of `parse_config` now indicates that it returns a `Config` value. +In the body of `parse_config`, we used to be returning string slices that were +references to `String` values in `args`, but we've defined `Config` to contain +owend `String` values. Because the argument to `parse_config` is a slice of +`String` values, the `Config` instance can't take ownership of the `String` +values: that violates Rust's borrowing rules, since the `args` variable in +`main` owns the `String` values and is only letting the `parse_config` function +borrow them. -We now have a single `config` variable, and so we need to update everything to -use it instead of the old variables. +There are a number of different ways we could manage the `String` data; for +now, we'll take the easy but less efficient route, and call the `clone` method +on the string slices. The call to `clone` will make a full copy of the string's +data for the `Config` instance to own, which does take more time and memory +than storing a reference to the string data, but cloning the data makes our +code very straightforward. + +There's a tendency amongst many Rustaceans to prefer not to use `clone` to fix +ownership problems, due to its runtime cost. In Chapter XX on iterators, we'll +learn how to make this situation more efficient. For now, it's okay to copy a +few strings to keep making progress. We're only going to be making these copies +once, and our filename and search string are both very small. It's better to +have a working program that's a bit inefficient than try to hyper-optimize code +on your first pass. As you get more experienced with Rust, it'll be easier to +skip this step, but for now, it's perfectly acceptable to call `clone`. + +We've updated `main` to put the instance of `Config` that `parse_config` +returns in a variable named `config`, and we've updated the code that was using +the separate `search` and `filename` variables to use the fields on the +`Config` struct instead. This is getting pretty good! Give your program another run to make sure it's still working. We have two more refactorings to do here, though! Let's think -about `parse_config`. It's a function that creates a `Config`. We already know -a convention for this: a `new` method. Let's transform `parse_config` into one: +about the purpose of `parse_config`: it's a function that creates a `Config` +instance. We've already seen a convention for functions that create instances: +a `new` function, like `String::new`. Listing 12-6 shows the result of +transforming `parse_config` into a `new` function associated with our `Config` +struct: + +
+Filename: src/main.rs ```rust,ignore +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args); + + // ...snip... +} + +// ...snip... + impl Config { fn new(args: &[String]) -> Config { let search = args[1].clone(); @@ -397,28 +499,48 @@ impl Config { } ``` -The only changes here are putting it into an `impl` block and changing the name -to `new`. Easy! We do need to update the callsite in `main` too, though: +
-```rust,ignore -let config = Config::new(&args); -``` +Listing 12-6: Changing `parse_config` into `Config::new` -Try compiling this again to make sure it works. +
+
-Here's our last refactoring: remember how accessing the vector with incorrect -indices panics and gives a bad error message? Let's fix that! To do that, we -can check that our slice is long enough: + + +We've changed the name of `parse_config` to `new` and moved it within an `impl` +block. We've also updated the callsite in `main`. Try compiling this again to +make sure it works. + +Here's our last refactoring of this method: remember how accessing the vector +with indices 1 and 2 panics when it contains fewer than 3 items and gives a bad +error message? Let's fix that! Listing 12-7 shows how we can check that our +slice is long enough before accessing those locations, and panic with a better +error message: + +
+Filename: src/main.rs ```rust,ignore +// ...snip... fn new(args: &[String]) -> Config { if args.len() < 3 { panic!("not enough arguments"); } + // ...snip... ``` -With these extra few lines of code in `new`, let's try running our program with -incorrect arguments: +
+ +Listing 12-7: Adding a check for the number of arguments + +
+
+ + + +With these extra few lines of code in `new`, let's try running our program +without any arguments: ```bash $ cargo run @@ -428,12 +550,15 @@ thread 'main' panicked at 'not enough arguments', src\main.rs:29 note: Run with `RUST_BACKTRACE=1` for a backtrace. ``` -This is a bit better! We at least have a reasonable panic message here. -However, we also have a bunch of extra information here that we don't want to -give to our users. We can do better. To do that, we need to change the type -signature of `new`. Right now, because it returns only a `Config`, there's no -way to indicate that an error happened while creating our `Config`. So instead, -we can use `Result`, like this: +This is a bit better! We at least have a reasonable error message here. +However, we also have a bunch of extra information that we don't want to give +to our users. We can do better by changing the type signature of `new`. Right +now, it returns only a `Config`, so there's no way to indicate that an error +happened while creating our `Config`. Instead, we can return a `Result`, as +shown in Listing 12-8: + +
+Filename: src/main.rs ```rust,ignore impl Config { @@ -453,21 +578,34 @@ impl Config { } ``` -Our `new` function now gives us a `Result`, with a `&'static str` as our error -message. Remember, this is the type of string literals, which is what our error -message is right now. +
-We've made two changes in the body: instead of `panic!`ing, we now return an -`Err`, and we wrapped our return value in an `Ok`. This makes it conform to the -new type signature. +Listing 12-8: Return a `Result` from `Config::new` -Finally, we make some changes in `main`. Up top, we need a new `use` line: +
+
+ + + +Our `new` function now returns a `Result`, with a `Config` instance in the +success case and a `&'static str` when an error happens. Recall from "The +Static Lifetime" section in Chapter 10 `&'static str` is the type of string +literals, which is what our error message is for now. + +We've made two changes in the body of the `new` function: instead of calling +`panic!` if there aren't enough arguments, we now return an `Err` value. We +wrapped the `Config` return value in an `Ok`. These changes make the function +conform to its new type signature. + +Additionally, we're going to add a new `use` line: ```rust,ignore use std::process; ``` -And then in the main function itself: +And in the `main` function itself, we'll handle the `Result` value returned +from the `new` function and exit the process in a cleaner way if `Config::new` +returns an `Err` value: ```rust,ignore fn main() { @@ -477,41 +615,49 @@ fn main() { println!("Problem parsing arguments: {}", err); process::exit(1); }); + + // ...snip... ``` -Here, we see a new method on `Result`: `unwrap_or_else`. This method does -something similar to `unwrap`; that is, if the `Result` is `Ok`, it -returns the inner value `Ok` is wrapping. But unlike `unwrap`, if the value is -an `Err`, it instead calls a closure, passing the inner value of the `Err` to -it. This lets us do some custom, non-`panic!` error handling. + -Said error handling is only two lines: we print out the error, and then call +We're using a method we haven't covered before that's defined on `Result` +by the standard library: `unwrap_or_else`. This method has similar behavior as +`unwrap` if the `Result` is an `Ok` value: it returns the inner value `Ok` is +wrapping. Unlike `unwrap`, if the value is an `Err` value, this method calls a +*closure* which is an anonymous function that we define and pass as an argument +to `unwrap_or_else`. We'll be covering closures in more detail in Chapter XX; +the important part to understand in this case is that `unwrap_or_else` will +pass the inner value of the `Err` to our closure in the argument `err` that +appears between the vertical pipes. Using `unwrap_or_else` lets us do some +custom, non-`panic!` error handling. + +Said error handling is only two lines: we print out the error, then call `std::process::exit`. That function will stop our program's execution -immediately, and return the number passed to it as a return code. By convention, -a zero means success and any other value means failure. So in the end, this has -similar characteristics to our `panic!`-based handling from before, but we no -longer get all the extra output. Let's try it: +immediately and return the number passed to it as a return code. By convention, +a zero means success and any other value means failure. In the end, this has +similar characteristics to our `panic!`-based handling we had in Listing 12-7, +but we no longer get all the extra output. Let's try it: ```bash $ cargo run - Compiling greprs v0.1.0 (file:///C:/Users/steve/tmp/greprs) + Compiling greprs v0.1.0 (file:///project/greprs) Finished debug [unoptimized + debuginfo] target(s) in 0.48 secs Running `target\debug\greprs.exe` Problem parsing arguments: not enough arguments ``` -Great! This is much nicer. Now that we're done with fixing up our configuration -parsing, let's do some work on our program's logic. Let's create a new function, -and then call it from `main`: +Great! This output is much friendlier for our users. Now that we're done +refactoring our configuration parsing, let's improve our program's logic. +Listing 12-9 shows the code after extracting a function named `run` that we'll +call from `main`. The `run` function contains the code that was in `main`: + +
+Filename: src/main.rs ```rust,ignore fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - println!("Problem parsing arguments: {}", err); - process::exit(1); - }); + // ...snip... println!("Searching for {}", config.search); println!("In file {}", config.filename); @@ -527,21 +673,35 @@ fn run(config: Config) { println!("With text:\n{}", contents); } + +// ...snip... ``` -The contents of `run` are the previous lines that were in `main`, and we take a -`Config` as an argument. Now that we have a separate function, we can do -something very similar to what we did with `Config::new`: let's have it return -a `Result` instead of `panic!`ing with `expect`. First, we need to add a -line at the top: +
-```rust -use std::error::Error; -``` +Listing 12-9: Extracting a `run` functionality for the rest of the program logic -And then change our `run()` function to look like this: +
+
+ + + +The contents of `run` are the previous lines that were in `main`, and the `run` +function takes a `Config` as an argument. Now that we have a separate function, +we can make a similar improvement to the one we made to `Config::new` in +Listing 12-8: let's return a `Result` instead of calling `panic!` via +`expect`. Listing 12-10 shows the addition of a `use` statement to bring +`std::error::Error` struct into scope and the changes to the `run` function +to return a `Result`: + +
+Filename: src/main.rs ```rust,ignore +use std::error::Error; + +// ...snip... + fn run(config: Config) -> Result<(), Box> { let mut f = File::open(config.filename)?; @@ -554,13 +714,23 @@ fn run(config: Config) -> Result<(), Box> { } ``` -We have three big changes here. The first is the return type: `Result<(), -Box>`. Previously, our function returned nothing, aka `()`, so that's -still our `Ok` case. For our error type, we're going to use `Box`. This -is called a "trait object," which we'll be covering in chapter XX. For now, -think of it like this: a `Box` means "I just want some kind of error, -I don't care what specific kind." We could do something more specialized, but -this is the most straightforward thing for now. +
+ +Listing 12-10: Changing the `run` function to return `Result` + +
+
+ + + +We've made three big changes here. The first is the return type of the `run` +function is now `Result<(), Box>`. Previously, our function returned the +unit type, `()`, so that's still the value returned in the `Ok` case. For our +error type, we're going to use `Box`. This is called a *trait object*, +which we'll be covering in Chapter XX. For now, think of it like this: +`Box` means the function will return some kind of type that implements +the `Error` trait, but we're not specifying what particular type the return +value will be. This gives us flexibility because... `Box` means... Secondly, we've removed our calls to `expect` in favor of `?`, like we talked about in chapter XX. Rather than `panic!` on an error, this will instead return @@ -604,7 +774,7 @@ two things: In this case, because `run` returns a `()` in the success case, the only thing we care about is the first case: detecting an error. If we used `unwrap_or_else`, we'd have to save its return value, which would be `()`. -That's not very useful. +That's not very useful. The bodies are the same in both cases though: we print out an error and exit. @@ -693,7 +863,7 @@ in a much nicer fashion, and we've made our code slightly more modular. Let's take advantage of this newfound modularity by doing something that would have been hard with our old code, but is easy with our new code: write some tests! - + ## Tests We need to write a function, `grep`, that takes our search term and the text to @@ -750,7 +920,7 @@ Pick three."; Being able to do this test is enabled by all that modularization work we did in the previous sections. By separating the code that relies on dealing with the environment from our core logic, we can write very straightforward tests -that don't need to load files or deal with command-line arguments. Nice! +that don't need to load files or deal with command line arguments. Nice! Before we run the test, let's talk about this type signature: @@ -938,12 +1108,12 @@ To an admiring bog! Excellent! We've built our own version of a classic tool, and learned a lot about how to structure applications. We've also learned a bit about file input and output, -and command-line parsing. +and command line parsing. ## Working with Environment Variables Let's add one more feature: case insensitive searching. In addtion, this setting won't -be a command-line option: it'll be an environment variable instead. But first, let's +be a command line option: it'll be an environment variable instead. But first, let's build out the functionality. Let's add a new test, and re-name our existing one: ```rust,ignore @@ -1097,7 +1267,7 @@ impl Config { ``` Here, we call `env::vars`, which is kind of like `env::args`. The difference? -It returns an iterator of environment variables, rather than command-line +It returns an iterator of environment variables, rather than command line arguments. Instead of using `collect` to create a vector of all of the environment variables, we instead use a `for` loop. `env::vars` returns tuples: the name of the environment varaible, and then its value. We never care about From 3cd2cb289031f1d10d9f36933df120eef045cbd6 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 27 Dec 2016 09:29:47 -0500 Subject: [PATCH 13/25] finish up the last bit --- src/ch12-00-an-io-project.md | 64 +++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 43fb85659..798a15cc1 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -1304,45 +1304,48 @@ its documentation for more goodies. ## Write to `stderr` Instead of `stdout` -Let's say we want to output any errors to `stderr` instead of `stdout`. Right now, if we run: +Right now, we're writing all of our output to the terminal with `println!`. +This works, but most terminals provide two kinds of output: "standard out" is +used for most things, but "standard error" is used for error messages. This +makes it easier to do things like "Print error messages to my terminal, but +write other output to a file." + +We can try this behavior with `>`: ```text $ cargo run > output.txt ``` -The contents of *output.txt* will be: +The `>` syntax says, "please write the contents of standard out to +`output.txt`." If we open *output.txt* we'll see: ```text Application error: No search string or filename found ``` -Even if we're saving the output to a file, we want to see errors on the screen. +We'd like this to be printed to the screen instead. Let's make a change! + Filename: src/main.rs ```rust,ignore extern crate greprs; -use greprs::Config; - use std::env; use std::process; -use std::io::prelude::*; + +use greprs::Config; fn main() { - let mut args = env::args(); + let args: Vec = env::args().collect(); - // Discard the name of the binary - args.next(); + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); - let case_insensitive = env::vars().find(|&(ref var, _)| { - var == "CASE_INSENSITIVE" - }).is_some(); - - let config = Config { - arguments: args.collect(), - case_insensitive: case_insensitive, - }; + println!("Searching for {}", config.search); + println!("In file {}", config.filename); if let Err(e) = greprs::run(config) { let mut stderr = std::io::stderr(); @@ -1358,12 +1361,33 @@ fn main() { } ``` -Now the output when we don't pass any arguments but redirect stdout to a file -is: +Rust does not have a convenient function like `println!` for writing to +standard error. Instead, we use the `writeln!` macro, which is sort of like +`println!`, but it takes an extra argument: the first thing we pass to it is +what to write to. We can aquire a handle to standard error through the +`std::io::stderr` function, and we give a mutable reference to it to +`wrintln!`; we need it to be mutable so we can write to it! The second and +third arguments to `writeln!` are like the first and second arguments to +`println!`: a format string, and then any variables we're interpolating. + +Let's try running it again with `>`: ```text $ cargo run > output.txt Application error: No search string or filename found ``` -and the file is empty. +Now we see our error on the screen, but `output.txt` contains nothing. +If we try it again with good arguments: + +```text +$ cargo run to poem.txt > output.txt +``` + +We'll see no output to our terminal, but `output.txt` will contain +our results: + +```text +Are you nobody, too? +How dreary to be somebody! +``` From 99db5097379c68afb0a587b39bb8f8ccdff8db7e Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 27 Dec 2016 18:17:05 -0500 Subject: [PATCH 14/25] Get code blocks to compile --- src/ch12-00-an-io-project.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 798a15cc1..947408284 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -397,6 +397,8 @@ and updates to `main`: Filename: src/main.rs ```rust +# use std::env; +# fn main() { let args: Vec = env::args().collect(); @@ -475,7 +477,8 @@ struct:
Filename: src/main.rs -```rust,ignore +```rust + fn main() { let args: Vec = env::args().collect(); @@ -484,6 +487,11 @@ fn main() { // ...snip... } +# struct Config { +# search: String, +# filename: String, +# } +# // ...snip... impl Config { @@ -561,6 +569,11 @@ shown in Listing 12-8: Filename: src/main.rs ```rust,ignore +# struct Config { +# search: String, +# filename: String, +# } +# impl Config { fn new(args: &[String]) -> Result { if args.len() < 3 { @@ -876,6 +889,18 @@ function: File: src/lib.rs ```rust +# use std::error::Error; +# use std::fs::File; +# use std::io::prelude::*; +# pub struct Config { +# pub search: String, +# pub filename: String, +# } +# +# fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { +# vec![] +# } +# pub fn run(config: Config) -> Result<(), Box>{ let mut f = File::open(config.filename)?; @@ -1240,6 +1265,14 @@ use std::env; And then using the `vars` method from it inside of `new`: ```rust +# use std::env; +# +# struct Config { +# search: String, +# filename: String, +# case_sensitive: bool, +# } +# impl Config { pub fn new(args: &[String]) -> Result { if args.len() < 3 { From 991844d9aeeea59f5190f4555ca1bfb0ba8ecdd9 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 28 Dec 2016 18:02:59 -0500 Subject: [PATCH 15/25] Finish my first edit of ch 12 --- src/ch12-00-an-io-project.md | 472 +++++++++++++++++++++++------------ 1 file changed, 314 insertions(+), 158 deletions(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 947408284..5da78a2f5 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -610,17 +610,14 @@ We've made two changes in the body of the `new` function: instead of calling wrapped the `Config` return value in an `Ok`. These changes make the function conform to its new type signature. -Additionally, we're going to add a new `use` line: +Now we need to make some changes to `main` as shown in Listing 12-9: + +
+Filename: src/main.rs ```rust,ignore use std::process; -``` -And in the `main` function itself, we'll handle the `Result` value returned -from the `new` function and exit the process in a cleaner way if `Config::new` -returns an `Err` value: - -```rust,ignore fn main() { let args: Vec = env::args().collect(); @@ -632,8 +629,20 @@ fn main() { // ...snip... ``` +
+ +Listing 12-9: Exiting with an error code if creating a new `Config` fails + +
+
+ +We've added a new `use` line to import `process` from the standard library. +In the `main` function itself, we'll handle the `Result` value returned +from the `new` function and exit the process in a cleaner way if `Config::new` +returns an `Err` value. + We're using a method we haven't covered before that's defined on `Result` by the standard library: `unwrap_or_else`. This method has similar behavior as `unwrap` if the `Result` is an `Ok` value: it returns the inner value `Ok` is @@ -662,7 +671,7 @@ Problem parsing arguments: not enough arguments Great! This output is much friendlier for our users. Now that we're done refactoring our configuration parsing, let's improve our program's logic. -Listing 12-9 shows the code after extracting a function named `run` that we'll +Listing 12-10 shows the code after extracting a function named `run` that we'll call from `main`. The `run` function contains the code that was in `main`:
@@ -692,7 +701,7 @@ fn run(config: Config) {
-Listing 12-9: Extracting a `run` functionality for the rest of the program logic +Listing 12-10: Extracting a `run` functionality for the rest of the program logic
@@ -703,7 +712,7 @@ The contents of `run` are the previous lines that were in `main`, and the `run` function takes a `Config` as an argument. Now that we have a separate function, we can make a similar improvement to the one we made to `Config::new` in Listing 12-8: let's return a `Result` instead of calling `panic!` via -`expect`. Listing 12-10 shows the addition of a `use` statement to bring +`expect`. Listing 12-11 shows the addition of a `use` statement to bring `std::error::Error` struct into scope and the changes to the `run` function to return a `Result`: @@ -729,7 +738,7 @@ fn run(config: Config) -> Result<(), Box> {
-Listing 12-10: Changing the `run` function to return `Result` +Listing 12-11: Changing the `run` function to return `Result`
@@ -743,17 +752,20 @@ error type, we're going to use `Box`. This is called a *trait object*, which we'll be covering in Chapter XX. For now, think of it like this: `Box` means the function will return some kind of type that implements the `Error` trait, but we're not specifying what particular type the return -value will be. This gives us flexibility because... `Box` means... +value will be. This gives us flexibility to return error values that may be of +different types in different error cases. `Box` is a smart pointer to heap +data, and we'll be going into detail about `Box` in Chapter YY. -Secondly, we've removed our calls to `expect` in favor of `?`, like we talked -about in chapter XX. Rather than `panic!` on an error, this will instead return -the result from the function we're in, as we talked about in that chapter. +The second change is that we've removed our calls to `expect` in favor of `?`, +like we talked about in Chapter 9. Rather than `panic!` on an error, this will +return the error value from the function we're in for the caller to handle. -Finally, we have to return an `Ok` value from this function, and since we have -declared its type as `()` in our function signature, we need `Ok(())`. This -looks a bit strange at first, but using `()` in this way is the idiomatic way -to say "we are calling `run` for its side effects only, it doesn't return a -value of anything interesting." +The third change is that we're now returning an `Ok` value from this function +in the success case. Because we've declared the `run` function's success type +as `()` in the signature, we need to wrap the unit type value in the `Ok` +value. `Ok(())` looks a bit strange at first, but using `()` in this way is the +idiomatic way to indicate that we're calling `run` for its side effects only; +it doesn't return anything interesting. This will compile, but with a warning: @@ -765,20 +777,33 @@ warning: unused result which must be used, #[warn(unused_must_use)] on by defaul | ^^^^^^^^^^^^ ``` -Rust is trying to tell us that we're ignoring our result, which may fail. Let's -handle that now. It similar to the way we handled failure with `Config::new`, -but slightly different: +Rust is trying to tell us that we're ignoring our `Result`, which might be an +error value. Let's handle that now. We'll use a similar technique as the way we +handled failure with `Config::new` in Listing 12-9, but with a slight +difference: + +Filename: src/main.rs ```rust,ignore -if let Err(e) = run(config) { - println!("Application error: {}", e); +fn main() { + // ...snip... - process::exit(1); + println!("Searching for {}", config.search); + println!("In file {}", config.filename); + + if let Err(e) = run(config) { + println!("Application error: {}", e); + + process::exit(1); + } } ``` + + Instead of `unwrap_or_else`, we use `if let` to see if `run` returns an `Err` -value. Why? The distinction is a bit subtle. With `Config::new`, we cared about +value and call `process::exit(1)` if so. Why? The distinction between this case +and the `Config::new` case is a bit subtle. With `Config::new`, we cared about two things: 1. Detecting any errors that happen @@ -786,15 +811,21 @@ two things: In this case, because `run` returns a `()` in the success case, the only thing we care about is the first case: detecting an error. If we used -`unwrap_or_else`, we'd have to save its return value, which would be `()`. -That's not very useful. +`unwrap_or_else`, we'd get its return value, which would be `()`. That's not +very useful. -The bodies are the same in both cases though: we print out an error and exit. +The bodies of the `if let` and of the `unwrap_or_else` are the same in both +cases though: we print out an error and exit. This is looking pretty good! There's one more thing we haven't done yet: split -things up into a `lib.rs` as well. Let's do that now. Move `run` from `main.rs` -to a new file, `src/lib.rs`. You'll also need to move the relevant `use` -statements, as well as `Config`: +the *src/main.rs* up and put some code into *src/lib.rs* Let's do that now: +move the `run` function from *src/main.rs* to a new file, *src/lib.rs*. You'll +also need to move the relevant `use` statements and the definition of `Config` +and its `new` method as well. Your *src/lib.rs* should now look like Listing +12-12: + +
+Filename: src/lib.rs ```rust,ignore use std::error::Error; @@ -834,11 +865,25 @@ pub fn run(config: Config) -> Result<(), Box>{ } ``` -Notice we also made liberal use of `pub`: on `Config`, its `new` function, -and its elements. In addition, on `run`. +
-Now, for `main.rs`. We need to add in our `lib.rs` through `extern crate`, -use `Config`, and prefix the `run` function with our crate name: +Listing 12-12: Moving `Config` and `run` into *src/lib.rs* + +
+
+ + + +Notice we also made liberal use of `pub`: on `Config`, its fields and its `new` +method, and on the `run` function. + +Now in *src/main.rs*, we need to bring in the code that's now in *src/lib.rs* +through `extern crate greprs`. Then we need to add a `use greprs::Config` line +to bring `Corfig` into scope, and prefix the `run` function with our crate name +as shown in Listing 12-13: + +
+Filename: src/main.rs ```rust,ignore extern crate greprs; @@ -867,26 +912,45 @@ fn main() { } ``` +
+ +Listing 12-13: Bringing the `greprs` crate into the scope of *src/main.rs* + +
+
+ + + With that, everything should work again. Give it a few `cargo run`s and make sure you haven't broken anything. Whew! That all was a lot of work, but we've -set ourselves up for success in the future. Almost all of our work will be -done in the library from here on out, but we've set up a way to handle errors -in a much nicer fashion, and we've made our code slightly more modular. +set ourselves up for success in the future. We've set up a way to handle errors +in a much nicer fashion, and we've made our code slightly more modular. Almost +all of our work will be done in *src/lib.rs* from here on out. Let's take advantage of this newfound modularity by doing something that would have been hard with our old code, but is easy with our new code: write some tests! -## Tests +## Testing the Library's Functionality -We need to write a function, `grep`, that takes our search term and the text to -search, and procudes a list of search results. Let's remove that `println!` from -`run` (and probably from `main.rs` as well, as we don't really need those anymore -either), and call this function with the options we've collected. We'll add a -dummy implementation of the function, and some tests. Here's our new `run` -function: +Writing tests for the core functionality of our code is now easier since we +extracted the logic into *src/lib.rs* and left all the argument parsing and +error handling in *src/main.rs*. We can now call our code directly with various +arguments and check return values without having to call our binary from the +command line. -File: src/lib.rs +We're going to write a function named `grep` that takes our search term and the +text to search and procudes a list of search results. Let's remove that +`println!` from `run` (and from *src/main.rs* as well, as we don't really need +those anymore either), and call the new `grep` function with the options we've +collected. We'll add a placeholder implementation of the function for now, and +a test that specifies the behavior we'd like the `grep` function to have. The +test will fail with our placeholder implementation, of course, but we can make +sure the code compiles and that we get the failure message we expect. Listing +12-14 shows these modifications: + +
+Filename: src/lib.rs ```rust # use std::error::Error; @@ -897,10 +961,10 @@ File: src/lib.rs # pub filename: String, # } # -# fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { -# vec![] -# } -# +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + vec![] +} + pub fn run(config: Config) -> Result<(), Box>{ let mut f = File::open(config.filename)?; @@ -911,16 +975,6 @@ pub fn run(config: Config) -> Result<(), Box>{ Ok(()) } -``` - -And then our new definitions of `grep` and a test: - -File: src/lib.rs - -```rust -fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - vec![] -} #[cfg(test)] mod test { @@ -942,27 +996,29 @@ Pick three."; } ``` -Being able to do this test is enabled by all that modularization work we did -in the previous sections. By separating the code that relies on dealing with -the environment from our core logic, we can write very straightforward tests -that don't need to load files or deal with command line arguments. Nice! +
-Before we run the test, let's talk about this type signature: +Listing 12-14: Creating a function where our logic will go and a failing test +for that function -```rust,ignore -fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { -``` +
+
-We need an explicit lifetime on `grep`, which is what the `<'a>` business is -all about. But why? And what does it do? + -Remember, the `'a`s are used to connect the lifetimes of different arguments to -our function. So in this case, we're saying that the vector we're returning is -going to have `&str`s that reference `contents`, not `search`. This is -important! Given that slices and references need to always be valid, if Rust -thought that we were making string slices of `search`, rather than `contents`, -it would do its safety checking incorrectly. If we tried to compile this -function without lifetimes, Rust would fail to compile it: +Notice that we need an explicit lifetime `'a` declared in the signature of +`grep` and used with the `contents` argument and the return value. Remember, +lifetime parameters are used to specify which arguments' lifetimes connect to +the lifetime of the return value. In this case, we're indicating that the +vector we're returning is going to contain string slices that reference slices +of the argument `contents`, as opposed to referencing slices of the argument +`search`. Another way to think about what we're telling Rust is that the data +returned by the `grep` function will live as long as the data passed into this +function in the `contents` argument. This is important! Given that the data a +slice references needs to be valid in order for the reference to be valid, if +the compiler thought that we were making string slices of `search` rather than +`contents`, it would do its safety checking incorrectly. If we tried to compile +this function without lifetimes, we would get this error: ```text error[E0106]: missing lifetime specifier @@ -977,15 +1033,17 @@ error[E0106]: missing lifetime specifier ``` Rust can't possibly know which of the two arguments we need, so it needs us to -tell it. Since `contents` is the string that contains all of our text, we know -that's the one that our results will refer to, not the search string. And so, -we use the lifetime syntax to connect the two. +tell it. Because `contents` is the argument that contains all of our text and +we want to return the parts of that text that match, we know `contents` is the +argument that should be connected to the return value using the lifetime syntax. -The above situation is a little tricky at first, but it gets easier over time! -Practice makes perfect. Don't feel bad if you need to re-read the above -section, and maybe go back and compare with chapter XX's lifetimes section. +Connecting arguments to return values in the signature is something that other +programming langugages don't make you do, so don't worry if this still feels +strange! Knowing how to specify lifetimes gets easier over time, and practice +makes perfect. You may want to re-read the above section or go back and compare +this example with the Lifetime Syntax section in Chapter 10. -Now that we understand that, let's try running our test: +Now let's try running our test: ```text $ cargo test @@ -999,7 +1057,8 @@ test test::one_result ... FAILED failures: ---- test::one_result stdout ---- - thread 'test::one_result' panicked at 'assertion failed: `(left == right)` (left: `["safe, fast, productive."]`, right: `[]`)', src/lib.rs:16 + thread 'test::one_result' panicked at 'assertion failed: `(left == right)` +(left: `["safe, fast, productive."]`, right: `[]`)', src/lib.rs:16 note: Run with `RUST_BACKTRACE=1` for a backtrace. @@ -1012,17 +1071,19 @@ error: test failed ``` Great, our test fails, exactly as we expected. Let's get the test to pass! It's -failing because we always return an empty vector. Here's what we have to do +failing because we always return an empty vector. Here's what we're going to do to implement `grep`: 1. Iterate through each line of the contents. 2. Check if the line contains our search string. * If it does, add it to the list of values we're returning. - * If not, do nothing -3. Return our list of results. + * If not, do nothing. +3. Return the list of results that match. -Let's take each step at a time. First, iterating through lines. Strings have -a helpful method to handle this, conveniently named `lines`: +Let's take each step at a time, starting with iterating through lines. Strings +have a helpful method to handle this, conveniently named `lines`: + +Filename: src/lib.rs ```rust,ignore fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { @@ -1032,9 +1093,14 @@ fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { } ``` -We can use a `for` loop along with the `lines` method to get each line in turn. + + +We're using a `for` loop along with the `lines` method to get each line in turn. Next, let's see if our line contains the search string. Luckily, strings have a -helpful method named `contains` that does this for us! It looks like this: +helpful method named `contains` that does this for us! Using the `contains` +method looks like this: + +Filename: src/lib.rs ```rust,ignore fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { @@ -1046,8 +1112,14 @@ fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { } ``` -Finally, we need a way to store these lines that contian our search string. -For that, we can make a vector: + + +Finally, we need a way to store the lines that contain our search string. For +that, we can make a mutable vector before the `for` loop and call the `push` +method to store a `line` in the vector. After the `for` loop, we return the +vector: + +Filename: src/lib.rs ```rust,ignore fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { @@ -1063,6 +1135,8 @@ fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { } ``` + + Let's give it a try: ```text @@ -1085,13 +1159,18 @@ running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured ``` -Great! It works. However, we can do better. This code isn't bad, but it's very -focused on the fiddly details of each step. We can do better, but to do so, we -need to learn more about iterators and how they work. We'll come back to this -example in that chapter and see how to improve it. +Great! It works. Now that our test is passing, we could consider opportunities +for refactoring the implementation of `grep` and be certain we maintain the +same functionality while we do so. This code isn't bad, but it isn't taking +advantage of some useful features of iterators. We'll be coming back to this +example in Chapter 13 where we'll explore iterators in detail and see how to +improve it. -Now that `grep` is working, we need to do one last thing inside of `run`: we never -printed out the results! Try this: +Now that the `grep` function is working, we need to do one last thing inside of +the `run` function: we never printed out the results! We'll do that by adding +a `for` loop that prints each line returned from the `grep` function: + +Filename: src/lib.rs ```rust,ignore pub fn run(config: Config) -> Result<(), Box>{ @@ -1108,8 +1187,9 @@ pub fn run(config: Config) -> Result<(), Box>{ } ``` -We've added a `for` loop to print out each of the lines we get back from -`grep`. Now it all should be working! Let's try it out: + + +Now our whole program should be working! Let's try it out: ```text $ cargo run the poem.txt @@ -1131,15 +1211,22 @@ To tell your name the livelong day To an admiring bog! ``` -Excellent! We've built our own version of a classic tool, and learned a lot about -how to structure applications. We've also learned a bit about file input and output, -and command line parsing. +Excellent! We've built our own version of a classic tool, and learned a lot +about how to structure applications. We've also learned a bit about file input +and output, lifetimes, testing, and command line parsing. ## Working with Environment Variables -Let's add one more feature: case insensitive searching. In addtion, this setting won't -be a command line option: it'll be an environment variable instead. But first, let's -build out the functionality. Let's add a new test, and re-name our existing one: +Let's add one more feature: case insensitive searching. In addtion, this +setting won't be a command line option: it'll be an environment variable +instead. We could choose to make case insensitivity a command line option, but +our users have requested an environment variable that they could set once and +make all their searches case insensitive in that terminal session. + +### Implement and Test a Case-Insensitive `grep` Function + +First, let's add a new function that we will call when the environment variable +is on. Let's start by adding a new test and re-naming our existing one: ```rust,ignore #[cfg(test)] @@ -1178,21 +1265,21 @@ Trust me."; } ``` + -### Implement and Test a Case-Insensitive `grep` Function +We're going to define a new function named `grep_case_insensitive`. Its +implementation will be almost the same as the `grep` function, but with some +minor changes: -We also need to define a new function, `grep_case_insensitive`. We -can do this easily: it's almost the same as `grep`, but with one -minor change: - -Filename: src/lib.rs +Filename: src/lib.rs ```rust fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + let search = search.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { - if line.to_lowercase().contains(search) { + if line.to_lowercase().contains(&search) { results.push(line); } } @@ -1201,8 +1288,17 @@ fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { } ``` -All we need to change is add a call to `to_lowercase`. Now, we'll ignore the case -of our contents when searching. Let's see if it works: + + +First, we lowercase the `search` string, and store it in a shadowed variable +with the same name. Note that `search` is now a `String` rather than a string +slice, so we need to add an ampersand when we pass `search` to `contains` since +`contains` takes a string slice. + +Second, we add a call to `to_lowercase` each `line` before we check if it +contains `search`. Since we've converted both `line` and `search` into all +lowercase, we'll find matches no matter what case they used in the file and the +command line arguments, respectively. Let's see if this passes the tests: ```text Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs @@ -1227,8 +1323,10 @@ running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured ``` -Great! Now, we have to actually use it inside of our library. First, let's -add a configuration option for it: +Great! Now, we have to actually use the new `grep_case_insensitive` function. +First, let's add a configuration option for it to the `Config` struct: + +Filename: src/lib.rs ```rust pub struct Config { @@ -1238,9 +1336,20 @@ pub struct Config { } ``` -And then check for that option inside of `run`: + + +And then check for that option inside of the `run` function, and decide which +function to call based on the value of the `case_sensitive` function: + +Filename: src/lib.rs ```rust,ignore +pub fn run(config: Config) -> Result<(), Box>{ + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + let results = if config.case_sensitive { grep(&config.search, &contents) } else { @@ -1250,19 +1359,26 @@ And then check for that option inside of `run`: for line in results { println!("{}", line); } + + Ok(()) +} ``` -We check our configuration, and call the correct function for its setting. -We save the result to a variable, and then do the printing. + -Finally, we need to actually check the environment for the variable. This means -two things. First, we add a `use` line at the top of `lib.rs`: +Finally, we need to actually check the environment for the variable. To bring +the `env` module from the standard library into our project, we add a `use` line +at the top of *src/lib.rs*: + +Filename: src/lib.rs ```rust use std::env; ``` -And then using the `vars` method from it inside of `new`: +And then use the `vars` method from the `env` module inside of `Config::new`: + +Filename: src/lib.rs ```rust # use std::env; @@ -1285,7 +1401,7 @@ impl Config { let mut case_sensitive = true; for (name, _) in env::vars() { - if name == "CASE_INSENSITIVE" { + if name == "CASE_INSENSITIVE" { case_sensitive = false; } } @@ -1299,14 +1415,19 @@ impl Config { } ``` -Here, we call `env::vars`, which is kind of like `env::args`. The difference? -It returns an iterator of environment variables, rather than command line -arguments. Instead of using `collect` to create a vector of all of the -environment variables, we instead use a `for` loop. `env::vars` returns tuples: -the name of the environment varaible, and then its value. We never care about -the values, so we use a `_` to let Rust know that. Finally, we have a -`case_sensitive` variable, which is set to true by default. If we ever find a -`CASE_INSENSITIVE` environment variable, we set it to false instead. + + +Here, we call `env::vars`, which works in a similar way as `env::args`. The +difference is `env::vars` returns an iterator of environment variables rather +than command line arguments. Instead of using `collect` to create a vector of +all of the environment variables, we're using a `for` loop. `env::vars` returns +tuples: the name of the environment variable and its value. We never care about +the values, only if the variable is set at all, so we use the `_` placeholder +instead of a name to let Rust know that it shouldn't warn us about an unused +variable. Finally, we have a `case_sensitive` variable, which is set to true by +default. If we ever find a `CASE_INSENSITIVE` environment variable, we set the +`case_sensitive` variable to false instead. Then we return the value as part of +the `Config`. Let's give it a try! @@ -1328,38 +1449,50 @@ To tell your name the livelong day To an admiring bog! ``` -Excellent! Some programs are configurable through environement variables, and some -allow both arguments _and_ environment variables, and decide that one or the other takes -precedence. But now you know how to handle either strategy. +Excellent! Our `greprs` program can now do case insensitive searching controlled +by an environment variable. Now you know how to manage options set using +either command line arguments or environment variables! -There's a lot more stuff in `std::env` for dealing with environment variables; check out -its documentation for more goodies. +Some programs allow both arguments _and_ environment variables for the same +configuration. In those cases, the programs decide that one or the other of +arguments or environment variables take precedence. For another exercise on +your own, try controlling case insensitivity through a command line argument as +well, and decide which should take precedence if you run the program with +contradictory values. + +The `std::env` module contains many more useful features for dealing with +environment variables; check out its documentation to see what's available. ## Write to `stderr` Instead of `stdout` Right now, we're writing all of our output to the terminal with `println!`. This works, but most terminals provide two kinds of output: "standard out" is -used for most things, but "standard error" is used for error messages. This +used for most information, but "standard error" is used for error messages. This makes it easier to do things like "Print error messages to my terminal, but write other output to a file." -We can try this behavior with `>`: +We can see that our program is only capable of printing to `stdout` by +redirecting it to a file using `>` on the command line, and running our program +without any arguments, which causes an error: ```text $ cargo run > output.txt ``` -The `>` syntax says, "please write the contents of standard out to -`output.txt`." If we open *output.txt* we'll see: +The `>` syntax tells the shell to write the contents of standard out to +*output.txt* instead of the screen. However, if we open *output.txt* after +running we'll see our error message: ```text Application error: No search string or filename found ``` -We'd like this to be printed to the screen instead. Let's make a change! +We'd like this to be printed to the screen instead, and only have the output +from a successful run end up in the file if we run our program this way. Let's +change how error messages are printed as shown in Listing 12-15: - -Filename: src/main.rs +
+Filename: src/main.rs ```rust,ignore extern crate greprs; @@ -1377,9 +1510,6 @@ fn main() { process::exit(1); }); - println!("Searching for {}", config.search); - println!("In file {}", config.filename); - if let Err(e) = greprs::run(config) { let mut stderr = std::io::stderr(); @@ -1394,24 +1524,34 @@ fn main() { } ``` +
+ +Listing 12-15: Writing error messages to `stderr` instead of `stdout` + +
+
+ + + Rust does not have a convenient function like `println!` for writing to standard error. Instead, we use the `writeln!` macro, which is sort of like -`println!`, but it takes an extra argument: the first thing we pass to it is +`println!`, but it takes an extra argument. The first thing we pass to it is what to write to. We can aquire a handle to standard error through the -`std::io::stderr` function, and we give a mutable reference to it to -`wrintln!`; we need it to be mutable so we can write to it! The second and +`std::io::stderr` function. We give a mutable reference to `stderr` to +`writeln!`; we need it to be mutable so we can write to it! The second and third arguments to `writeln!` are like the first and second arguments to -`println!`: a format string, and then any variables we're interpolating. +`println!`: a format string and any variables we're interpolating. -Let's try running it again with `>`: +Let's try running the program again in the same way, without any arguments and +redirecting `stdout` with `>`: ```text $ cargo run > output.txt Application error: No search string or filename found ``` -Now we see our error on the screen, but `output.txt` contains nothing. -If we try it again with good arguments: +Now we see our error on the screen, but `output.txt` contains nothing. If we +try it again with arguments that work: ```text $ cargo run to poem.txt > output.txt @@ -1420,7 +1560,23 @@ $ cargo run to poem.txt > output.txt We'll see no output to our terminal, but `output.txt` will contain our results: +Filename: output.txt + ```text Are you nobody, too? How dreary to be somebody! ``` + +## Summary + +In this chapter, we've covered how to do common I/O operations in a Rust +context. By using command line arguments, files, environment variables, and the +ability to write to `stderr`, you're now prepared to write command line +applications. By using the concepts from previous chapters, your code will be +well-organized, be able to store data effectively in the appropriate data +structures, handle errors nicely, and be well tested. We also saw a real-world +scenario where lifetime annotations are needed to ensure references are +always valid. + +Next, let's explore how to make use of some features of Rust that were +influenced by functional languages: closures and iterators. From 01af63778c85c69fe9657667c1489fbc9fdf6568 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 28 Dec 2016 18:27:45 -0500 Subject: [PATCH 16/25] Split into sections and add more headings --- src/SUMMARY.md | 6 + src/ch12-00-an-io-project.md | 1532 ----------------- ...h12-01-accepting-command-line-arguments.md | 131 ++ src/ch12-02-reading-a-file.md | 109 ++ ...improving-error-handling-and-modularity.md | 662 +++++++ ...2-04-testing-the-librarys-functionality.md | 285 +++ ...2-05-working-with-environment-variables.md | 248 +++ ...-06-writing-to-stderr-instead-of-stdout.md | 118 ++ 8 files changed, 1559 insertions(+), 1532 deletions(-) create mode 100644 src/ch12-01-accepting-command-line-arguments.md create mode 100644 src/ch12-02-reading-a-file.md create mode 100644 src/ch12-03-improving-error-handling-and-modularity.md create mode 100644 src/ch12-04-testing-the-librarys-functionality.md create mode 100644 src/ch12-05-working-with-environment-variables.md create mode 100644 src/ch12-06-writing-to-stderr-instead-of-stdout.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 39a88a2c8..3f052abf9 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -56,6 +56,12 @@ - [Test Organization](ch11-03-test-organization.md) - [An I/O Project](ch12-00-an-io-project.md) + - [Accepting Command Line Arguments](ch12-01-accepting-command-line-arguments.md) + - [Reading a File](ch12-02-reading-a-file.md) + - [Improving Error Handling and Modularity](ch12-03-improving-error-handling-and-modularity.md) + - [Testing the Library's Functionality](ch12-04-testing-the-librarys-functionality.md) + - [Working with Environment Variables](ch12-05-working-with-environment-variables.md) + - [Writing to `stderr` instead of `stdout`](ch12-06-writing-to-stderr-instead-of-stdout.md) ## Thinking in Rust diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index 5da78a2f5..ebd73ccda 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -48,1535 +48,3 @@ $ cd greprs We're calling our version of `grep` 'greprs', so that we don't confuse any of our users into thinking that it's the more fully-featured version of `grep` they may already have installed on their system. - -## Accepting Command Line Arguments - -Our first task is to have `greprs` accept its two command line arguments. There -are some existing libraries on crates.io that can help us do this, but since -we're learning, we'll implement this ourselves. - -We'll need to call a function provided in Rust's standard library: -`std::env::args`. This function returns an *iterator* of the command line -arguments that were given to our program. We haven't discussed iterators yet; -Chapter 16 will cover them fully. For our purposes, though, we don't need to -understand much about how they work in order to use them. We only need to -understand two things: - -1. Iterators produce a series of values by repeatedly calling a `next` - function. -2. We can call the `collect` function on an iterator to turn it into a vector - containing all of the elements the iterator produces. - -Let's give it a try as shown in Listing 12-1: - -
-Filename: src/main.rs - -```rust -use std::env; - -fn main() { - let args: Vec = env::args().collect(); - println!("{:?}", args); -} -``` - -
- -Listing 12-1: Collect the command line arguments into a vector and print them out - -
-
- - - -First, we have a `use` statement to bring the `std::env` module into scope. -When using a function that's nested in more than one level of module, like -`std::env::args` is, it's conventional to use `use` to bring the parent module -into scope, rather than the function itself. `env::args` is less ambiguous than -a lone `args`. Also, if we end up using more than one function in `std::env`, -we only need a single `use`. - -On the first line of `main`, we call `env::args`, and immediately use `collect` -to create a vector out of it. We're also explicitly annotating the type of -`args` here: `collect` can be used to create many kinds of collections. Rust -won't be able to infer what kind of type we want, so the annotation is -required. We very rarely need to annotate types in Rust, but `collect` is one -function where you often need to. - -Finally, we print out the vector with the debug formatter, `:?`. Let's try -running our code with no arguments, and then with two arguments: - -```text -$ cargo run -["target/debug/greprs"] - -$ cargo run needle haystack -...snip... -["target/debug/greprs", "needle", "haystack"] -``` - -You'll notice one interesting thing: the name of the binary is the first -argument. The reasons for this are out of the scope of this chapter, but it's -something we'll have to remember to account for. - -Now that we have a way to access all of the arguments, let's find the ones we -care about and save them in variables as shown in Listing 12-2: - -
-Filename: src/main.rs - -```rust -use std::env; - -fn main() { - let args: Vec = env::args().collect(); - - let search = &args[1]; - let filename = &args[2]; - - println!("Searching for {}", search); - println!("In file {}", filename); -} -``` - -
- -Listing 12-2: Create variables to hold the search argument and filename argument - -
-
- - - -Remember, the program's name is the first argument, so we don't need `args[0]`. -We've decided that the first argument will be the string we're searching for, -so we put a reference to the first argument in the variable `search`. The -second argument will be the filename, so we put a reference to the second -argument in the variable `filename`. Let's try running this program again: - -```text -$ cargo run test sample.txt - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target\debug\greprs.exe test sample.txt` -Searching for test -In file sample.txt -``` - -Great! There's one problem, though. Let's try giving it no arguments: - -```text -$ cargo run - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target\debug\greprs.exe` -thread 'main' panicked at 'index out of bounds: the len is 1 -but the index is 1', ../src/libcollections\vec.rs:1307 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -Because our vector only has one element, the program's name, but we tried to -access the second element, our program panics with a message about the -out-of-bound access. While this error message is _accurate_, it's not -meaningful to users of our program at all. We could fix this problem right now, -but let's push forward: we'll improve this situation before we're finished. - -## Reading a File - -Now that we have some variables containing the information that we need, let's -try using them. The next step is to open the file that we want to search. To do -that, we need a file. Create one called `poem.txt` at the root level of your -project, and fill it up with some Emily Dickinson: - -Filename: poem.txt - -```text -I'm nobody! Who are you? -Are you nobody, too? -Then there's a pair of us — don't tell! -They'd banish us, you know. - -How dreary to be somebody! -How public, like a frog -To tell your name the livelong day -To an admiring bog! -``` - - - -With that in place, let's edit *src/main.rs* and add code to open the file as -shown in Listing 12-3: - -
-Filename: src/main.rs - -```rust -use std::env; -use std::fs::File; -use std::io::prelude::*; - -fn main() { - let args: Vec = env::args().collect(); - - let search = &args[1]; - let filename = &args[2]; - - println!("Searching for {}", search); - println!("In file {}", filename); - - let mut f = File::open(filename).expect("file not found"); - - let mut contents = String::new(); - f.read_to_string(&mut contents).expect("something went wrong reading the file"); - - println!("With text:\n{}", contents); -} -``` - -
- -Listing 12-3: Read the contents of the file specified by the second argument - -
-
- - - -We've added a few things. First of all, we need some more `use` statements to -bring in the relevant parts of the standard library: we need `std::fs::File` -for dealing with files, and `std::io::prelude::*` contains various traits that -are useful when doing I/O, including file I/O. In the same way that Rust has a -general prelude that brings certain things into scope automatically, the -`std::io` module has its own prelude of common things you'll need when working -with I/O. Unlike the default prelude, we must explicitly `use` the prelude in -`std::io`. - -In `main`, we've added three things: first, we get a handle to the file and -open it by using the `File::open` function and passing it the name of the file -specified in the second argument. Second, we create a mutable, empty `String` -in the variable `contents`, then call `read_to_string` on our file handle with -our `contents` string as the argument; `contents` is where `read_to_string` -will place the data it reads. Finally, we print out the entire file contents, -which is a way for us to be sure our program is working so far. - -Let's try running this code, specifying any string for the first argument (since -we haven't implemented the searching part yet) and our *poem.txt* file as the -second argument: - -```text -$ cargo run the poem.txt - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target\debug\greprs.exe the poem.txt` -Searching for the -In file poem.txt -With text: -I'm nobody! Who are you? -Are you nobody, too? -Then there's a pair of us — don't tell! -They'd banish us, you know. - -How dreary to be somebody! -How public, like a frog -To tell your name the livelong day -To an admiring bog! -``` - -Great! Our code is working. However, it's got a few flaws. Because our program -is still small, these flaws aren't a huge deal, but as our program grows, it -will be harder and harder to fix them in a clean way. Let's do the refactoring -now, instead of waiting. The refactoring will be much easier to do with only -this small amount of code. - -So what are these problems? There are four. The first problem is where we open -the file: we've used `expect` to print out an error message if opening the file -fails, but the error message only says "file not found". There are a number of -ways that opening a file can fail, but we're always assuming that it's due to -the file being missing. For example, the file could exist, but we might not have -permission to open it: right now, we print an error message that says the wrong -thing! - -Secondly, our use of `expect` over and over is similar to the earlier issue we -noted with the `panic!` on indexing if we don't pass any command line -arguments: while it _works_, it's a bit unprincipled, and we're doing it all -throughout our program. It would be nice to put our error handling in one spot. - -The third problem is that our `main` function now does two things: it parses -arguments, and it opens up files. For such a small function, this isn't a huge -problem. However, as we keep growing our program inside of `main`, the number of -separate tasks in the `main` function will get larger and larger. As one -function gains many responsibilities, it gets harder to reason about, harder to -test, and harder to change without breaking one of its parts. - -This also ties into our fourth problem: while `search` and `filename` are -configuration variables to our program, variables like `f` and `contents` are -used to perform our program's logic. The longer `main` gets, the more variables -we're going to bring into scope, and the more variables we have in scope, the -harder it is to keep track of which ones we need for which purpose. - -These organizational problems are common to many similar kinds of projects, so -the Rust community has developed a pattern for organizing the separate -concerns. This pattern is useful for organizing any binary project you'll build -in Rust, so we can justify doing this refactoring a bit earlier, since we know -that our project fits the pattern. The pattern looks like this: - -1. Split your program into both a *main.rs* and a *lib.rs*. -2. Place your command line parsing logic into *main.rs*. -3. Place your program's logic into *lib.rs*. -4. The job of the `main` function is: - * parse arguments - * set up any other configuration - * call a `run` function in *lib.rs* - * if `run` returns an error, handle that error - -Whew! The pattern sounds more complicated than it is, honestly. It's all about -separating concerns: *main.rs* handles actually running the program, and -*lib.rs* handles all of the actual logic of the task at hand. Let's re-work our -program into this pattern. First, let's extract a function whose purpose is -only to parse arguments. Listing 12-4 shows the new start of `main` that calls -a new function `parse_config`, which we're still going to define in -*src/main.rs*: - -
-Filename: src/main.rs - -```rust,ignore -fn main() { - let args: Vec = env::args().collect(); - - let (search, filename) = parse_config(&args); - - // ...snip... -} - -fn parse_config(args: &[String]) -> (&str, &str) { - let search = &args[1]; - let filename = &args[2]; - - (search, filename) -} -``` - -
- -Listing 12-4: Extract a `parse_config` function from `main` - -
-
- - - -This may seem like overkill, but we're working in small steps. After making -this change, run the program again to verify that the argument parsing still -works. It's good to check your progress often, so that you have a better idea -of which change caused a problem, should you encounter one. - - - - -Now that we have a function, let's improve it. Our code still has an indication -that there's a better design possible: we return a tuple, but then immediately -break that tuple up into individual parts again. This code isn't bad on its -own, but there's one other sign we have room for improvement: we called our -function `parse_config`. The `config` part of the name is saying the two values -we return should really be bound together, since they're both part of one -configuration value. - -> Note: some people call this antipattern of using primitive values when a -> complex type would be more appropriate *primitive obsession*. - -Let's introduce a struct to hold all of our configuration. Listing 12-5 shows -the addition of the `Config` struct definition, the refacting of `parse_config`, -and updates to `main`: - -
-Filename: src/main.rs - -```rust -# use std::env; -# -fn main() { - let args: Vec = env::args().collect(); - - let config = parse_config(&args); - - println!("Searching for {}", config.search); - println!("In file {}", config.filename); - - // ...snip... -} - -struct Config { - search: String, - filename: String, -} - -fn parse_config(args: &[String]) -> Config { - let search = args[1].clone(); - let filename = args[2].clone(); - - Config { - search: search, - filename: filename, - } -} -``` - -
- -Listing 12-5: Refactoring `parse_config` to return an instance of a `Config` -struct - -
-
- - - -The signature of `parse_config` now indicates that it returns a `Config` value. -In the body of `parse_config`, we used to be returning string slices that were -references to `String` values in `args`, but we've defined `Config` to contain -owend `String` values. Because the argument to `parse_config` is a slice of -`String` values, the `Config` instance can't take ownership of the `String` -values: that violates Rust's borrowing rules, since the `args` variable in -`main` owns the `String` values and is only letting the `parse_config` function -borrow them. - -There are a number of different ways we could manage the `String` data; for -now, we'll take the easy but less efficient route, and call the `clone` method -on the string slices. The call to `clone` will make a full copy of the string's -data for the `Config` instance to own, which does take more time and memory -than storing a reference to the string data, but cloning the data makes our -code very straightforward. - -There's a tendency amongst many Rustaceans to prefer not to use `clone` to fix -ownership problems, due to its runtime cost. In Chapter XX on iterators, we'll -learn how to make this situation more efficient. For now, it's okay to copy a -few strings to keep making progress. We're only going to be making these copies -once, and our filename and search string are both very small. It's better to -have a working program that's a bit inefficient than try to hyper-optimize code -on your first pass. As you get more experienced with Rust, it'll be easier to -skip this step, but for now, it's perfectly acceptable to call `clone`. - -We've updated `main` to put the instance of `Config` that `parse_config` -returns in a variable named `config`, and we've updated the code that was using -the separate `search` and `filename` variables to use the fields on the -`Config` struct instead. - -This is getting pretty good! Give your program another run to make sure it's -still working. We have two more refactorings to do here, though! Let's think -about the purpose of `parse_config`: it's a function that creates a `Config` -instance. We've already seen a convention for functions that create instances: -a `new` function, like `String::new`. Listing 12-6 shows the result of -transforming `parse_config` into a `new` function associated with our `Config` -struct: - -
-Filename: src/main.rs - -```rust - -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args); - - // ...snip... -} - -# struct Config { -# search: String, -# filename: String, -# } -# -// ...snip... - -impl Config { - fn new(args: &[String]) -> Config { - let search = args[1].clone(); - let filename = args[2].clone(); - - Config { - search: search, - filename: filename, - } - } -} -``` - -
- -Listing 12-6: Changing `parse_config` into `Config::new` - -
-
- - - -We've changed the name of `parse_config` to `new` and moved it within an `impl` -block. We've also updated the callsite in `main`. Try compiling this again to -make sure it works. - -Here's our last refactoring of this method: remember how accessing the vector -with indices 1 and 2 panics when it contains fewer than 3 items and gives a bad -error message? Let's fix that! Listing 12-7 shows how we can check that our -slice is long enough before accessing those locations, and panic with a better -error message: - -
-Filename: src/main.rs - -```rust,ignore -// ...snip... -fn new(args: &[String]) -> Config { - if args.len() < 3 { - panic!("not enough arguments"); - } - // ...snip... -``` - -
- -Listing 12-7: Adding a check for the number of arguments - -
-
- - - -With these extra few lines of code in `new`, let's try running our program -without any arguments: - -```bash -$ cargo run - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target\debug\greprs.exe` -thread 'main' panicked at 'not enough arguments', src\main.rs:29 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -This is a bit better! We at least have a reasonable error message here. -However, we also have a bunch of extra information that we don't want to give -to our users. We can do better by changing the type signature of `new`. Right -now, it returns only a `Config`, so there's no way to indicate that an error -happened while creating our `Config`. Instead, we can return a `Result`, as -shown in Listing 12-8: - -
-Filename: src/main.rs - -```rust,ignore -# struct Config { -# search: String, -# filename: String, -# } -# -impl Config { - fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } - - let search = args[1].clone(); - let filename = args[2].clone(); - - Ok(Config { - search: search, - filename: filename, - }) - } -} -``` - -
- -Listing 12-8: Return a `Result` from `Config::new` - -
-
- - - -Our `new` function now returns a `Result`, with a `Config` instance in the -success case and a `&'static str` when an error happens. Recall from "The -Static Lifetime" section in Chapter 10 `&'static str` is the type of string -literals, which is what our error message is for now. - -We've made two changes in the body of the `new` function: instead of calling -`panic!` if there aren't enough arguments, we now return an `Err` value. We -wrapped the `Config` return value in an `Ok`. These changes make the function -conform to its new type signature. - -Now we need to make some changes to `main` as shown in Listing 12-9: - -
-Filename: src/main.rs - -```rust,ignore -use std::process; - -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - println!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - // ...snip... -``` - -
- -Listing 12-9: Exiting with an error code if creating a new `Config` fails - -
-
- - - -We've added a new `use` line to import `process` from the standard library. -In the `main` function itself, we'll handle the `Result` value returned -from the `new` function and exit the process in a cleaner way if `Config::new` -returns an `Err` value. - -We're using a method we haven't covered before that's defined on `Result` -by the standard library: `unwrap_or_else`. This method has similar behavior as -`unwrap` if the `Result` is an `Ok` value: it returns the inner value `Ok` is -wrapping. Unlike `unwrap`, if the value is an `Err` value, this method calls a -*closure* which is an anonymous function that we define and pass as an argument -to `unwrap_or_else`. We'll be covering closures in more detail in Chapter XX; -the important part to understand in this case is that `unwrap_or_else` will -pass the inner value of the `Err` to our closure in the argument `err` that -appears between the vertical pipes. Using `unwrap_or_else` lets us do some -custom, non-`panic!` error handling. - -Said error handling is only two lines: we print out the error, then call -`std::process::exit`. That function will stop our program's execution -immediately and return the number passed to it as a return code. By convention, -a zero means success and any other value means failure. In the end, this has -similar characteristics to our `panic!`-based handling we had in Listing 12-7, -but we no longer get all the extra output. Let's try it: - -```bash -$ cargo run - Compiling greprs v0.1.0 (file:///project/greprs) - Finished debug [unoptimized + debuginfo] target(s) in 0.48 secs - Running `target\debug\greprs.exe` -Problem parsing arguments: not enough arguments -``` - -Great! This output is much friendlier for our users. Now that we're done -refactoring our configuration parsing, let's improve our program's logic. -Listing 12-10 shows the code after extracting a function named `run` that we'll -call from `main`. The `run` function contains the code that was in `main`: - -
-Filename: src/main.rs - -```rust,ignore -fn main() { - // ...snip... - - println!("Searching for {}", config.search); - println!("In file {}", config.filename); - - run(config); -} - -fn run(config: Config) { - let mut f = File::open(config.filename).expect("file not found"); - - let mut contents = String::new(); - f.read_to_string(&mut contents).expect("something went wrong reading the file"); - - println!("With text:\n{}", contents); -} - -// ...snip... -``` - -
- -Listing 12-10: Extracting a `run` functionality for the rest of the program logic - -
-
- - - -The contents of `run` are the previous lines that were in `main`, and the `run` -function takes a `Config` as an argument. Now that we have a separate function, -we can make a similar improvement to the one we made to `Config::new` in -Listing 12-8: let's return a `Result` instead of calling `panic!` via -`expect`. Listing 12-11 shows the addition of a `use` statement to bring -`std::error::Error` struct into scope and the changes to the `run` function -to return a `Result`: - -
-Filename: src/main.rs - -```rust,ignore -use std::error::Error; - -// ...snip... - -fn run(config: Config) -> Result<(), Box> { - let mut f = File::open(config.filename)?; - - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - - println!("With text:\n{}", contents); - - Ok(()) -} -``` - -
- -Listing 12-11: Changing the `run` function to return `Result` - -
-
- - - -We've made three big changes here. The first is the return type of the `run` -function is now `Result<(), Box>`. Previously, our function returned the -unit type, `()`, so that's still the value returned in the `Ok` case. For our -error type, we're going to use `Box`. This is called a *trait object*, -which we'll be covering in Chapter XX. For now, think of it like this: -`Box` means the function will return some kind of type that implements -the `Error` trait, but we're not specifying what particular type the return -value will be. This gives us flexibility to return error values that may be of -different types in different error cases. `Box` is a smart pointer to heap -data, and we'll be going into detail about `Box` in Chapter YY. - -The second change is that we've removed our calls to `expect` in favor of `?`, -like we talked about in Chapter 9. Rather than `panic!` on an error, this will -return the error value from the function we're in for the caller to handle. - -The third change is that we're now returning an `Ok` value from this function -in the success case. Because we've declared the `run` function's success type -as `()` in the signature, we need to wrap the unit type value in the `Ok` -value. `Ok(())` looks a bit strange at first, but using `()` in this way is the -idiomatic way to indicate that we're calling `run` for its side effects only; -it doesn't return anything interesting. - -This will compile, but with a warning: - -```text -warning: unused result which must be used, #[warn(unused_must_use)] on by default - --> src\main.rs:39:5 - | -39 | run(config); - | ^^^^^^^^^^^^ -``` - -Rust is trying to tell us that we're ignoring our `Result`, which might be an -error value. Let's handle that now. We'll use a similar technique as the way we -handled failure with `Config::new` in Listing 12-9, but with a slight -difference: - -Filename: src/main.rs - -```rust,ignore -fn main() { - // ...snip... - - println!("Searching for {}", config.search); - println!("In file {}", config.filename); - - if let Err(e) = run(config) { - println!("Application error: {}", e); - - process::exit(1); - } -} -``` - - - -Instead of `unwrap_or_else`, we use `if let` to see if `run` returns an `Err` -value and call `process::exit(1)` if so. Why? The distinction between this case -and the `Config::new` case is a bit subtle. With `Config::new`, we cared about -two things: - -1. Detecting any errors that happen -2. Getting a `Config` if no errors happened - -In this case, because `run` returns a `()` in the success case, the only thing -we care about is the first case: detecting an error. If we used -`unwrap_or_else`, we'd get its return value, which would be `()`. That's not -very useful. - -The bodies of the `if let` and of the `unwrap_or_else` are the same in both -cases though: we print out an error and exit. - -This is looking pretty good! There's one more thing we haven't done yet: split -the *src/main.rs* up and put some code into *src/lib.rs* Let's do that now: -move the `run` function from *src/main.rs* to a new file, *src/lib.rs*. You'll -also need to move the relevant `use` statements and the definition of `Config` -and its `new` method as well. Your *src/lib.rs* should now look like Listing -12-12: - -
-Filename: src/lib.rs - -```rust,ignore -use std::error::Error; -use std::fs::File; -use std::io::prelude::*; - -pub struct Config { - pub search: String, - pub filename: String, -} - -impl Config { - pub fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } - - let search = args[1].clone(); - let filename = args[2].clone(); - - Ok(Config { - search: search, - filename: filename, - }) - } -} - -pub fn run(config: Config) -> Result<(), Box>{ - let mut f = File::open(config.filename)?; - - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - - println!("With text:\n{}", contents); - - Ok(()) -} -``` - -
- -Listing 12-12: Moving `Config` and `run` into *src/lib.rs* - -
-
- - - -Notice we also made liberal use of `pub`: on `Config`, its fields and its `new` -method, and on the `run` function. - -Now in *src/main.rs*, we need to bring in the code that's now in *src/lib.rs* -through `extern crate greprs`. Then we need to add a `use greprs::Config` line -to bring `Corfig` into scope, and prefix the `run` function with our crate name -as shown in Listing 12-13: - -
-Filename: src/main.rs - -```rust,ignore -extern crate greprs; - -use std::env; -use std::process; - -use greprs::Config; - -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - println!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - println!("Searching for {}", config.search); - println!("In file {}", config.filename); - - if let Err(e) = greprs::run(config) { - println!("Application error: {}", e); - - process::exit(1); - } -} -``` - -
- -Listing 12-13: Bringing the `greprs` crate into the scope of *src/main.rs* - -
-
- - - -With that, everything should work again. Give it a few `cargo run`s and make -sure you haven't broken anything. Whew! That all was a lot of work, but we've -set ourselves up for success in the future. We've set up a way to handle errors -in a much nicer fashion, and we've made our code slightly more modular. Almost -all of our work will be done in *src/lib.rs* from here on out. - -Let's take advantage of this newfound modularity by doing something that would -have been hard with our old code, but is easy with our new code: write some -tests! - -## Testing the Library's Functionality - -Writing tests for the core functionality of our code is now easier since we -extracted the logic into *src/lib.rs* and left all the argument parsing and -error handling in *src/main.rs*. We can now call our code directly with various -arguments and check return values without having to call our binary from the -command line. - -We're going to write a function named `grep` that takes our search term and the -text to search and procudes a list of search results. Let's remove that -`println!` from `run` (and from *src/main.rs* as well, as we don't really need -those anymore either), and call the new `grep` function with the options we've -collected. We'll add a placeholder implementation of the function for now, and -a test that specifies the behavior we'd like the `grep` function to have. The -test will fail with our placeholder implementation, of course, but we can make -sure the code compiles and that we get the failure message we expect. Listing -12-14 shows these modifications: - -
-Filename: src/lib.rs - -```rust -# use std::error::Error; -# use std::fs::File; -# use std::io::prelude::*; -# pub struct Config { -# pub search: String, -# pub filename: String, -# } -# -fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - vec![] -} - -pub fn run(config: Config) -> Result<(), Box>{ - let mut f = File::open(config.filename)?; - - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - - grep(&config.search, &contents); - - Ok(()) -} - -#[cfg(test)] -mod test { - use grep; - - #[test] - fn one_result() { - let search = "duct"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three."; - - assert_eq!( - vec!["safe, fast, productive."], - grep(search, contents) - ); - } -} -``` - -
- -Listing 12-14: Creating a function where our logic will go and a failing test -for that function - -
-
- - - -Notice that we need an explicit lifetime `'a` declared in the signature of -`grep` and used with the `contents` argument and the return value. Remember, -lifetime parameters are used to specify which arguments' lifetimes connect to -the lifetime of the return value. In this case, we're indicating that the -vector we're returning is going to contain string slices that reference slices -of the argument `contents`, as opposed to referencing slices of the argument -`search`. Another way to think about what we're telling Rust is that the data -returned by the `grep` function will live as long as the data passed into this -function in the `contents` argument. This is important! Given that the data a -slice references needs to be valid in order for the reference to be valid, if -the compiler thought that we were making string slices of `search` rather than -`contents`, it would do its safety checking incorrectly. If we tried to compile -this function without lifetimes, we would get this error: - -```text -error[E0106]: missing lifetime specifier - --> src\lib.rs:37:46 - | -37 | fn grep(search: &str, contents: &str) -> Vec<&str> { - | ^ expected lifetime parameter - | - = help: this function's return type contains a borrowed value, but the - signature does not say whether it is borrowed from `search` or - `contents` -``` - -Rust can't possibly know which of the two arguments we need, so it needs us to -tell it. Because `contents` is the argument that contains all of our text and -we want to return the parts of that text that match, we know `contents` is the -argument that should be connected to the return value using the lifetime syntax. - -Connecting arguments to return values in the signature is something that other -programming langugages don't make you do, so don't worry if this still feels -strange! Knowing how to specify lifetimes gets easier over time, and practice -makes perfect. You may want to re-read the above section or go back and compare -this example with the Lifetime Syntax section in Chapter 10. - -Now let's try running our test: - -```text -$ cargo test -...warnings... - Finished debug [unoptimized + debuginfo] target(s) in 0.43 secs - Running target/debug/deps/greprs-917c5edfc3cf199a - -running 1 test -test test::one_result ... FAILED - -failures: - ----- test::one_result stdout ---- - thread 'test::one_result' panicked at 'assertion failed: `(left == right)` -(left: `["safe, fast, productive."]`, right: `[]`)', src/lib.rs:16 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - - -failures: - test::one_result - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured - -error: test failed -``` - -Great, our test fails, exactly as we expected. Let's get the test to pass! It's -failing because we always return an empty vector. Here's what we're going to do -to implement `grep`: - -1. Iterate through each line of the contents. -2. Check if the line contains our search string. - * If it does, add it to the list of values we're returning. - * If not, do nothing. -3. Return the list of results that match. - -Let's take each step at a time, starting with iterating through lines. Strings -have a helpful method to handle this, conveniently named `lines`: - -Filename: src/lib.rs - -```rust,ignore -fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - for line in contents.lines() { - // do something with line - } -} -``` - - - -We're using a `for` loop along with the `lines` method to get each line in turn. -Next, let's see if our line contains the search string. Luckily, strings have a -helpful method named `contains` that does this for us! Using the `contains` -method looks like this: - -Filename: src/lib.rs - -```rust,ignore -fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - for line in contents.lines() { - if line.contains(search) { - // do something with line - } - } -} -``` - - - -Finally, we need a way to store the lines that contain our search string. For -that, we can make a mutable vector before the `for` loop and call the `push` -method to store a `line` in the vector. After the `for` loop, we return the -vector: - -Filename: src/lib.rs - -```rust,ignore -fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = Vec::new(); - - for line in contents.lines() { - if line.contains(search) { - results.push(line); - } - } - - results -} -``` - - - -Let's give it a try: - -```text -$ cargo test -running 1 test -test test::one_result ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/debug/greprs-2f55ee8cd1721808 - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests greprs - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Great! It works. Now that our test is passing, we could consider opportunities -for refactoring the implementation of `grep` and be certain we maintain the -same functionality while we do so. This code isn't bad, but it isn't taking -advantage of some useful features of iterators. We'll be coming back to this -example in Chapter 13 where we'll explore iterators in detail and see how to -improve it. - -Now that the `grep` function is working, we need to do one last thing inside of -the `run` function: we never printed out the results! We'll do that by adding -a `for` loop that prints each line returned from the `grep` function: - -Filename: src/lib.rs - -```rust,ignore -pub fn run(config: Config) -> Result<(), Box>{ - let mut f = File::open(config.filename)?; - - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - - for line in grep(&config.search, &contents) { - println!("{}", line); - } - - Ok(()) -} -``` - - - -Now our whole program should be working! Let's try it out: - -```text -$ cargo run the poem.txt - Compiling greprs v0.1.0 (file:///C:/Users/steve/tmp/greprs) - Finished debug [unoptimized + debuginfo] target(s) in 0.38 secs - Running `target\debug\greprs.exe the poem.txt` -Then there's a pair of us - don't tell! -To tell your name the livelong day - -$ cargo run a poem.txt - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target\debug\greprs.exe a poem.txt` -I'm nobody! Who are you? -Then there's a pair of us - don't tell! -They'd banish us, you know. -How dreary to be somebody! -How public, like a frog -To tell your name the livelong day -To an admiring bog! -``` - -Excellent! We've built our own version of a classic tool, and learned a lot -about how to structure applications. We've also learned a bit about file input -and output, lifetimes, testing, and command line parsing. - -## Working with Environment Variables - -Let's add one more feature: case insensitive searching. In addtion, this -setting won't be a command line option: it'll be an environment variable -instead. We could choose to make case insensitivity a command line option, but -our users have requested an environment variable that they could set once and -make all their searches case insensitive in that terminal session. - -### Implement and Test a Case-Insensitive `grep` Function - -First, let's add a new function that we will call when the environment variable -is on. Let's start by adding a new test and re-naming our existing one: - -```rust,ignore -#[cfg(test)] -mod test { - use {grep, grep_case_insensitive}; - - #[test] - fn case_sensitive() { - let search = "duct"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three. -Duct tape."; - - assert_eq!( - vec!["safe, fast, productive."], - grep(search, contents) - ); - } - - #[test] - fn case_insensitive() { - let search = "rust"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three. -Trust me."; - - assert_eq!( - vec!["Rust:", "Trust me."], - grep_case_insensitive(search, contents) - ); - } -} -``` - - - -We're going to define a new function named `grep_case_insensitive`. Its -implementation will be almost the same as the `grep` function, but with some -minor changes: - -Filename: src/lib.rs - -```rust -fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { - let search = search.to_lowercase(); - let mut results = Vec::new(); - - for line in contents.lines() { - if line.to_lowercase().contains(&search) { - results.push(line); - } - } - - results -} -``` - - - -First, we lowercase the `search` string, and store it in a shadowed variable -with the same name. Note that `search` is now a `String` rather than a string -slice, so we need to add an ampersand when we pass `search` to `contains` since -`contains` takes a string slice. - -Second, we add a call to `to_lowercase` each `line` before we check if it -contains `search`. Since we've converted both `line` and `search` into all -lowercase, we'll find matches no matter what case they used in the file and the -command line arguments, respectively. Let's see if this passes the tests: - -```text - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running target\debug\deps\greprs-e58e9b12d35dc861.exe - -running 2 tests -test test::case_insensitive ... ok -test test::case_sensitive ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured - - Running target\debug\greprs-8a7faa2662b5030a.exe - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests greprs - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Great! Now, we have to actually use the new `grep_case_insensitive` function. -First, let's add a configuration option for it to the `Config` struct: - -Filename: src/lib.rs - -```rust -pub struct Config { - pub search: String, - pub filename: String, - pub case_sensitive: bool, -} -``` - - - -And then check for that option inside of the `run` function, and decide which -function to call based on the value of the `case_sensitive` function: - -Filename: src/lib.rs - -```rust,ignore -pub fn run(config: Config) -> Result<(), Box>{ - let mut f = File::open(config.filename)?; - - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - - let results = if config.case_sensitive { - grep(&config.search, &contents) - } else { - grep_case_insensitive(&config.search, &contents) - }; - - for line in results { - println!("{}", line); - } - - Ok(()) -} -``` - - - -Finally, we need to actually check the environment for the variable. To bring -the `env` module from the standard library into our project, we add a `use` line -at the top of *src/lib.rs*: - -Filename: src/lib.rs - -```rust -use std::env; -``` - -And then use the `vars` method from the `env` module inside of `Config::new`: - -Filename: src/lib.rs - -```rust -# use std::env; -# -# struct Config { -# search: String, -# filename: String, -# case_sensitive: bool, -# } -# -impl Config { - pub fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } - - let search = args[1].clone(); - let filename = args[2].clone(); - - let mut case_sensitive = true; - - for (name, _) in env::vars() { - if name == "CASE_INSENSITIVE" { - case_sensitive = false; - } - } - - Ok(Config { - search: search, - filename: filename, - case_sensitive: case_sensitive, - }) - } -} -``` - - - -Here, we call `env::vars`, which works in a similar way as `env::args`. The -difference is `env::vars` returns an iterator of environment variables rather -than command line arguments. Instead of using `collect` to create a vector of -all of the environment variables, we're using a `for` loop. `env::vars` returns -tuples: the name of the environment variable and its value. We never care about -the values, only if the variable is set at all, so we use the `_` placeholder -instead of a name to let Rust know that it shouldn't warn us about an unused -variable. Finally, we have a `case_sensitive` variable, which is set to true by -default. If we ever find a `CASE_INSENSITIVE` environment variable, we set the -`case_sensitive` variable to false instead. Then we return the value as part of -the `Config`. - -Let's give it a try! - -```text -$ cargo run to poem.txt - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target\debug\greprs.exe to poem.txt` -Are you nobody, too? -How dreary to be somebody! -``` - -```text -$ CASE_INSENSITIVE=1 cargo run to poem.txt - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target\debug\greprs.exe to poem.txt` -Are you nobody, too? -How dreary to be somebody! -To tell your name the livelong day -To an admiring bog! -``` - -Excellent! Our `greprs` program can now do case insensitive searching controlled -by an environment variable. Now you know how to manage options set using -either command line arguments or environment variables! - -Some programs allow both arguments _and_ environment variables for the same -configuration. In those cases, the programs decide that one or the other of -arguments or environment variables take precedence. For another exercise on -your own, try controlling case insensitivity through a command line argument as -well, and decide which should take precedence if you run the program with -contradictory values. - -The `std::env` module contains many more useful features for dealing with -environment variables; check out its documentation to see what's available. - -## Write to `stderr` Instead of `stdout` - -Right now, we're writing all of our output to the terminal with `println!`. -This works, but most terminals provide two kinds of output: "standard out" is -used for most information, but "standard error" is used for error messages. This -makes it easier to do things like "Print error messages to my terminal, but -write other output to a file." - -We can see that our program is only capable of printing to `stdout` by -redirecting it to a file using `>` on the command line, and running our program -without any arguments, which causes an error: - -```text -$ cargo run > output.txt -``` - -The `>` syntax tells the shell to write the contents of standard out to -*output.txt* instead of the screen. However, if we open *output.txt* after -running we'll see our error message: - -```text -Application error: No search string or filename found -``` - -We'd like this to be printed to the screen instead, and only have the output -from a successful run end up in the file if we run our program this way. Let's -change how error messages are printed as shown in Listing 12-15: - -
-Filename: src/main.rs - -```rust,ignore -extern crate greprs; - -use std::env; -use std::process; - -use greprs::Config; - -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - println!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - if let Err(e) = greprs::run(config) { - let mut stderr = std::io::stderr(); - - writeln!( - &mut stderr, - "Application error: {}", - e - ).expect("Could not write to stderr"); - - process::exit(1); - } -} -``` - -
- -Listing 12-15: Writing error messages to `stderr` instead of `stdout` - -
-
- - - -Rust does not have a convenient function like `println!` for writing to -standard error. Instead, we use the `writeln!` macro, which is sort of like -`println!`, but it takes an extra argument. The first thing we pass to it is -what to write to. We can aquire a handle to standard error through the -`std::io::stderr` function. We give a mutable reference to `stderr` to -`writeln!`; we need it to be mutable so we can write to it! The second and -third arguments to `writeln!` are like the first and second arguments to -`println!`: a format string and any variables we're interpolating. - -Let's try running the program again in the same way, without any arguments and -redirecting `stdout` with `>`: - -```text -$ cargo run > output.txt -Application error: No search string or filename found -``` - -Now we see our error on the screen, but `output.txt` contains nothing. If we -try it again with arguments that work: - -```text -$ cargo run to poem.txt > output.txt -``` - -We'll see no output to our terminal, but `output.txt` will contain -our results: - -Filename: output.txt - -```text -Are you nobody, too? -How dreary to be somebody! -``` - -## Summary - -In this chapter, we've covered how to do common I/O operations in a Rust -context. By using command line arguments, files, environment variables, and the -ability to write to `stderr`, you're now prepared to write command line -applications. By using the concepts from previous chapters, your code will be -well-organized, be able to store data effectively in the appropriate data -structures, handle errors nicely, and be well tested. We also saw a real-world -scenario where lifetime annotations are needed to ensure references are -always valid. - -Next, let's explore how to make use of some features of Rust that were -influenced by functional languages: closures and iterators. diff --git a/src/ch12-01-accepting-command-line-arguments.md b/src/ch12-01-accepting-command-line-arguments.md new file mode 100644 index 000000000..6d6fac57f --- /dev/null +++ b/src/ch12-01-accepting-command-line-arguments.md @@ -0,0 +1,131 @@ + +## Accepting Command Line Arguments + +Our first task is to have `greprs` accept its two command line arguments. There +are some existing libraries on crates.io that can help us do this, but since +we're learning, we'll implement this ourselves. + +We'll need to call a function provided in Rust's standard library: +`std::env::args`. This function returns an *iterator* of the command line +arguments that were given to our program. We haven't discussed iterators yet; +Chapter 16 will cover them fully. For our purposes, though, we don't need to +understand much about how they work in order to use them. We only need to +understand two things: + +1. Iterators produce a series of values by repeatedly calling a `next` + function. +2. We can call the `collect` function on an iterator to turn it into a vector + containing all of the elements the iterator produces. + +Let's give it a try as shown in Listing 12-1: + +
+Filename: src/main.rs + +```rust +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + println!("{:?}", args); +} +``` + +
+ +Listing 12-1: Collect the command line arguments into a vector and print them out + +
+
+ + + +First, we have a `use` statement to bring the `std::env` module into scope. +When using a function that's nested in more than one level of module, like +`std::env::args` is, it's conventional to use `use` to bring the parent module +into scope, rather than the function itself. `env::args` is less ambiguous than +a lone `args`. Also, if we end up using more than one function in `std::env`, +we only need a single `use`. + +On the first line of `main`, we call `env::args`, and immediately use `collect` +to create a vector out of it. We're also explicitly annotating the type of +`args` here: `collect` can be used to create many kinds of collections. Rust +won't be able to infer what kind of type we want, so the annotation is +required. We very rarely need to annotate types in Rust, but `collect` is one +function where you often need to. + +Finally, we print out the vector with the debug formatter, `:?`. Let's try +running our code with no arguments, and then with two arguments: + +```text +$ cargo run +["target/debug/greprs"] + +$ cargo run needle haystack +...snip... +["target/debug/greprs", "needle", "haystack"] +``` + +You'll notice one interesting thing: the name of the binary is the first +argument. The reasons for this are out of the scope of this chapter, but it's +something we'll have to remember to account for. + +Now that we have a way to access all of the arguments, let's find the ones we +care about and save them in variables as shown in Listing 12-2: + +
+Filename: src/main.rs + +```rust +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + + let search = &args[1]; + let filename = &args[2]; + + println!("Searching for {}", search); + println!("In file {}", filename); +} +``` + +
+ +Listing 12-2: Create variables to hold the search argument and filename argument + +
+
+ + + +Remember, the program's name is the first argument, so we don't need `args[0]`. +We've decided that the first argument will be the string we're searching for, +so we put a reference to the first argument in the variable `search`. The +second argument will be the filename, so we put a reference to the second +argument in the variable `filename`. Let's try running this program again: + +```text +$ cargo run test sample.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe test sample.txt` +Searching for test +In file sample.txt +``` + +Great! There's one problem, though. Let's try giving it no arguments: + +```text +$ cargo run + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe` +thread 'main' panicked at 'index out of bounds: the len is 1 +but the index is 1', ../src/libcollections\vec.rs:1307 +note: Run with `RUST_BACKTRACE=1` for a backtrace. +``` + +Because our vector only has one element, the program's name, but we tried to +access the second element, our program panics with a message about the +out-of-bound access. While this error message is _accurate_, it's not +meaningful to users of our program at all. We could fix this problem right now, +but let's push forward: we'll improve this situation before we're finished. diff --git a/src/ch12-02-reading-a-file.md b/src/ch12-02-reading-a-file.md new file mode 100644 index 000000000..8e582957d --- /dev/null +++ b/src/ch12-02-reading-a-file.md @@ -0,0 +1,109 @@ + +## Reading a File + +Now that we have some variables containing the information that we need, let's +try using them. The next step is to open the file that we want to search. To do +that, we need a file. Create one called `poem.txt` at the root level of your +project, and fill it up with some Emily Dickinson: + +Filename: poem.txt + +```text +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us — don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! +``` + + + +With that in place, let's edit *src/main.rs* and add code to open the file as +shown in Listing 12-3: + +
+Filename: src/main.rs + +```rust +use std::env; +use std::fs::File; +use std::io::prelude::*; + +fn main() { + let args: Vec = env::args().collect(); + + let search = &args[1]; + let filename = &args[2]; + + println!("Searching for {}", search); + println!("In file {}", filename); + + let mut f = File::open(filename).expect("file not found"); + + let mut contents = String::new(); + f.read_to_string(&mut contents).expect("something went wrong reading the file"); + + println!("With text:\n{}", contents); +} +``` + +
+ +Listing 12-3: Read the contents of the file specified by the second argument + +
+
+ + + +We've added a few things. First of all, we need some more `use` statements to +bring in the relevant parts of the standard library: we need `std::fs::File` +for dealing with files, and `std::io::prelude::*` contains various traits that +are useful when doing I/O, including file I/O. In the same way that Rust has a +general prelude that brings certain things into scope automatically, the +`std::io` module has its own prelude of common things you'll need when working +with I/O. Unlike the default prelude, we must explicitly `use` the prelude in +`std::io`. + +In `main`, we've added three things: first, we get a handle to the file and +open it by using the `File::open` function and passing it the name of the file +specified in the second argument. Second, we create a mutable, empty `String` +in the variable `contents`, then call `read_to_string` on our file handle with +our `contents` string as the argument; `contents` is where `read_to_string` +will place the data it reads. Finally, we print out the entire file contents, +which is a way for us to be sure our program is working so far. + +Let's try running this code, specifying any string for the first argument (since +we haven't implemented the searching part yet) and our *poem.txt* file as the +second argument: + +```text +$ cargo run the poem.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe the poem.txt` +Searching for the +In file poem.txt +With text: +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us — don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! +``` + +Great! Our code is working. However, it's got a few flaws. Because our program +is still small, these flaws aren't a huge deal, but as our program grows, it +will be harder and harder to fix them in a clean way. Let's do the refactoring +now, instead of waiting. The refactoring will be much easier to do with only +this small amount of code. diff --git a/src/ch12-03-improving-error-handling-and-modularity.md b/src/ch12-03-improving-error-handling-and-modularity.md new file mode 100644 index 000000000..2a5193511 --- /dev/null +++ b/src/ch12-03-improving-error-handling-and-modularity.md @@ -0,0 +1,662 @@ +## Improving Error Handling and Modularity + +There are four problems that we'd like to fix to improve our program, and they +all have to do with potential errors and the way the program is structured. The +first problem is where we open the file: we've used `expect` to print out an +error message if opening the file fails, but the error message only says "file +not found". There are a number of ways that opening a file can fail, but we're +always assuming that it's due to the file being missing. For example, the file +could exist, but we might not have permission to open it: right now, we print +an error message that says the wrong thing! + +Secondly, our use of `expect` over and over is similar to the earlier issue we +noted with the `panic!` on indexing if we don't pass any command line +arguments: while it _works_, it's a bit unprincipled, and we're doing it all +throughout our program. It would be nice to put our error handling in one spot. + +The third problem is that our `main` function now does two things: it parses +arguments, and it opens up files. For such a small function, this isn't a huge +problem. However, as we keep growing our program inside of `main`, the number of +separate tasks in the `main` function will get larger and larger. As one +function gains many responsibilities, it gets harder to reason about, harder to +test, and harder to change without breaking one of its parts. + +This also ties into our fourth problem: while `search` and `filename` are +configuration variables to our program, variables like `f` and `contents` are +used to perform our program's logic. The longer `main` gets, the more variables +we're going to bring into scope, and the more variables we have in scope, the +harder it is to keep track of which ones we need for which purpose. It would be +better if we grouped the configuration variables into one structure to make +their purpose clear. + +Let's address these problems by restructuring our project. + +### Separation of Concerns for Binary Projects + +These kinds of organizational problems are common to many similar kinds of +projects, so the Rust community has developed a pattern for organizing the +separate concerns. This pattern is useful for organizing any binary project +you'll build in Rust, so we can justify doing this refactoring a bit earlier, +since we know that our project fits the pattern. The pattern looks like this: + +1. Split your program into both a *main.rs* and a *lib.rs*. +2. Place your command line parsing logic into *main.rs*. +3. Place your program's logic into *lib.rs*. +4. The job of the `main` function is: + * parse arguments + * set up any other configuration + * call a `run` function in *lib.rs* + * if `run` returns an error, handle that error + +Whew! The pattern sounds more complicated than it is, honestly. It's all about +separating concerns: *main.rs* handles actually running the program, and +*lib.rs* handles all of the actual logic of the task at hand. Let's re-work our +program into this pattern. First, let's extract a function whose purpose is +only to parse arguments. Listing 12-4 shows the new start of `main` that calls +a new function `parse_config`, which we're still going to define in +*src/main.rs*: + +
+Filename: src/main.rs + +```rust,ignore +fn main() { + let args: Vec = env::args().collect(); + + let (search, filename) = parse_config(&args); + + // ...snip... +} + +fn parse_config(args: &[String]) -> (&str, &str) { + let search = &args[1]; + let filename = &args[2]; + + (search, filename) +} +``` + +
+ +Listing 12-4: Extract a `parse_config` function from `main` + +
+
+ + + +This may seem like overkill, but we're working in small steps. After making +this change, run the program again to verify that the argument parsing still +works. It's good to check your progress often, so that you have a better idea +of which change caused a problem, should you encounter one. + + + + +### Grouping Configuration Values + +Now that we have a function, let's improve it. Our code still has an indication +that there's a better design possible: we return a tuple, but then immediately +break that tuple up into individual parts again. This code isn't bad on its +own, but there's one other sign we have room for improvement: we called our +function `parse_config`. The `config` part of the name is saying the two values +we return should really be bound together, since they're both part of one +configuration value. + +> Note: some people call this antipattern of using primitive values when a +> complex type would be more appropriate *primitive obsession*. + +Let's introduce a struct to hold all of our configuration. Listing 12-5 shows +the addition of the `Config` struct definition, the refacting of `parse_config`, +and updates to `main`: + +
+Filename: src/main.rs + +```rust +# use std::env; +# +fn main() { + let args: Vec = env::args().collect(); + + let config = parse_config(&args); + + println!("Searching for {}", config.search); + println!("In file {}", config.filename); + + // ...snip... +} + +struct Config { + search: String, + filename: String, +} + +fn parse_config(args: &[String]) -> Config { + let search = args[1].clone(); + let filename = args[2].clone(); + + Config { + search: search, + filename: filename, + } +} +``` + +
+ +Listing 12-5: Refactoring `parse_config` to return an instance of a `Config` +struct + +
+
+ + + +The signature of `parse_config` now indicates that it returns a `Config` value. +In the body of `parse_config`, we used to be returning string slices that were +references to `String` values in `args`, but we've defined `Config` to contain +owend `String` values. Because the argument to `parse_config` is a slice of +`String` values, the `Config` instance can't take ownership of the `String` +values: that violates Rust's borrowing rules, since the `args` variable in +`main` owns the `String` values and is only letting the `parse_config` function +borrow them. + +There are a number of different ways we could manage the `String` data; for +now, we'll take the easy but less efficient route, and call the `clone` method +on the string slices. The call to `clone` will make a full copy of the string's +data for the `Config` instance to own, which does take more time and memory +than storing a reference to the string data, but cloning the data makes our +code very straightforward. + +There's a tendency amongst many Rustaceans to prefer not to use `clone` to fix +ownership problems, due to its runtime cost. In Chapter XX on iterators, we'll +learn how to make this situation more efficient. For now, it's okay to copy a +few strings to keep making progress. We're only going to be making these copies +once, and our filename and search string are both very small. It's better to +have a working program that's a bit inefficient than try to hyper-optimize code +on your first pass. As you get more experienced with Rust, it'll be easier to +skip this step, but for now, it's perfectly acceptable to call `clone`. + +We've updated `main` to put the instance of `Config` that `parse_config` +returns in a variable named `config`, and we've updated the code that was using +the separate `search` and `filename` variables to use the fields on the +`Config` struct instead. + +### Creating a Constructor for `Config` + +Let's now think about the purpose of `parse_config`: it's a function that +creates a `Config` instance. We've already seen a convention for functions that +create instances: a `new` function, like `String::new`. Listing 12-6 shows the +result of transforming `parse_config` into a `new` function associated with our +`Config` struct: + +
+Filename: src/main.rs + +```rust + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args); + + // ...snip... +} + +# struct Config { +# search: String, +# filename: String, +# } +# +// ...snip... + +impl Config { + fn new(args: &[String]) -> Config { + let search = args[1].clone(); + let filename = args[2].clone(); + + Config { + search: search, + filename: filename, + } + } +} +``` + +
+ +Listing 12-6: Changing `parse_config` into `Config::new` + +
+
+ + + +We've changed the name of `parse_config` to `new` and moved it within an `impl` +block. We've also updated the callsite in `main`. Try compiling this again to +make sure it works. + +### Returning a `Result` from the Constructor + +Here's our last refactoring of this method: remember how accessing the vector +with indices 1 and 2 panics when it contains fewer than 3 items and gives a bad +error message? Let's fix that! Listing 12-7 shows how we can check that our +slice is long enough before accessing those locations, and panic with a better +error message: + +
+Filename: src/main.rs + +```rust,ignore +// ...snip... +fn new(args: &[String]) -> Config { + if args.len() < 3 { + panic!("not enough arguments"); + } + // ...snip... +``` + +
+ +Listing 12-7: Adding a check for the number of arguments + +
+
+ + + +With these extra few lines of code in `new`, let's try running our program +without any arguments: + +```bash +$ cargo run + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe` +thread 'main' panicked at 'not enough arguments', src\main.rs:29 +note: Run with `RUST_BACKTRACE=1` for a backtrace. +``` + +This is a bit better! We at least have a reasonable error message here. +However, we also have a bunch of extra information that we don't want to give +to our users. We can do better by changing the type signature of `new`. Right +now, it returns only a `Config`, so there's no way to indicate that an error +happened while creating our `Config`. Instead, we can return a `Result`, as +shown in Listing 12-8: + +
+Filename: src/main.rs + +```rust,ignore +# struct Config { +# search: String, +# filename: String, +# } +# +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let search = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { + search: search, + filename: filename, + }) + } +} +``` + +
+ +Listing 12-8: Return a `Result` from `Config::new` + +
+
+ + + +Our `new` function now returns a `Result`, with a `Config` instance in the +success case and a `&'static str` when an error happens. Recall from "The +Static Lifetime" section in Chapter 10 `&'static str` is the type of string +literals, which is what our error message is for now. + +We've made two changes in the body of the `new` function: instead of calling +`panic!` if there aren't enough arguments, we now return an `Err` value. We +wrapped the `Config` return value in an `Ok`. These changes make the function +conform to its new type signature. + +### Calling `Config::new` and Handling Errors + +Now we need to make some changes to `main` as shown in Listing 12-9: + +
+Filename: src/main.rs + +```rust,ignore +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // ...snip... +``` + +
+ +Listing 12-9: Exiting with an error code if creating a new `Config` fails + +
+
+ + + +We've added a new `use` line to import `process` from the standard library. +In the `main` function itself, we'll handle the `Result` value returned +from the `new` function and exit the process in a cleaner way if `Config::new` +returns an `Err` value. + +We're using a method we haven't covered before that's defined on `Result` +by the standard library: `unwrap_or_else`. This method has similar behavior as +`unwrap` if the `Result` is an `Ok` value: it returns the inner value `Ok` is +wrapping. Unlike `unwrap`, if the value is an `Err` value, this method calls a +*closure* which is an anonymous function that we define and pass as an argument +to `unwrap_or_else`. We'll be covering closures in more detail in Chapter XX; +the important part to understand in this case is that `unwrap_or_else` will +pass the inner value of the `Err` to our closure in the argument `err` that +appears between the vertical pipes. Using `unwrap_or_else` lets us do some +custom, non-`panic!` error handling. + +Said error handling is only two lines: we print out the error, then call +`std::process::exit`. That function will stop our program's execution +immediately and return the number passed to it as a return code. By convention, +a zero means success and any other value means failure. In the end, this has +similar characteristics to our `panic!`-based handling we had in Listing 12-7, +but we no longer get all the extra output. Let's try it: + +```bash +$ cargo run + Compiling greprs v0.1.0 (file:///project/greprs) + Finished debug [unoptimized + debuginfo] target(s) in 0.48 secs + Running `target\debug\greprs.exe` +Problem parsing arguments: not enough arguments +``` + +Great! This output is much friendlier for our users. + +### Handling Errors from the `run` Function + +Now that we're done refactoring our configuration parsing, let's improve our +program's logic. Listing 12-10 shows the code after extracting a function named +`run` that we'll call from `main`. The `run` function contains the code that +was in `main`: + +
+Filename: src/main.rs + +```rust,ignore +fn main() { + // ...snip... + + println!("Searching for {}", config.search); + println!("In file {}", config.filename); + + run(config); +} + +fn run(config: Config) { + let mut f = File::open(config.filename).expect("file not found"); + + let mut contents = String::new(); + f.read_to_string(&mut contents).expect("something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +// ...snip... +``` + +
+ +Listing 12-10: Extracting a `run` functionality for the rest of the program logic + +
+
+ + + +The contents of `run` are the previous lines that were in `main`, and the `run` +function takes a `Config` as an argument. Now that we have a separate function, +we can make a similar improvement to the one we made to `Config::new` in +Listing 12-8: let's return a `Result` instead of calling `panic!` via +`expect`. Listing 12-11 shows the addition of a `use` statement to bring +`std::error::Error` struct into scope and the changes to the `run` function +to return a `Result`: + +
+Filename: src/main.rs + +```rust,ignore +use std::error::Error; + +// ...snip... + +fn run(config: Config) -> Result<(), Box> { + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + println!("With text:\n{}", contents); + + Ok(()) +} +``` + +
+ +Listing 12-11: Changing the `run` function to return `Result` + +
+
+ + + +We've made three big changes here. The first is the return type of the `run` +function is now `Result<(), Box>`. Previously, our function returned the +unit type, `()`, so that's still the value returned in the `Ok` case. For our +error type, we're going to use `Box`. This is called a *trait object*, +which we'll be covering in Chapter XX. For now, think of it like this: +`Box` means the function will return some kind of type that implements +the `Error` trait, but we're not specifying what particular type the return +value will be. This gives us flexibility to return error values that may be of +different types in different error cases. `Box` is a smart pointer to heap +data, and we'll be going into detail about `Box` in Chapter YY. + +The second change is that we've removed our calls to `expect` in favor of `?`, +like we talked about in Chapter 9. Rather than `panic!` on an error, this will +return the error value from the function we're in for the caller to handle. + +The third change is that we're now returning an `Ok` value from this function +in the success case. Because we've declared the `run` function's success type +as `()` in the signature, we need to wrap the unit type value in the `Ok` +value. `Ok(())` looks a bit strange at first, but using `()` in this way is the +idiomatic way to indicate that we're calling `run` for its side effects only; +it doesn't return anything interesting. + +This will compile, but with a warning: + +```text +warning: unused result which must be used, #[warn(unused_must_use)] on by default + --> src\main.rs:39:5 + | +39 | run(config); + | ^^^^^^^^^^^^ +``` + +Rust is trying to tell us that we're ignoring our `Result`, which might be an +error value. Let's handle that now. We'll use a similar technique as the way we +handled failure with `Config::new` in Listing 12-9, but with a slight +difference: + +Filename: src/main.rs + +```rust,ignore +fn main() { + // ...snip... + + println!("Searching for {}", config.search); + println!("In file {}", config.filename); + + if let Err(e) = run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} +``` + + + +Instead of `unwrap_or_else`, we use `if let` to see if `run` returns an `Err` +value and call `process::exit(1)` if so. Why? The distinction between this case +and the `Config::new` case is a bit subtle. With `Config::new`, we cared about +two things: + +1. Detecting any errors that happen +2. Getting a `Config` if no errors happened + +In this case, because `run` returns a `()` in the success case, the only thing +we care about is the first case: detecting an error. If we used +`unwrap_or_else`, we'd get its return value, which would be `()`. That's not +very useful. + +The bodies of the `if let` and of the `unwrap_or_else` are the same in both +cases though: we print out an error and exit. + +### Split Code into a Library Crate + +This is looking pretty good! There's one more thing we haven't done yet: split +the *src/main.rs* up and put some code into *src/lib.rs* Let's do that now: +move the `run` function from *src/main.rs* to a new file, *src/lib.rs*. You'll +also need to move the relevant `use` statements and the definition of `Config` +and its `new` method as well. Your *src/lib.rs* should now look like Listing +12-12: + +
+Filename: src/lib.rs + +```rust,ignore +use std::error::Error; +use std::fs::File; +use std::io::prelude::*; + +pub struct Config { + pub search: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let search = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { + search: search, + filename: filename, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box>{ + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + println!("With text:\n{}", contents); + + Ok(()) +} +``` + +
+ +Listing 12-12: Moving `Config` and `run` into *src/lib.rs* + +
+
+ + + +Notice we also made liberal use of `pub`: on `Config`, its fields and its `new` +method, and on the `run` function. + +Now in *src/main.rs*, we need to bring in the code that's now in *src/lib.rs* +through `extern crate greprs`. Then we need to add a `use greprs::Config` line +to bring `Corfig` into scope, and prefix the `run` function with our crate name +as shown in Listing 12-13: + +
+Filename: src/main.rs + +```rust,ignore +extern crate greprs; + +use std::env; +use std::process; + +use greprs::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.search); + println!("In file {}", config.filename); + + if let Err(e) = greprs::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} +``` + +
+ +Listing 12-13: Bringing the `greprs` crate into the scope of *src/main.rs* + +
+
+ + + +With that, everything should work again. Give it a few `cargo run`s and make +sure you haven't broken anything. Whew! That all was a lot of work, but we've +set ourselves up for success in the future. We've set up a way to handle errors +in a much nicer fashion, and we've made our code slightly more modular. Almost +all of our work will be done in *src/lib.rs* from here on out. + +Let's take advantage of this newfound modularity by doing something that would +have been hard with our old code, but is easy with our new code: write some +tests! diff --git a/src/ch12-04-testing-the-librarys-functionality.md b/src/ch12-04-testing-the-librarys-functionality.md new file mode 100644 index 000000000..8d95c59fb --- /dev/null +++ b/src/ch12-04-testing-the-librarys-functionality.md @@ -0,0 +1,285 @@ + + +## Testing the Library's Functionality + +Writing tests for the core functionality of our code is now easier since we +extracted the logic into *src/lib.rs* and left all the argument parsing and +error handling in *src/main.rs*. We can now call our code directly with various +arguments and check return values without having to call our binary from the +command line. + +We're going to write a function named `grep` that takes our search term and the +text to search and procudes a list of search results. Let's remove that +`println!` from `run` (and from *src/main.rs* as well, as we don't really need +those anymore either), and call the new `grep` function with the options we've +collected. We'll add a placeholder implementation of the function for now, and +a test that specifies the behavior we'd like the `grep` function to have. The +test will fail with our placeholder implementation, of course, but we can make +sure the code compiles and that we get the failure message we expect. Listing +12-14 shows these modifications: + +
+Filename: src/lib.rs + +```rust +# use std::error::Error; +# use std::fs::File; +# use std::io::prelude::*; +# pub struct Config { +# pub search: String, +# pub filename: String, +# } +# +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + vec![] +} + +pub fn run(config: Config) -> Result<(), Box>{ + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + grep(&config.search, &contents); + + Ok(()) +} + +#[cfg(test)] +mod test { + use grep; + + #[test] + fn one_result() { + let search = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!( + vec!["safe, fast, productive."], + grep(search, contents) + ); + } +} +``` + +
+ +Listing 12-14: Creating a function where our logic will go and a failing test +for that function + +
+
+ + + +Notice that we need an explicit lifetime `'a` declared in the signature of +`grep` and used with the `contents` argument and the return value. Remember, +lifetime parameters are used to specify which arguments' lifetimes connect to +the lifetime of the return value. In this case, we're indicating that the +vector we're returning is going to contain string slices that reference slices +of the argument `contents`, as opposed to referencing slices of the argument +`search`. Another way to think about what we're telling Rust is that the data +returned by the `grep` function will live as long as the data passed into this +function in the `contents` argument. This is important! Given that the data a +slice references needs to be valid in order for the reference to be valid, if +the compiler thought that we were making string slices of `search` rather than +`contents`, it would do its safety checking incorrectly. If we tried to compile +this function without lifetimes, we would get this error: + +```text +error[E0106]: missing lifetime specifier + --> src\lib.rs:37:46 + | +37 | fn grep(search: &str, contents: &str) -> Vec<&str> { + | ^ expected lifetime parameter + | + = help: this function's return type contains a borrowed value, but the + signature does not say whether it is borrowed from `search` or + `contents` +``` + +Rust can't possibly know which of the two arguments we need, so it needs us to +tell it. Because `contents` is the argument that contains all of our text and +we want to return the parts of that text that match, we know `contents` is the +argument that should be connected to the return value using the lifetime syntax. + +Connecting arguments to return values in the signature is something that other +programming langugages don't make you do, so don't worry if this still feels +strange! Knowing how to specify lifetimes gets easier over time, and practice +makes perfect. You may want to re-read the above section or go back and compare +this example with the Lifetime Syntax section in Chapter 10. + +Now let's try running our test: + +```text +$ cargo test +...warnings... + Finished debug [unoptimized + debuginfo] target(s) in 0.43 secs + Running target/debug/deps/greprs-917c5edfc3cf199a + +running 1 test +test test::one_result ... FAILED + +failures: + +---- test::one_result stdout ---- + thread 'test::one_result' panicked at 'assertion failed: `(left == right)` +(left: `["safe, fast, productive."]`, right: `[]`)', src/lib.rs:16 +note: Run with `RUST_BACKTRACE=1` for a backtrace. + + +failures: + test::one_result + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured + +error: test failed +``` + +Great, our test fails, exactly as we expected. Let's get the test to pass! It's +failing because we always return an empty vector. Here's what we're going to do +to implement `grep`: + +1. Iterate through each line of the contents. +2. Check if the line contains our search string. + * If it does, add it to the list of values we're returning. + * If not, do nothing. +3. Return the list of results that match. + +Let's take each step at a time, starting with iterating through lines. Strings +have a helpful method to handle this, conveniently named `lines`: + +Filename: src/lib.rs + +```rust,ignore +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + for line in contents.lines() { + // do something with line + } +} +``` + + + +We're using a `for` loop along with the `lines` method to get each line in turn. +Next, let's see if our line contains the search string. Luckily, strings have a +helpful method named `contains` that does this for us! Using the `contains` +method looks like this: + +Filename: src/lib.rs + +```rust,ignore +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + for line in contents.lines() { + if line.contains(search) { + // do something with line + } + } +} +``` + + + +Finally, we need a way to store the lines that contain our search string. For +that, we can make a mutable vector before the `for` loop and call the `push` +method to store a `line` in the vector. After the `for` loop, we return the +vector: + +Filename: src/lib.rs + +```rust,ignore +fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(search) { + results.push(line); + } + } + + results +} +``` + + + +Let's give it a try: + +```text +$ cargo test +running 1 test +test test::one_result ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured + + Running target/debug/greprs-2f55ee8cd1721808 + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured + + Doc-tests greprs + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured +``` + +Great! It works. Now that our test is passing, we could consider opportunities +for refactoring the implementation of `grep` and be certain we maintain the +same functionality while we do so. This code isn't bad, but it isn't taking +advantage of some useful features of iterators. We'll be coming back to this +example in Chapter 13 where we'll explore iterators in detail and see how to +improve it. + +Now that the `grep` function is working, we need to do one last thing inside of +the `run` function: we never printed out the results! We'll do that by adding +a `for` loop that prints each line returned from the `grep` function: + +Filename: src/lib.rs + +```rust,ignore +pub fn run(config: Config) -> Result<(), Box>{ + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + for line in grep(&config.search, &contents) { + println!("{}", line); + } + + Ok(()) +} +``` + + + +Now our whole program should be working! Let's try it out: + +```text +$ cargo run the poem.txt + Compiling greprs v0.1.0 (file:///C:/Users/steve/tmp/greprs) + Finished debug [unoptimized + debuginfo] target(s) in 0.38 secs + Running `target\debug\greprs.exe the poem.txt` +Then there's a pair of us - don't tell! +To tell your name the livelong day + +$ cargo run a poem.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe a poem.txt` +I'm nobody! Who are you? +Then there's a pair of us - don't tell! +They'd banish us, you know. +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! +``` + +Excellent! We've built our own version of a classic tool, and learned a lot +about how to structure applications. We've also learned a bit about file input +and output, lifetimes, testing, and command line parsing. diff --git a/src/ch12-05-working-with-environment-variables.md b/src/ch12-05-working-with-environment-variables.md new file mode 100644 index 000000000..69a039310 --- /dev/null +++ b/src/ch12-05-working-with-environment-variables.md @@ -0,0 +1,248 @@ + +## Working with Environment Variables + +Let's add one more feature: case insensitive searching. In addtion, this +setting won't be a command line option: it'll be an environment variable +instead. We could choose to make case insensitivity a command line option, but +our users have requested an environment variable that they could set once and +make all their searches case insensitive in that terminal session. + +### Implement and Test a Case-Insensitive `grep` Function + +First, let's add a new function that we will call when the environment variable +is on. Let's start by adding a new test and re-naming our existing one: + +```rust,ignore +#[cfg(test)] +mod test { + use {grep, grep_case_insensitive}; + + #[test] + fn case_sensitive() { + let search = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!( + vec!["safe, fast, productive."], + grep(search, contents) + ); + } + + #[test] + fn case_insensitive() { + let search = "rust"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + grep_case_insensitive(search, contents) + ); + } +} +``` + + + +We're going to define a new function named `grep_case_insensitive`. Its +implementation will be almost the same as the `grep` function, but with some +minor changes: + +Filename: src/lib.rs + +```rust +fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { + let search = search.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&search) { + results.push(line); + } + } + + results +} +``` + + + +First, we lowercase the `search` string, and store it in a shadowed variable +with the same name. Note that `search` is now a `String` rather than a string +slice, so we need to add an ampersand when we pass `search` to `contains` since +`contains` takes a string slice. + +Second, we add a call to `to_lowercase` each `line` before we check if it +contains `search`. Since we've converted both `line` and `search` into all +lowercase, we'll find matches no matter what case they used in the file and the +command line arguments, respectively. Let's see if this passes the tests: + +```text + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running target\debug\deps\greprs-e58e9b12d35dc861.exe + +running 2 tests +test test::case_insensitive ... ok +test test::case_sensitive ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured + + Running target\debug\greprs-8a7faa2662b5030a.exe + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured + + Doc-tests greprs + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured +``` + +Great! Now, we have to actually use the new `grep_case_insensitive` function. +First, let's add a configuration option for it to the `Config` struct: + +Filename: src/lib.rs + +```rust +pub struct Config { + pub search: String, + pub filename: String, + pub case_sensitive: bool, +} +``` + + + +And then check for that option inside of the `run` function, and decide which +function to call based on the value of the `case_sensitive` function: + +Filename: src/lib.rs + +```rust,ignore +pub fn run(config: Config) -> Result<(), Box>{ + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + let results = if config.case_sensitive { + grep(&config.search, &contents) + } else { + grep_case_insensitive(&config.search, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} +``` + + + +Finally, we need to actually check the environment for the variable. To bring +the `env` module from the standard library into our project, we add a `use` line +at the top of *src/lib.rs*: + +Filename: src/lib.rs + +```rust +use std::env; +``` + +And then use the `vars` method from the `env` module inside of `Config::new`: + +Filename: src/lib.rs + +```rust +# use std::env; +# +# struct Config { +# search: String, +# filename: String, +# case_sensitive: bool, +# } +# +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let search = args[1].clone(); + let filename = args[2].clone(); + + let mut case_sensitive = true; + + for (name, _) in env::vars() { + if name == "CASE_INSENSITIVE" { + case_sensitive = false; + } + } + + Ok(Config { + search: search, + filename: filename, + case_sensitive: case_sensitive, + }) + } +} +``` + + + +Here, we call `env::vars`, which works in a similar way as `env::args`. The +difference is `env::vars` returns an iterator of environment variables rather +than command line arguments. Instead of using `collect` to create a vector of +all of the environment variables, we're using a `for` loop. `env::vars` returns +tuples: the name of the environment variable and its value. We never care about +the values, only if the variable is set at all, so we use the `_` placeholder +instead of a name to let Rust know that it shouldn't warn us about an unused +variable. Finally, we have a `case_sensitive` variable, which is set to true by +default. If we ever find a `CASE_INSENSITIVE` environment variable, we set the +`case_sensitive` variable to false instead. Then we return the value as part of +the `Config`. + +Let's give it a try! + +```text +$ cargo run to poem.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe to poem.txt` +Are you nobody, too? +How dreary to be somebody! +``` + +```text +$ CASE_INSENSITIVE=1 cargo run to poem.txt + Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs + Running `target\debug\greprs.exe to poem.txt` +Are you nobody, too? +How dreary to be somebody! +To tell your name the livelong day +To an admiring bog! +``` + +Excellent! Our `greprs` program can now do case insensitive searching controlled +by an environment variable. Now you know how to manage options set using +either command line arguments or environment variables! + +Some programs allow both arguments _and_ environment variables for the same +configuration. In those cases, the programs decide that one or the other of +arguments or environment variables take precedence. For another exercise on +your own, try controlling case insensitivity through a command line argument as +well, and decide which should take precedence if you run the program with +contradictory values. + +The `std::env` module contains many more useful features for dealing with +environment variables; check out its documentation to see what's available. diff --git a/src/ch12-06-writing-to-stderr-instead-of-stdout.md b/src/ch12-06-writing-to-stderr-instead-of-stdout.md new file mode 100644 index 000000000..3c2c07806 --- /dev/null +++ b/src/ch12-06-writing-to-stderr-instead-of-stdout.md @@ -0,0 +1,118 @@ + +## Write to `stderr` Instead of `stdout` + +Right now, we're writing all of our output to the terminal with `println!`. +This works, but most terminals provide two kinds of output: "standard out" is +used for most information, but "standard error" is used for error messages. This +makes it easier to do things like "Print error messages to my terminal, but +write other output to a file." + +We can see that our program is only capable of printing to `stdout` by +redirecting it to a file using `>` on the command line, and running our program +without any arguments, which causes an error: + +```text +$ cargo run > output.txt +``` + +The `>` syntax tells the shell to write the contents of standard out to +*output.txt* instead of the screen. However, if we open *output.txt* after +running we'll see our error message: + +```text +Application error: No search string or filename found +``` + +We'd like this to be printed to the screen instead, and only have the output +from a successful run end up in the file if we run our program this way. Let's +change how error messages are printed as shown in Listing 12-15: + +
+Filename: src/main.rs + +```rust,ignore +extern crate greprs; + +use std::env; +use std::process; + +use greprs::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = greprs::run(config) { + let mut stderr = std::io::stderr(); + + writeln!( + &mut stderr, + "Application error: {}", + e + ).expect("Could not write to stderr"); + + process::exit(1); + } +} +``` + +
+ +Listing 12-15: Writing error messages to `stderr` instead of `stdout` + +
+
+ + + +Rust does not have a convenient function like `println!` for writing to +standard error. Instead, we use the `writeln!` macro, which is sort of like +`println!`, but it takes an extra argument. The first thing we pass to it is +what to write to. We can aquire a handle to standard error through the +`std::io::stderr` function. We give a mutable reference to `stderr` to +`writeln!`; we need it to be mutable so we can write to it! The second and +third arguments to `writeln!` are like the first and second arguments to +`println!`: a format string and any variables we're interpolating. + +Let's try running the program again in the same way, without any arguments and +redirecting `stdout` with `>`: + +```text +$ cargo run > output.txt +Application error: No search string or filename found +``` + +Now we see our error on the screen, but `output.txt` contains nothing. If we +try it again with arguments that work: + +```text +$ cargo run to poem.txt > output.txt +``` + +We'll see no output to our terminal, but `output.txt` will contain +our results: + +Filename: output.txt + +```text +Are you nobody, too? +How dreary to be somebody! +``` + +## Summary + +In this chapter, we've covered how to do common I/O operations in a Rust +context. By using command line arguments, files, environment variables, and the +ability to write to `stderr`, you're now prepared to write command line +applications. By using the concepts from previous chapters, your code will be +well-organized, be able to store data effectively in the appropriate data +structures, handle errors nicely, and be well tested. We also saw a real-world +scenario where lifetime annotations are needed to ensure references are +always valid. + +Next, let's explore how to make use of some features of Rust that were +influenced by functional languages: closures and iterators. From e46fd3c432456841e8208fa31fd3a8556ff45450 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 28 Dec 2016 18:30:03 -0500 Subject: [PATCH 17/25] Use capitals instead of italics for grep explanation --- src/ch12-00-an-io-project.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ch12-00-an-io-project.md b/src/ch12-00-an-io-project.md index ebd73ccda..f79628889 100644 --- a/src/ch12-00-an-io-project.md +++ b/src/ch12-00-an-io-project.md @@ -8,7 +8,7 @@ So what should we build? One that uses Rust's strengths. A great use of Rust is for command line tools: Rust's speed, safety, 'single binary' output, and cross-platform support make it a good language choice for this kind of task. So we'll make our own version of a classic command line tool: `grep`. `grep` is -short for "*g*lobally search a *r*egular *e*xpression and *p*rint." In the +short for "Globally search a Regular Expression and Print." In the simplest use case, it does this: - Takes a filename and a string as arguments. From 70efcbe967a82b8328361268e5e4154a153f0727 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 28 Dec 2016 18:32:55 -0500 Subject: [PATCH 18/25] Add some words to the dictionary --- dictionary.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dictionary.txt b/dictionary.txt index 070c19fe4..bcd33ce9b 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -7,6 +7,7 @@ alignof Amir APIs aren +args backtrace BACKTRACE benchmarking @@ -84,6 +85,7 @@ GitHub gitignore grapheme Grapheme +greprs growable hardcoded hardcoding @@ -175,6 +177,7 @@ refactor refactoring RefCell repr +ripgrep runtime Rustacean Rustaceans From de6075be987eddec6feb8cbfc159cd53d439b8e7 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 28 Dec 2016 19:48:06 -0500 Subject: [PATCH 19/25] Fixing more spelling mistakes!!!!! --- dictionary.txt | 3 +++ ...2-03-improving-error-handling-and-modularity.md | 14 +++++++------- src/ch12-04-testing-the-librarys-functionality.md | 8 ++++---- src/ch12-05-working-with-environment-variables.md | 2 +- src/ch12-06-writing-to-stderr-instead-of-stdout.md | 2 +- 5 files changed, 16 insertions(+), 13 deletions(-) diff --git a/dictionary.txt b/dictionary.txt index bcd33ce9b..80b76ed70 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -141,6 +141,7 @@ namespace namespaced namespaces namespacing +newfound nocapture nomicon Nomicon @@ -193,6 +194,7 @@ someusername SpreadsheetCell sqrt stackoverflow +stderr stdin Stdin stdlib @@ -241,5 +243,6 @@ workspace workspaces Workspaces wouldn +writeln WriteMessage yyyy diff --git a/src/ch12-03-improving-error-handling-and-modularity.md b/src/ch12-03-improving-error-handling-and-modularity.md index 2a5193511..41b481669 100644 --- a/src/ch12-03-improving-error-handling-and-modularity.md +++ b/src/ch12-03-improving-error-handling-and-modularity.md @@ -90,8 +90,8 @@ this change, run the program again to verify that the argument parsing still works. It's good to check your progress often, so that you have a better idea of which change caused a problem, should you encounter one. - + @@ -106,12 +106,12 @@ function `parse_config`. The `config` part of the name is saying the two values we return should really be bound together, since they're both part of one configuration value. -> Note: some people call this antipattern of using primitive values when a +> Note: some people call this anti-pattern of using primitive values when a > complex type would be more appropriate *primitive obsession*. Let's introduce a struct to hold all of our configuration. Listing 12-5 shows -the addition of the `Config` struct definition, the refacting of `parse_config`, -and updates to `main`: +the addition of the `Config` struct definition, the refactoring of +`parse_config`, and updates to `main`:
Filename: src/main.rs @@ -159,7 +159,7 @@ struct The signature of `parse_config` now indicates that it returns a `Config` value. In the body of `parse_config`, we used to be returning string slices that were references to `String` values in `args`, but we've defined `Config` to contain -owend `String` values. Because the argument to `parse_config` is a slice of +owned `String` values. Because the argument to `parse_config` is a slice of `String` values, the `Config` instance can't take ownership of the `String` values: that violates Rust's borrowing rules, since the `args` variable in `main` owns the `String` values and is only letting the `parse_config` function @@ -609,7 +609,7 @@ method, and on the `run` function. Now in *src/main.rs*, we need to bring in the code that's now in *src/lib.rs* through `extern crate greprs`. Then we need to add a `use greprs::Config` line -to bring `Corfig` into scope, and prefix the `run` function with our crate name +to bring `Config` into scope, and prefix the `run` function with our crate name as shown in Listing 12-13:
diff --git a/src/ch12-04-testing-the-librarys-functionality.md b/src/ch12-04-testing-the-librarys-functionality.md index 8d95c59fb..a065d3c6d 100644 --- a/src/ch12-04-testing-the-librarys-functionality.md +++ b/src/ch12-04-testing-the-librarys-functionality.md @@ -9,7 +9,7 @@ arguments and check return values without having to call our binary from the command line. We're going to write a function named `grep` that takes our search term and the -text to search and procudes a list of search results. Let's remove that +text to search and produces a list of search results. Let's remove that `println!` from `run` (and from *src/main.rs* as well, as we don't really need those anymore either), and call the new `grep` function with the options we've collected. We'll add a placeholder implementation of the function for now, and @@ -107,7 +107,7 @@ we want to return the parts of that text that match, we know `contents` is the argument that should be connected to the return value using the lifetime syntax. Connecting arguments to return values in the signature is something that other -programming langugages don't make you do, so don't worry if this still feels +programming languages don't make you do, so don't worry if this still feels strange! Knowing how to specify lifetimes gets easier over time, and practice makes perfect. You may want to re-read the above section or go back and compare this example with the Lifetime Syntax section in Chapter 10. @@ -118,7 +118,7 @@ Now let's try running our test: $ cargo test ...warnings... Finished debug [unoptimized + debuginfo] target(s) in 0.43 secs - Running target/debug/deps/greprs-917c5edfc3cf199a + Running target/debug/deps/greprs-abcabcabc running 1 test test test::one_result ... FAILED @@ -262,7 +262,7 @@ Now our whole program should be working! Let's try it out: ```text $ cargo run the poem.txt - Compiling greprs v0.1.0 (file:///C:/Users/steve/tmp/greprs) + Compiling greprs v0.1.0 (file:///projects/greprs) Finished debug [unoptimized + debuginfo] target(s) in 0.38 secs Running `target\debug\greprs.exe the poem.txt` Then there's a pair of us - don't tell! diff --git a/src/ch12-05-working-with-environment-variables.md b/src/ch12-05-working-with-environment-variables.md index 69a039310..8383026e2 100644 --- a/src/ch12-05-working-with-environment-variables.md +++ b/src/ch12-05-working-with-environment-variables.md @@ -1,7 +1,7 @@ ## Working with Environment Variables -Let's add one more feature: case insensitive searching. In addtion, this +Let's add one more feature: case insensitive searching. In addition, this setting won't be a command line option: it'll be an environment variable instead. We could choose to make case insensitivity a command line option, but our users have requested an environment variable that they could set once and diff --git a/src/ch12-06-writing-to-stderr-instead-of-stdout.md b/src/ch12-06-writing-to-stderr-instead-of-stdout.md index 3c2c07806..3efb04d72 100644 --- a/src/ch12-06-writing-to-stderr-instead-of-stdout.md +++ b/src/ch12-06-writing-to-stderr-instead-of-stdout.md @@ -72,7 +72,7 @@ Listing 12-15: Writing error messages to `stderr` instead of `stdout` Rust does not have a convenient function like `println!` for writing to standard error. Instead, we use the `writeln!` macro, which is sort of like `println!`, but it takes an extra argument. The first thing we pass to it is -what to write to. We can aquire a handle to standard error through the +what to write to. We can acquire a handle to standard error through the `std::io::stderr` function. We give a mutable reference to `stderr` to `writeln!`; we need it to be mutable so we can write to it! The second and third arguments to `writeln!` are like the first and second arguments to From 609f68f3e9f71490b2961f9c308253d229dd96b3 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 28 Dec 2016 20:00:02 -0500 Subject: [PATCH 20/25] Fix a filename to match conventions --- src/ch12-03-improving-error-handling-and-modularity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ch12-03-improving-error-handling-and-modularity.md b/src/ch12-03-improving-error-handling-and-modularity.md index 41b481669..94df90333 100644 --- a/src/ch12-03-improving-error-handling-and-modularity.md +++ b/src/ch12-03-improving-error-handling-and-modularity.md @@ -387,7 +387,7 @@ but we no longer get all the extra output. Let's try it: ```bash $ cargo run - Compiling greprs v0.1.0 (file:///project/greprs) + Compiling greprs v0.1.0 (file:///projects/greprs) Finished debug [unoptimized + debuginfo] target(s) in 0.48 secs Running `target\debug\greprs.exe` Problem parsing arguments: not enough arguments From 587d605c8120bd66deb8a0962191835ae464fb4f Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 28 Dec 2016 20:06:40 -0500 Subject: [PATCH 21/25] One more in the dictionary --- dictionary.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/dictionary.txt b/dictionary.txt index 87b41a86a..77d71afcf 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -122,6 +122,7 @@ lang latin libc libcore +librarys libreoffice lifecycle loopback From 42c876b3fff0bde5e3f41b3ffbcc18b03aabd4cc Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 29 Dec 2016 10:31:06 -0500 Subject: [PATCH 22/25] Fix extra whitespace --- src/ch12-01-accepting-command-line-arguments.md | 1 - src/ch12-02-reading-a-file.md | 1 - src/ch12-04-testing-the-librarys-functionality.md | 2 -- src/ch12-05-working-with-environment-variables.md | 1 - src/ch12-06-writing-to-stderr-instead-of-stdout.md | 1 - 5 files changed, 6 deletions(-) diff --git a/src/ch12-01-accepting-command-line-arguments.md b/src/ch12-01-accepting-command-line-arguments.md index 6d6fac57f..93ecbd3bc 100644 --- a/src/ch12-01-accepting-command-line-arguments.md +++ b/src/ch12-01-accepting-command-line-arguments.md @@ -1,4 +1,3 @@ - ## Accepting Command Line Arguments Our first task is to have `greprs` accept its two command line arguments. There diff --git a/src/ch12-02-reading-a-file.md b/src/ch12-02-reading-a-file.md index 8e582957d..2e181237b 100644 --- a/src/ch12-02-reading-a-file.md +++ b/src/ch12-02-reading-a-file.md @@ -1,4 +1,3 @@ - ## Reading a File Now that we have some variables containing the information that we need, let's diff --git a/src/ch12-04-testing-the-librarys-functionality.md b/src/ch12-04-testing-the-librarys-functionality.md index a065d3c6d..d43017f39 100644 --- a/src/ch12-04-testing-the-librarys-functionality.md +++ b/src/ch12-04-testing-the-librarys-functionality.md @@ -1,5 +1,3 @@ - - ## Testing the Library's Functionality Writing tests for the core functionality of our code is now easier since we diff --git a/src/ch12-05-working-with-environment-variables.md b/src/ch12-05-working-with-environment-variables.md index 8383026e2..8dab306d1 100644 --- a/src/ch12-05-working-with-environment-variables.md +++ b/src/ch12-05-working-with-environment-variables.md @@ -1,4 +1,3 @@ - ## Working with Environment Variables Let's add one more feature: case insensitive searching. In addition, this diff --git a/src/ch12-06-writing-to-stderr-instead-of-stdout.md b/src/ch12-06-writing-to-stderr-instead-of-stdout.md index 3efb04d72..8fff0a25a 100644 --- a/src/ch12-06-writing-to-stderr-instead-of-stdout.md +++ b/src/ch12-06-writing-to-stderr-instead-of-stdout.md @@ -1,4 +1,3 @@ - ## Write to `stderr` Instead of `stdout` Right now, we're writing all of our output to the terminal with `println!`. From 30550a83659ac3cea682c6d299a62723e32065c0 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 29 Dec 2016 10:31:49 -0500 Subject: [PATCH 23/25] Don't mention the next function since we don't use it --- src/ch12-01-accepting-command-line-arguments.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/ch12-01-accepting-command-line-arguments.md b/src/ch12-01-accepting-command-line-arguments.md index 93ecbd3bc..a8256978f 100644 --- a/src/ch12-01-accepting-command-line-arguments.md +++ b/src/ch12-01-accepting-command-line-arguments.md @@ -11,8 +11,7 @@ Chapter 16 will cover them fully. For our purposes, though, we don't need to understand much about how they work in order to use them. We only need to understand two things: -1. Iterators produce a series of values by repeatedly calling a `next` - function. +1. Iterators produce a series of values. 2. We can call the `collect` function on an iterator to turn it into a vector containing all of the elements the iterator produces. From 469ace636c70796cf2496d90d91bf8f97d30bac4 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 29 Dec 2016 10:34:52 -0500 Subject: [PATCH 24/25] Make the paragraph about whether it's worth it to use clone into a box --- ...improving-error-handling-and-modularity.md | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/ch12-03-improving-error-handling-and-modularity.md b/src/ch12-03-improving-error-handling-and-modularity.md index 94df90333..36c9a4ed7 100644 --- a/src/ch12-03-improving-error-handling-and-modularity.md +++ b/src/ch12-03-improving-error-handling-and-modularity.md @@ -172,14 +172,21 @@ data for the `Config` instance to own, which does take more time and memory than storing a reference to the string data, but cloning the data makes our code very straightforward. -There's a tendency amongst many Rustaceans to prefer not to use `clone` to fix -ownership problems, due to its runtime cost. In Chapter XX on iterators, we'll -learn how to make this situation more efficient. For now, it's okay to copy a -few strings to keep making progress. We're only going to be making these copies -once, and our filename and search string are both very small. It's better to -have a working program that's a bit inefficient than try to hyper-optimize code -on your first pass. As you get more experienced with Rust, it'll be easier to -skip this step, but for now, it's perfectly acceptable to call `clone`. + + +> #### The Tradeoffs of Using `clone` +> +> There's a tendency amongst many Rustaceans to prefer not to use `clone` to fix +> ownership problems due to its runtime cost. In Chapter XX on iterators, we'll +> learn how to make this situation more efficient. For now, it's okay to copy a +> few strings to keep making progress. We're only going to be making these +> copies once, and our filename and search string are both very small. It's +> better to have a working program that's a bit inefficient than try to +> hyper-optimize code on your first pass. As you get more experienced with Rust, +> it'll be easier to skip this step, but for now, it's perfectly acceptable to +> call `clone`. + + We've updated `main` to put the instance of `Config` that `parse_config` returns in a variable named `config`, and we've updated the code that was using From c8b6fad1ba10754ed93944c305e153dffc6cc65a Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 29 Dec 2016 10:36:07 -0500 Subject: [PATCH 25/25] Space needed before curly braces --- src/ch12-04-testing-the-librarys-functionality.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ch12-04-testing-the-librarys-functionality.md b/src/ch12-04-testing-the-librarys-functionality.md index d43017f39..9da717de0 100644 --- a/src/ch12-04-testing-the-librarys-functionality.md +++ b/src/ch12-04-testing-the-librarys-functionality.md @@ -240,7 +240,7 @@ a `for` loop that prints each line returned from the `grep` function: Filename: src/lib.rs ```rust,ignore -pub fn run(config: Config) -> Result<(), Box>{ +pub fn run(config: Config) -> Result<(), Box> { let mut f = File::open(config.filename)?; let mut contents = String::new();