From fd359beff05f090ffe813cde73e178d3df6acc27 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Fri, 30 Dec 2016 17:48:52 +0000 Subject: [PATCH] rebuild pages at 901aa3d --- ch09-02-recoverable-errors-with-result.html | 2 +- ...proving-error-handling-and-modularity.html | 238 +++++++++++++++- ...04-testing-the-librarys-functionality.html | 5 +- ...6-writing-to-stderr-instead-of-stdout.html | 14 +- print.html | 259 ++++++++++++++++-- 5 files changed, 476 insertions(+), 42 deletions(-) diff --git a/ch09-02-recoverable-errors-with-result.html b/ch09-02-recoverable-errors-with-result.html index 3f65c6e7a..0930b554a 100644 --- a/ch09-02-recoverable-errors-with-result.html +++ b/ch09-02-recoverable-errors-with-result.html @@ -512,7 +512,7 @@ https://github.com/rust-lang/rust/issues/35946 fixed soon, hopefully before this chapter gets through copy editing-- at that point I'll make sure to update this error message. /Carol -->

When we compile this, we get the following error message:

-
error[E0308]: mismatched types
+
error[E0308]: mismatched types
  -->
   |
 3 |     let f = File::open("hello.txt")?;
diff --git a/ch12-03-improving-error-handling-and-modularity.html b/ch12-03-improving-error-handling-and-modularity.html
index 05dc876d8..0dd03195b 100644
--- a/ch12-03-improving-error-handling-and-modularity.html
+++ b/ch12-03-improving-error-handling-and-modularity.html
@@ -122,12 +122,26 @@ a new function parse_config, which we're still going to define in
 src/main.rs:

Filename: src/main.rs -
fn main() {
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+#
+fn main() {
     let args: Vec<String> = env::args().collect();
 
     let (search, filename) = parse_config(&args);
 
+    println!("Searching for {}", search);
+    println!("In file {}", filename);
+
     // ...snip...
+#
+#     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);
 }
 
 fn parse_config(args: &[String]) -> (&str, &str) {
@@ -146,11 +160,6 @@ fn parse_config(args: &[String]) -> (&str, &str) {
 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 @@ -169,6 +178,8 @@ the addition of the Config struct definition, the refactoring of

Filename: src/main.rs
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
 #
 fn main() {
     let args: Vec<String> = env::args().collect();
@@ -178,7 +189,13 @@ fn main() {
     println!("Searching for {}", config.search);
     println!("In file {}", config.filename);
 
+    let mut f = File::open(config.filename).expect("file not found");
+
     // ...snip...
+#     let mut contents = String::new();
+#     f.read_to_string(&mut contents).expect("something went wrong reading the file");
+#
+#    println!("With text:\n{}", contents);
 }
 
 struct Config {
@@ -242,13 +259,27 @@ result of transforming parse_config into a new functio
 Config struct:

Filename: src/main.rs -

+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+#
 fn main() {
     let args: Vec<String> = env::args().collect();
 
     let config = Config::new(&args);
 
+    println!("Searching for {}", config.search);
+    println!("In file {}", config.filename);
+
     // ...snip...
+
+#     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);
+
 }
 
 # struct Config {
@@ -286,12 +317,48 @@ slice is long enough before accessing those locations, and panic with a better
 error message:

Filename: src/main.rs -
// ...snip...
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+#
+# fn main() {
+#     let args: Vec<String> = env::args().collect();
+#
+#     let config = Config::new(&args);
+#
+#     println!("Searching for {}", config.search);
+#     println!("In file {}", config.filename);
+#
+#     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);
+# }
+#
+# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+# impl Config {
+// ...snip...
 fn new(args: &[String]) -> Config {
     if args.len() < 3 {
         panic!("not enough arguments");
     }
+
+    let search = args[1].clone();
     // ...snip...
+#     let filename = args[2].clone();
+#
+#     Config {
+#         search: search,
+#         filename: filename,
+#     }
+}
+# }
 

Listing 12-7: Adding a check for the number of arguments

@@ -300,7 +367,7 @@ fn new(args: &[String]) -> Config {

With these extra few lines of code in new, let's try running our program without any arguments:

-
$ cargo run
+
$ 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
@@ -314,7 +381,30 @@ happened while creating our Config. Instead, we can return a 
 shown in Listing 12-8:

Filename: src/main.rs -
# struct Config {
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+# use std::process;
+#
+# fn main() {
+#     let args: Vec<String> = 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);
+#
+#     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);
+# }
+# struct Config {
 #     search: String,
 #     filename: String,
 # }
@@ -352,7 +442,11 @@ 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 -
use std::process;
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+// ...snip...
+use std::process;
 
 fn main() {
     let args: Vec<String> = env::args().collect();
@@ -362,7 +456,39 @@ fn main() {
         process::exit(1);
     });
 
+    println!("Searching for {}", config.search);
+    println!("In file {}", config.filename);
+
     // ...snip...
+#
+#     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);
+# }
+#
+# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+# impl Config {
+#     fn new(args: &[String]) -> Result<Config, &'static str> {
+#         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-9: Exiting with an error code if creating a new Config fails

@@ -389,7 +515,7 @@ 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:

-
$ cargo run
+
$ cargo run
    Compiling greprs v0.1.0 (file:///projects/greprs)
     Finished debug [unoptimized + debuginfo] target(s) in 0.48 secs
      Running `target\debug\greprs.exe`
@@ -403,7 +529,18 @@ program's logic. Listing 12-10 shows the code after extracting a function named
 was in main:

Filename: src/main.rs -
fn main() {
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+# use std::process;
+#
+fn main() {
+#     let args: Vec<String> = 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);
@@ -422,6 +559,27 @@ fn run(config: Config) {
 }
 
 // ...snip...
+#
+# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+# impl Config {
+#     fn new(args: &[String]) -> Result<Config, &'static str> {
+#         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-10: Extracting a run functionality for the rest of the program logic

@@ -437,9 +595,27 @@ Listing 12-8: let's return a Result<T, E> instead of calling to return a Result:

Filename: src/main.rs -
use std::error::Error;
+
use std::error::Error;
+# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+# use std::process;
 
 // ...snip...
+# fn main() {
+#     let args: Vec<String> = 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) -> Result<(), Box<Error>> {
     let mut f = File::open(config.filename)?;
@@ -451,6 +627,27 @@ fn run(config: Config) -> Result<(), Box<Error>> {
 
     Ok(())
 }
+#
+# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+# impl Config {
+#     fn new(args: &[String]) -> Result<Config, &'static str> {
+#         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-11: Changing the run function to return Result

@@ -500,6 +697,17 @@ difference:

process::exit(1); } } + +fn run(config: Config) -> Result<(), Box<Error>> { + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + println!("With text:\n{}", contents); + + Ok(()) +}

Instead of unwrap_or_else, we use if let to see if run returns an Err @@ -525,7 +733,7 @@ and its new method as well. Your src/lib.rs should now loo 12-12:

Filename: src/lib.rs -
use std::error::Error;
+
use std::error::Error;
 use std::fs::File;
 use std::io::prelude::*;
 
diff --git a/ch12-04-testing-the-librarys-functionality.html b/ch12-04-testing-the-librarys-functionality.html
index 60dd41a1a..0d933feff 100644
--- a/ch12-04-testing-the-librarys-functionality.html
+++ b/ch12-04-testing-the-librarys-functionality.html
@@ -87,11 +87,14 @@ sure the code compiles and that we get the failure message we expect. Listing
 
# use std::error::Error;
 # use std::fs::File;
 # use std::io::prelude::*;
+#
 # pub struct Config {
 #     pub search: String,
 #     pub filename: String,
 # }
 #
+// ...snip...
+
 fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
      vec![]
 }
@@ -230,7 +233,7 @@ that, we can make a mutable vector before the for loop and call the
 method to store a line in the vector. After the for loop, we return the
 vector:

Filename: src/lib.rs

-
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
+
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
     let mut results = Vec::new();
 
     for line in contents.lines() {
diff --git a/ch12-06-writing-to-stderr-instead-of-stdout.html b/ch12-06-writing-to-stderr-instead-of-stdout.html
index 3b8c8ff1c..277125955 100644
--- a/ch12-06-writing-to-stderr-instead-of-stdout.html
+++ b/ch12-06-writing-to-stderr-instead-of-stdout.html
@@ -81,7 +81,7 @@ without any arguments, which causes an error:

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:

-
Application error: No search string or filename found
+
Problem parsing arguments: not enough arguments
 

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 @@ -92,19 +92,25 @@ change how error messages are printed as shown in Listing 12-15:

use std::env; use std::process; +use std::io::prelude::*; use greprs::Config; fn main() { + let mut stderr = std::io::stderr(); let args: Vec<String> = env::args().collect(); let config = Config::new(&args).unwrap_or_else(|err| { - println!("Problem parsing arguments: {}", err); + writeln!( + &mut stderr, + "Problem parsing arguments: {}", + err + ).expect("Could not write to stderr"); + process::exit(1); }); if let Err(e) = greprs::run(config) { - let mut stderr = std::io::stderr(); writeln!( &mut stderr, @@ -132,7 +138,7 @@ third arguments to writeln! are like the first and second arguments

Let's try running the program again in the same way, without any arguments and redirecting stdout with >:

$ cargo run > output.txt
-Application error: No search string or filename found
+Problem parsing arguments: not enough arguments
 

Now we see our error on the screen, but output.txt contains nothing. If we try it again with arguments that work:

diff --git a/print.html b/print.html index aba77f40c..20d6806fc 100644 --- a/print.html +++ b/print.html @@ -6891,7 +6891,7 @@ https://github.com/rust-lang/rust/issues/35946 fixed soon, hopefully before this chapter gets through copy editing-- at that point I'll make sure to update this error message. /Carol -->

When we compile this, we get the following error message:

-
error[E0308]: mismatched types
+
error[E0308]: mismatched types
  -->
   |
 3 |     let f = File::open("hello.txt")?;
@@ -9147,12 +9147,26 @@ a new function parse_config, which we're still going to define in
 src/main.rs:

Filename: src/main.rs -
fn main() {
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+#
+fn main() {
     let args: Vec<String> = env::args().collect();
 
     let (search, filename) = parse_config(&args);
 
+    println!("Searching for {}", search);
+    println!("In file {}", filename);
+
     // ...snip...
+#
+#     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);
 }
 
 fn parse_config(args: &[String]) -> (&str, &str) {
@@ -9171,11 +9185,6 @@ fn parse_config(args: &[String]) -> (&str, &str) {
 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 @@ -9194,6 +9203,8 @@ the addition of the Config struct definition, the refactoring of

Filename: src/main.rs
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
 #
 fn main() {
     let args: Vec<String> = env::args().collect();
@@ -9203,7 +9214,13 @@ fn main() {
     println!("Searching for {}", config.search);
     println!("In file {}", config.filename);
 
+    let mut f = File::open(config.filename).expect("file not found");
+
     // ...snip...
+#     let mut contents = String::new();
+#     f.read_to_string(&mut contents).expect("something went wrong reading the file");
+#
+#    println!("With text:\n{}", contents);
 }
 
 struct Config {
@@ -9267,13 +9284,27 @@ result of transforming parse_config into a new functio
 Config struct:

Filename: src/main.rs -

+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+#
 fn main() {
     let args: Vec<String> = env::args().collect();
 
     let config = Config::new(&args);
 
+    println!("Searching for {}", config.search);
+    println!("In file {}", config.filename);
+
     // ...snip...
+
+#     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);
+
 }
 
 # struct Config {
@@ -9311,12 +9342,48 @@ slice is long enough before accessing those locations, and panic with a better
 error message:

Filename: src/main.rs -
// ...snip...
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+#
+# fn main() {
+#     let args: Vec<String> = env::args().collect();
+#
+#     let config = Config::new(&args);
+#
+#     println!("Searching for {}", config.search);
+#     println!("In file {}", config.filename);
+#
+#     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);
+# }
+#
+# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+# impl Config {
+// ...snip...
 fn new(args: &[String]) -> Config {
     if args.len() < 3 {
         panic!("not enough arguments");
     }
+
+    let search = args[1].clone();
     // ...snip...
+#     let filename = args[2].clone();
+#
+#     Config {
+#         search: search,
+#         filename: filename,
+#     }
+}
+# }
 

Listing 12-7: Adding a check for the number of arguments

@@ -9325,7 +9392,7 @@ fn new(args: &[String]) -> Config {

With these extra few lines of code in new, let's try running our program without any arguments:

-
$ cargo run
+
$ 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
@@ -9339,7 +9406,30 @@ happened while creating our Config. Instead, we can return a 
 shown in Listing 12-8:

Filename: src/main.rs -
# struct Config {
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+# use std::process;
+#
+# fn main() {
+#     let args: Vec<String> = 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);
+#
+#     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);
+# }
+# struct Config {
 #     search: String,
 #     filename: String,
 # }
@@ -9377,7 +9467,11 @@ 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 -
use std::process;
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+// ...snip...
+use std::process;
 
 fn main() {
     let args: Vec<String> = env::args().collect();
@@ -9387,7 +9481,39 @@ fn main() {
         process::exit(1);
     });
 
+    println!("Searching for {}", config.search);
+    println!("In file {}", config.filename);
+
     // ...snip...
+#
+#     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);
+# }
+#
+# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+# impl Config {
+#     fn new(args: &[String]) -> Result<Config, &'static str> {
+#         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-9: Exiting with an error code if creating a new Config fails

@@ -9414,7 +9540,7 @@ 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:

-
$ cargo run
+
$ cargo run
    Compiling greprs v0.1.0 (file:///projects/greprs)
     Finished debug [unoptimized + debuginfo] target(s) in 0.48 secs
      Running `target\debug\greprs.exe`
@@ -9428,7 +9554,18 @@ program's logic. Listing 12-10 shows the code after extracting a function named
 was in main:

Filename: src/main.rs -
fn main() {
+
# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+# use std::process;
+#
+fn main() {
+#     let args: Vec<String> = 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);
@@ -9447,6 +9584,27 @@ fn run(config: Config) {
 }
 
 // ...snip...
+#
+# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+# impl Config {
+#     fn new(args: &[String]) -> Result<Config, &'static str> {
+#         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-10: Extracting a run functionality for the rest of the program logic

@@ -9462,9 +9620,27 @@ Listing 12-8: let's return a Result<T, E> instead of calling to return a Result:

Filename: src/main.rs -
use std::error::Error;
+
use std::error::Error;
+# use std::env;
+# use std::fs::File;
+# use std::io::prelude::*;
+# use std::process;
 
 // ...snip...
+# fn main() {
+#     let args: Vec<String> = 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) -> Result<(), Box<Error>> {
     let mut f = File::open(config.filename)?;
@@ -9476,6 +9652,27 @@ fn run(config: Config) -> Result<(), Box<Error>> {
 
     Ok(())
 }
+#
+# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+# impl Config {
+#     fn new(args: &[String]) -> Result<Config, &'static str> {
+#         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-11: Changing the run function to return Result

@@ -9525,6 +9722,17 @@ difference:

process::exit(1); } } + +fn run(config: Config) -> Result<(), Box<Error>> { + let mut f = File::open(config.filename)?; + + let mut contents = String::new(); + f.read_to_string(&mut contents)?; + + println!("With text:\n{}", contents); + + Ok(()) +}

Instead of unwrap_or_else, we use if let to see if run returns an Err @@ -9550,7 +9758,7 @@ and its new method as well. Your src/lib.rs should now loo 12-12:

Filename: src/lib.rs -
use std::error::Error;
+
use std::error::Error;
 use std::fs::File;
 use std::io::prelude::*;
 
@@ -9657,11 +9865,14 @@ sure the code compiles and that we get the failure message we expect. Listing
 
# use std::error::Error;
 # use std::fs::File;
 # use std::io::prelude::*;
+#
 # pub struct Config {
 #     pub search: String,
 #     pub filename: String,
 # }
 #
+// ...snip...
+
 fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
      vec![]
 }
@@ -9800,7 +10011,7 @@ that, we can make a mutable vector before the for loop and call the
 method to store a line in the vector. After the for loop, we return the
 vector:

Filename: src/lib.rs

-
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
+
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
     let mut results = Vec::new();
 
     for line in contents.lines() {
@@ -10096,7 +10307,7 @@ without any arguments, which causes an error:

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:

-
Application error: No search string or filename found
+
Problem parsing arguments: not enough arguments
 

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 @@ -10107,19 +10318,25 @@ change how error messages are printed as shown in Listing 12-15:

use std::env; use std::process; +use std::io::prelude::*; use greprs::Config; fn main() { + let mut stderr = std::io::stderr(); let args: Vec<String> = env::args().collect(); let config = Config::new(&args).unwrap_or_else(|err| { - println!("Problem parsing arguments: {}", err); + writeln!( + &mut stderr, + "Problem parsing arguments: {}", + err + ).expect("Could not write to stderr"); + process::exit(1); }); if let Err(e) = greprs::run(config) { - let mut stderr = std::io::stderr(); writeln!( &mut stderr, @@ -10147,7 +10364,7 @@ third arguments to writeln! are like the first and second arguments

Let's try running the program again in the same way, without any arguments and redirecting stdout with >:

$ cargo run > output.txt
-Application error: No search string or filename found
+Problem parsing arguments: not enough arguments
 

Now we see our error on the screen, but output.txt contains nothing. If we try it again with arguments that work: