828 lines
47 KiB
HTML
828 lines
47 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>Refactoring to Improve Modularity and Error Handling</title>
|
||
</head>
|
||
<body>
|
||
<h2 id="refactoring-to-improve-modularity-and-error-handling"><a class="header" href="#refactoring-to-improve-modularity-and-error-handling">Refactoring to Improve Modularity and Error Handling</a></h2>
|
||
<p>To improve our program, we’ll fix four problems that have to do with the
|
||
program’s structure and how it’s handling potential errors. First, our <code>main</code>
|
||
function now performs two tasks: It parses arguments and reads files. As our
|
||
program grows, the number of separate tasks the <code>main</code> function handles will
|
||
increase. As a function gains responsibilities, it becomes more difficult to
|
||
reason about, harder to test, and harder to change without breaking one of its
|
||
parts. It’s best to separate functionality so that each function is responsible
|
||
for one task.</p>
|
||
<p>This issue also ties into the second problem: Although <code>query</code> and <code>file_path</code>
|
||
are configuration variables to our program, variables like <code>contents</code> are used
|
||
to perform the program’s logic. The longer <code>main</code> becomes, the more variables
|
||
we’ll need to bring into scope; the more variables we have in scope, the harder
|
||
it will be to keep track of the purpose of each. It’s best to group the
|
||
configuration variables into one structure to make their purpose clear.</p>
|
||
<p>The third problem is that we’ve used <code>expect</code> to print an error message when
|
||
reading the file fails, but the error message just prints <code>Should have been able to read the file</code>. Reading a file can fail in a number of ways: For
|
||
example, the file could be missing, or we might not have permission to open it.
|
||
Right now, regardless of the situation, we’d print the same error message for
|
||
everything, which wouldn’t give the user any information!</p>
|
||
<p>Fourth, we use <code>expect</code> to handle an error, and if the user runs our program
|
||
without specifying enough arguments, they’ll get an <code>index out of bounds</code> error
|
||
from Rust that doesn’t clearly explain the problem. It would be best if all the
|
||
error-handling code were in one place so that future maintainers had only one
|
||
place to consult the code if the error-handling logic needed to change. Having
|
||
all the error-handling code in one place will also ensure that we’re printing
|
||
messages that will be meaningful to our end users.</p>
|
||
<p>Let’s address these four problems by refactoring our project.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="separation-of-concerns-for-binary-projects"></a></p>
|
||
<h3 id="separating-concerns-in-binary-projects"><a class="header" href="#separating-concerns-in-binary-projects">Separating Concerns in Binary Projects</a></h3>
|
||
<p>The organizational problem of allocating responsibility for multiple tasks to
|
||
the <code>main</code> function is common to many binary projects. As a result, many Rust
|
||
programmers find it useful to split up the separate concerns of a binary
|
||
program when the <code>main</code> function starts getting large. This process has the
|
||
following steps:</p>
|
||
<ul>
|
||
<li>Split your program into a <em>main.rs</em> file and a <em>lib.rs</em> file and move your
|
||
program’s logic to <em>lib.rs</em>.</li>
|
||
<li>As long as your command line parsing logic is small, it can remain in
|
||
the <code>main</code> function.</li>
|
||
<li>When the command line parsing logic starts getting complicated, extract it
|
||
from the <code>main</code> function into other functions or types.</li>
|
||
</ul>
|
||
<p>The responsibilities that remain in the <code>main</code> function after this process
|
||
should be limited to the following:</p>
|
||
<ul>
|
||
<li>Calling the command line parsing logic with the argument values</li>
|
||
<li>Setting up any other configuration</li>
|
||
<li>Calling a <code>run</code> function in <em>lib.rs</em></li>
|
||
<li>Handling the error if <code>run</code> returns an error</li>
|
||
</ul>
|
||
<p>This pattern is about separating concerns: <em>main.rs</em> handles running the
|
||
program and <em>lib.rs</em> handles all the logic of the task at hand. Because you
|
||
can’t test the <code>main</code> function directly, this structure lets you test all of
|
||
your program’s logic by moving it out of the <code>main</code> function. The code that
|
||
remains in the <code>main</code> function will be small enough to verify its correctness
|
||
by reading it. Let’s rework our program by following this process.</p>
|
||
<h4 id="extracting-the-argument-parser"><a class="header" href="#extracting-the-argument-parser">Extracting the Argument Parser</a></h4>
|
||
<p>We’ll extract the functionality for parsing arguments into a function that
|
||
<code>main</code> will call. Listing 12-5 shows the new start of the <code>main</code> function that
|
||
calls a new function <code>parse_config</code>, which we’ll define in <em>src/main.rs</em>.</p>
|
||
<figure class="listing" id="listing-12-5">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
let args: Vec<String> = env::args().collect();
|
||
|
||
let (query, file_path) = parse_config(&args);
|
||
|
||
// --snip--
|
||
<span class="boring">
|
||
</span><span class="boring"> println!("Searching for {query}");
|
||
</span><span class="boring"> println!("In file {file_path}");
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let contents = fs::read_to_string(file_path)
|
||
</span><span class="boring"> .expect("Should have been able to read the file");
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("With text:\n{contents}");
|
||
</span>}
|
||
|
||
fn parse_config(args: &[String]) -> (&str, &str) {
|
||
let query = &args[1];
|
||
let file_path = &args[2];
|
||
|
||
(query, file_path)
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-12-5">Listing 12-5</a>: Extracting a <code>parse_config</code> function from <code>main</code></figcaption>
|
||
</figure>
|
||
<p>We’re still collecting the command line arguments into a vector, but instead of
|
||
assigning the argument value at index 1 to the variable <code>query</code> and the
|
||
argument value at index 2 to the variable <code>file_path</code> within the <code>main</code>
|
||
function, we pass the whole vector to the <code>parse_config</code> function. The
|
||
<code>parse_config</code> function then holds the logic that determines which argument
|
||
goes in which variable and passes the values back to <code>main</code>. We still create
|
||
the <code>query</code> and <code>file_path</code> variables in <code>main</code>, but <code>main</code> no longer has the
|
||
responsibility of determining how the command line arguments and variables
|
||
correspond.</p>
|
||
<p>This rework may seem like overkill for our small program, but we’re refactoring
|
||
in small, incremental 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, to help identify the cause of problems when they occur.</p>
|
||
<h4 id="grouping-configuration-values"><a class="header" href="#grouping-configuration-values">Grouping Configuration Values</a></h4>
|
||
<p>We can take another small step to improve the <code>parse_config</code> function further.
|
||
At the moment, we’re returning a tuple, but then we immediately break that
|
||
tuple into individual parts again. This is a sign that perhaps we don’t have
|
||
the right abstraction yet.</p>
|
||
<p>Another indicator that shows there’s room for improvement is the <code>config</code> part
|
||
of <code>parse_config</code>, which implies that the two values we return are related and
|
||
are both part of one configuration value. We’re not currently conveying this
|
||
meaning in the structure of the data other than by grouping the two values into
|
||
a tuple; we’ll instead put the two values into one struct and give each of the
|
||
struct fields a meaningful name. Doing so will make it easier for future
|
||
maintainers of this code to understand how the different values relate to each
|
||
other and what their purpose is.</p>
|
||
<p>Listing 12-6 shows the improvements to the <code>parse_config</code> function.</p>
|
||
<figure class="listing" id="listing-12-6">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust should_panic noplayground"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
let args: Vec<String> = env::args().collect();
|
||
|
||
let config = parse_config(&args);
|
||
|
||
println!("Searching for {}", config.query);
|
||
println!("In file {}", config.file_path);
|
||
|
||
let contents = fs::read_to_string(config.file_path)
|
||
.expect("Should have been able to read the file");
|
||
|
||
// --snip--
|
||
<span class="boring">
|
||
</span><span class="boring"> println!("With text:\n{contents}");
|
||
</span>}
|
||
|
||
struct Config {
|
||
query: String,
|
||
file_path: String,
|
||
}
|
||
|
||
fn parse_config(args: &[String]) -> Config {
|
||
let query = args[1].clone();
|
||
let file_path = args[2].clone();
|
||
|
||
Config { query, file_path }
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-12-6">Listing 12-6</a>: Refactoring <code>parse_config</code> to return an instance of a <code>Config</code> struct</figcaption>
|
||
</figure>
|
||
<p>We’ve added a struct named <code>Config</code> defined to have fields named <code>query</code> and
|
||
<code>file_path</code>. The signature of <code>parse_config</code> now indicates that it returns a
|
||
<code>Config</code> value. In the body of <code>parse_config</code>, where we used to return
|
||
string slices that reference <code>String</code> values in <code>args</code>, we now define <code>Config</code>
|
||
to contain owned <code>String</code> values. The <code>args</code> variable in <code>main</code> is the owner of
|
||
the argument values and is only letting the <code>parse_config</code> function borrow
|
||
them, which means we’d violate Rust’s borrowing rules if <code>Config</code> tried to take
|
||
ownership of the values in <code>args</code>.</p>
|
||
<p>There are a number of ways we could manage the <code>String</code> data; the easiest,
|
||
though somewhat inefficient, route is to call the <code>clone</code> method on the values.
|
||
This will make a full copy of the data for the <code>Config</code> instance to own, which
|
||
takes more time and memory than storing a reference to the string data.
|
||
However, cloning the data also makes our code very straightforward because we
|
||
don’t have to manage the lifetimes of the references; in this circumstance,
|
||
giving up a little performance to gain simplicity is a worthwhile trade-off.</p>
|
||
<section class="note" aria-role="note">
|
||
<h3 id="the-trade-offs-of-using-clone"><a class="header" href="#the-trade-offs-of-using-clone">The Trade-Offs of Using <code>clone</code></a></h3>
|
||
<p>There’s a tendency among many Rustaceans to avoid using <code>clone</code> to fix
|
||
ownership problems because of its runtime cost. In
|
||
<a href="../ch13/ch13-00-functional-features.html">Chapter 13</a><!-- ignore -->, you’ll learn how to use more efficient
|
||
methods in this type of situation. But for now, it’s okay to copy a few
|
||
strings to continue making progress because you’ll make these copies only
|
||
once and your file path and query string are very small. It’s better to have
|
||
a working program that’s a bit inefficient than to try to hyperoptimize code
|
||
on your first pass. As you become more experienced with Rust, it’ll be
|
||
easier to start with the most efficient solution, but for now, it’s
|
||
perfectly acceptable to call <code>clone</code>.</p>
|
||
</section>
|
||
<p>We’ve updated <code>main</code> so that it places the instance of <code>Config</code> returned by
|
||
<code>parse_config</code> into a variable named <code>config</code>, and we updated the code that
|
||
previously used the separate <code>query</code> and <code>file_path</code> variables so that it now
|
||
uses the fields on the <code>Config</code> struct instead.</p>
|
||
<p>Now our code more clearly conveys that <code>query</code> and <code>file_path</code> are related and
|
||
that their purpose is to configure how the program will work. Any code that
|
||
uses these values knows to find them in the <code>config</code> instance in the fields
|
||
named for their purpose.</p>
|
||
<h4 id="creating-a-constructor-for-config"><a class="header" href="#creating-a-constructor-for-config">Creating a Constructor for <code>Config</code></a></h4>
|
||
<p>So far, we’ve extracted the logic responsible for parsing the command line
|
||
arguments from <code>main</code> and placed it in the <code>parse_config</code> function. Doing so
|
||
helped us see that the <code>query</code> and <code>file_path</code> values were related, and that
|
||
relationship should be conveyed in our code. We then added a <code>Config</code> struct to
|
||
name the related purpose of <code>query</code> and <code>file_path</code> and to be able to return the
|
||
values’ names as struct field names from the <code>parse_config</code> function.</p>
|
||
<p>So, now that the purpose of the <code>parse_config</code> function is to create a <code>Config</code>
|
||
instance, we can change <code>parse_config</code> from a plain function to a function
|
||
named <code>new</code> that is associated with the <code>Config</code> struct. Making this change
|
||
will make the code more idiomatic. We can create instances of types in the
|
||
standard library, such as <code>String</code>, by calling <code>String::new</code>. Similarly, by
|
||
changing <code>parse_config</code> into a <code>new</code> function associated with <code>Config</code>, we’ll
|
||
be able to create instances of <code>Config</code> by calling <code>Config::new</code>. Listing 12-7
|
||
shows the changes we need to make.</p>
|
||
<figure class="listing" id="listing-12-7">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust should_panic noplayground"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
let args: Vec<String> = env::args().collect();
|
||
|
||
let config = Config::new(&args);
|
||
<span class="boring">
|
||
</span><span class="boring"> println!("Searching for {}", config.query);
|
||
</span><span class="boring"> println!("In file {}", config.file_path);
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)
|
||
</span><span class="boring"> .expect("Should have been able to read the file");
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("With text:\n{contents}");
|
||
</span>
|
||
// --snip--
|
||
}
|
||
|
||
// --snip--
|
||
|
||
<span class="boring">struct Config {
|
||
</span><span class="boring"> query: String,
|
||
</span><span class="boring"> file_path: String,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>impl Config {
|
||
fn new(args: &[String]) -> Config {
|
||
let query = args[1].clone();
|
||
let file_path = args[2].clone();
|
||
|
||
Config { query, file_path }
|
||
}
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-12-7">Listing 12-7</a>: Changing <code>parse_config</code> into <code>Config::new</code></figcaption>
|
||
</figure>
|
||
<p>We’ve updated <code>main</code> where we were calling <code>parse_config</code> to instead call
|
||
<code>Config::new</code>. We’ve changed the name of <code>parse_config</code> to <code>new</code> and moved it
|
||
within an <code>impl</code> block, which associates the <code>new</code> function with <code>Config</code>. Try
|
||
compiling this code again to make sure it works.</p>
|
||
<h3 id="fixing-the-error-handling"><a class="header" href="#fixing-the-error-handling">Fixing the Error Handling</a></h3>
|
||
<p>Now we’ll work on fixing our error handling. Recall that attempting to access
|
||
the values in the <code>args</code> vector at index 1 or index 2 will cause the program to
|
||
panic if the vector contains fewer than three items. Try running the program
|
||
without any arguments; it will look like this:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling minigrep v0.1.0 (file:///projects/minigrep)
|
||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
|
||
Running `target/debug/minigrep`
|
||
|
||
thread 'main' panicked at src/main.rs:27:21:
|
||
index out of bounds: the len is 1 but the index is 1
|
||
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
|
||
</code></pre>
|
||
<p>The line <code>index out of bounds: the len is 1 but the index is 1</code> is an error
|
||
message intended for programmers. It won’t help our end users understand what
|
||
they should do instead. Let’s fix that now.</p>
|
||
<h4 id="improving-the-error-message"><a class="header" href="#improving-the-error-message">Improving the Error Message</a></h4>
|
||
<p>In Listing 12-8, we add a check in the <code>new</code> function that will verify that the
|
||
slice is long enough before accessing index 1 and index 2. If the slice isn’t
|
||
long enough, the program panics and displays a better error message.</p>
|
||
<figure class="listing" id="listing-12-8">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">
|
||
</span><span class="boring">fn main() {
|
||
</span><span class="boring"> let args: Vec<String> = env::args().collect();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let config = Config::new(&args);
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("Searching for {}", config.query);
|
||
</span><span class="boring"> println!("In file {}", config.file_path);
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)
|
||
</span><span class="boring"> .expect("Should have been able to read the file");
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("With text:\n{contents}");
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Config {
|
||
</span><span class="boring"> query: String,
|
||
</span><span class="boring"> file_path: String,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Config {
|
||
</span> // --snip--
|
||
fn new(args: &[String]) -> Config {
|
||
if args.len() < 3 {
|
||
panic!("not enough arguments");
|
||
}
|
||
// --snip--
|
||
<span class="boring">
|
||
</span><span class="boring"> let query = args[1].clone();
|
||
</span><span class="boring"> let file_path = args[2].clone();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> Config { query, file_path }
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-12-8">Listing 12-8</a>: Adding a check for the number of arguments</figcaption>
|
||
</figure>
|
||
<p>This code is similar to <a href="../ch09/ch09-03-to-panic-or-not-to-panic.html#creating-custom-types-for-validation">the <code>Guess::new</code> function we wrote in Listing
|
||
9-13</a><!-- ignore -->, where we called <code>panic!</code> when the
|
||
<code>value</code> argument was out of the range of valid values. Instead of checking for
|
||
a range of values here, we’re checking that the length of <code>args</code> is at least
|
||
<code>3</code> and the rest of the function can operate under the assumption that this
|
||
condition has been met. If <code>args</code> has fewer than three items, this condition
|
||
will be <code>true</code>, and we call the <code>panic!</code> macro to end the program immediately.</p>
|
||
<p>With these extra few lines of code in <code>new</code>, let’s run the program without any
|
||
arguments again to see what the error looks like now:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling minigrep v0.1.0 (file:///projects/minigrep)
|
||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
|
||
Running `target/debug/minigrep`
|
||
|
||
thread 'main' panicked at src/main.rs:26:13:
|
||
not enough arguments
|
||
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
|
||
</code></pre>
|
||
<p>This output is better: We now have a reasonable error message. However, we also
|
||
have extraneous information we don’t want to give to our users. Perhaps the
|
||
technique we used in Listing 9-13 isn’t the best one to use here: A call to
|
||
<code>panic!</code> is more appropriate for a programming problem than a usage problem,
|
||
<a href="../ch09/ch09-03-to-panic-or-not-to-panic.html#guidelines-for-error-handling">as discussed in Chapter 9</a><!-- ignore -->. Instead,
|
||
we’ll use the other technique you learned about in Chapter 9—<a href="../ch09/ch09-02-recoverable-errors-with-result.html">returning a
|
||
<code>Result</code></a><!-- ignore --> that indicates either success or an error.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="returning-a-result-from-new-instead-of-calling-panic"></a></p>
|
||
<h4 id="returning-a-result-instead-of-calling-panic"><a class="header" href="#returning-a-result-instead-of-calling-panic">Returning a <code>Result</code> Instead of Calling <code>panic!</code></a></h4>
|
||
<p>We can instead return a <code>Result</code> value that will contain a <code>Config</code> instance in
|
||
the successful case and will describe the problem in the error case. We’re also
|
||
going to change the function name from <code>new</code> to <code>build</code> because many
|
||
programmers expect <code>new</code> functions to never fail. When <code>Config::build</code> is
|
||
communicating to <code>main</code>, we can use the <code>Result</code> type to signal there was a
|
||
problem. Then, we can change <code>main</code> to convert an <code>Err</code> variant into a more
|
||
practical error for our users without the surrounding text about <code>thread 'main'</code> and <code>RUST_BACKTRACE</code> that a call to <code>panic!</code> causes.</p>
|
||
<p>Listing 12-9 shows the changes we need to make to the return value of the
|
||
function we’re now calling <code>Config::build</code> and the body of the function needed
|
||
to return a <code>Result</code>. Note that this won’t compile until we update <code>main</code> as
|
||
well, which we’ll do in the next listing.</p>
|
||
<figure class="listing" id="listing-12-9">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">
|
||
</span><span class="boring">fn main() {
|
||
</span><span class="boring"> let args: Vec<String> = env::args().collect();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let config = Config::new(&args);
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("Searching for {}", config.query);
|
||
</span><span class="boring"> println!("In file {}", config.file_path);
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)
|
||
</span><span class="boring"> .expect("Should have been able to read the file");
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("With text:\n{contents}");
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Config {
|
||
</span><span class="boring"> query: String,
|
||
</span><span class="boring"> file_path: String,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>impl Config {
|
||
fn build(args: &[String]) -> Result<Config, &'static str> {
|
||
if args.len() < 3 {
|
||
return Err("not enough arguments");
|
||
}
|
||
|
||
let query = args[1].clone();
|
||
let file_path = args[2].clone();
|
||
|
||
Ok(Config { query, file_path })
|
||
}
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-12-9">Listing 12-9</a>: Returning a <code>Result</code> from <code>Config::build</code></figcaption>
|
||
</figure>
|
||
<p>Our <code>build</code> function returns a <code>Result</code> with a <code>Config</code> instance in the success
|
||
case and a string literal in the error case. Our error values will always be
|
||
string literals that have the <code>'static</code> lifetime.</p>
|
||
<p>We’ve made two changes in the body of the function: Instead of calling <code>panic!</code>
|
||
when the user doesn’t pass enough arguments, we now return an <code>Err</code> value, and
|
||
we’ve wrapped the <code>Config</code> return value in an <code>Ok</code>. These changes make the
|
||
function conform to its new type signature.</p>
|
||
<p>Returning an <code>Err</code> value from <code>Config::build</code> allows the <code>main</code> function to
|
||
handle the <code>Result</code> value returned from the <code>build</code> function and exit the
|
||
process more cleanly in the error case.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="calling-confignew-and-handling-errors"></a></p>
|
||
<h4 id="calling-configbuild-and-handling-errors"><a class="header" href="#calling-configbuild-and-handling-errors">Calling <code>Config::build</code> and Handling Errors</a></h4>
|
||
<p>To handle the error case and print a user-friendly message, we need to update
|
||
<code>main</code> to handle the <code>Result</code> being returned by <code>Config::build</code>, as shown in
|
||
Listing 12-10. We’ll also take the responsibility of exiting the command line
|
||
tool with a nonzero error code away from <code>panic!</code> and instead implement it by
|
||
hand. A nonzero exit status is a convention to signal to the process that
|
||
called our program that the program exited with an error state.</p>
|
||
<figure class="listing" id="listing-12-10">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::fs;
|
||
</span>use std::process;
|
||
|
||
fn main() {
|
||
let args: Vec<String> = env::args().collect();
|
||
|
||
let config = Config::build(&args).unwrap_or_else(|err| {
|
||
println!("Problem parsing arguments: {err}");
|
||
process::exit(1);
|
||
});
|
||
|
||
// --snip--
|
||
<span class="boring">
|
||
</span><span class="boring"> println!("Searching for {}", config.query);
|
||
</span><span class="boring"> println!("In file {}", config.file_path);
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)
|
||
</span><span class="boring"> .expect("Should have been able to read the file");
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("With text:\n{contents}");
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Config {
|
||
</span><span class="boring"> query: String,
|
||
</span><span class="boring"> file_path: String,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Config {
|
||
</span><span class="boring"> fn build(args: &[String]) -> Result<Config, &'static str> {
|
||
</span><span class="boring"> if args.len() < 3 {
|
||
</span><span class="boring"> return Err("not enough arguments");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let query = args[1].clone();
|
||
</span><span class="boring"> let file_path = args[2].clone();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> Ok(Config { query, file_path })
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-12-10">Listing 12-10</a>: Exiting with an error code if building a <code>Config</code> fails</figcaption>
|
||
</figure>
|
||
<p>In this listing, we’ve used a method we haven’t covered in detail yet:
|
||
<code>unwrap_or_else</code>, which is defined on <code>Result<T, E></code> by the standard library.
|
||
Using <code>unwrap_or_else</code> allows us to define some custom, non-<code>panic!</code> error
|
||
handling. If the <code>Result</code> is an <code>Ok</code> value, this method’s behavior is similar
|
||
to <code>unwrap</code>: It returns the inner value that <code>Ok</code> is wrapping. However, if the
|
||
value is an <code>Err</code> value, this method calls the code in the closure, which is
|
||
an anonymous function we define and pass as an argument to <code>unwrap_or_else</code>.
|
||
We’ll cover closures in more detail in <a href="../ch13/ch13-00-functional-features.html">Chapter 13</a><!-- ignore -->. For
|
||
now, you just need to know that <code>unwrap_or_else</code> will pass the inner value of
|
||
the <code>Err</code>, which in this case is the static string <code>"not enough arguments"</code>
|
||
that we added in Listing 12-9, to our closure in the argument <code>err</code> that
|
||
appears between the vertical pipes. The code in the closure can then use the
|
||
<code>err</code> value when it runs.</p>
|
||
<p>We’ve added a new <code>use</code> line to bring <code>process</code> from the standard library into
|
||
scope. The code in the closure that will be run in the error case is only two
|
||
lines: We print the <code>err</code> value and then call <code>process::exit</code>. The
|
||
<code>process::exit</code> function will stop the program immediately and return the
|
||
number that was passed as the exit status code. This is similar to the
|
||
<code>panic!</code>-based handling we used in Listing 12-8, but we no longer get all the
|
||
extra output. Let’s try it:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling minigrep v0.1.0 (file:///projects/minigrep)
|
||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
|
||
Running `target/debug/minigrep`
|
||
Problem parsing arguments: not enough arguments
|
||
</code></pre>
|
||
<p>Great! This output is much friendlier for our users.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="extracting-logic-from-the-main-function"></a></p>
|
||
<h3 id="extracting-logic-from-main"><a class="header" href="#extracting-logic-from-main">Extracting Logic from <code>main</code></a></h3>
|
||
<p>Now that we’ve finished refactoring the configuration parsing, let’s turn to
|
||
the program’s logic. As we stated in <a href="#separation-of-concerns-for-binary-projects">“Separating Concerns in Binary
|
||
Projects”</a><!-- ignore -->, we’ll
|
||
extract a function named <code>run</code> that will hold all the logic currently in the
|
||
<code>main</code> function that isn’t involved with setting up configuration or handling
|
||
errors. When we’re done, the <code>main</code> function will be concise and easy to verify
|
||
by inspection, and we’ll be able to write tests for all the other logic.</p>
|
||
<p>Listing 12-11 shows the small, incremental improvement of extracting a <code>run</code>
|
||
function.</p>
|
||
<figure class="listing" id="listing-12-11">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">use std::process;
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
// --snip--
|
||
|
||
<span class="boring"> let args: Vec<String> = env::args().collect();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let config = Config::build(&args).unwrap_or_else(|err| {
|
||
</span><span class="boring"> println!("Problem parsing arguments: {err}");
|
||
</span><span class="boring"> process::exit(1);
|
||
</span><span class="boring"> });
|
||
</span><span class="boring">
|
||
</span> println!("Searching for {}", config.query);
|
||
println!("In file {}", config.file_path);
|
||
|
||
run(config);
|
||
}
|
||
|
||
fn run(config: Config) {
|
||
let contents = fs::read_to_string(config.file_path)
|
||
.expect("Should have been able to read the file");
|
||
|
||
println!("With text:\n{contents}");
|
||
}
|
||
|
||
// --snip--
|
||
<span class="boring">
|
||
</span><span class="boring">struct Config {
|
||
</span><span class="boring"> query: String,
|
||
</span><span class="boring"> file_path: String,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Config {
|
||
</span><span class="boring"> fn build(args: &[String]) -> Result<Config, &'static str> {
|
||
</span><span class="boring"> if args.len() < 3 {
|
||
</span><span class="boring"> return Err("not enough arguments");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let query = args[1].clone();
|
||
</span><span class="boring"> let file_path = args[2].clone();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> Ok(Config { query, file_path })
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-12-11">Listing 12-11</a>: Extracting a <code>run</code> function containing the rest of the program logic</figcaption>
|
||
</figure>
|
||
<p>The <code>run</code> function now contains all the remaining logic from <code>main</code>, starting
|
||
from reading the file. The <code>run</code> function takes the <code>Config</code> instance as an
|
||
argument.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="returning-errors-from-the-run-function"></a></p>
|
||
<h4 id="returning-errors-from-run"><a class="header" href="#returning-errors-from-run">Returning Errors from <code>run</code></a></h4>
|
||
<p>With the remaining program logic separated into the <code>run</code> function, we can
|
||
improve the error handling, as we did with <code>Config::build</code> in Listing 12-9.
|
||
Instead of allowing the program to panic by calling <code>expect</code>, the <code>run</code>
|
||
function will return a <code>Result<T, E></code> when something goes wrong. This will let
|
||
us further consolidate the logic around handling errors into <code>main</code> in a
|
||
user-friendly way. Listing 12-12 shows the changes we need to make to the
|
||
signature and body of <code>run</code>.</p>
|
||
<figure class="listing" id="listing-12-12">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">use std::process;
|
||
</span>use std::error::Error;
|
||
|
||
// --snip--
|
||
|
||
<span class="boring">
|
||
</span><span class="boring">fn main() {
|
||
</span><span class="boring"> let args: Vec<String> = env::args().collect();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let config = Config::build(&args).unwrap_or_else(|err| {
|
||
</span><span class="boring"> println!("Problem parsing arguments: {err}");
|
||
</span><span class="boring"> process::exit(1);
|
||
</span><span class="boring"> });
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("Searching for {}", config.query);
|
||
</span><span class="boring"> println!("In file {}", config.file_path);
|
||
</span><span class="boring">
|
||
</span><span class="boring"> run(config);
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn run(config: Config) -> Result<(), Box<dyn Error>> {
|
||
let contents = fs::read_to_string(config.file_path)?;
|
||
|
||
println!("With text:\n{contents}");
|
||
|
||
Ok(())
|
||
}
|
||
<span class="boring">
|
||
</span><span class="boring">struct Config {
|
||
</span><span class="boring"> query: String,
|
||
</span><span class="boring"> file_path: String,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Config {
|
||
</span><span class="boring"> fn build(args: &[String]) -> Result<Config, &'static str> {
|
||
</span><span class="boring"> if args.len() < 3 {
|
||
</span><span class="boring"> return Err("not enough arguments");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let query = args[1].clone();
|
||
</span><span class="boring"> let file_path = args[2].clone();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> Ok(Config { query, file_path })
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-12-12">Listing 12-12</a>: Changing the <code>run</code> function to return <code>Result</code></figcaption>
|
||
</figure>
|
||
<p>We’ve made three significant changes here. First, we changed the return type of
|
||
the <code>run</code> function to <code>Result<(), Box<dyn Error>></code>. This function previously
|
||
returned the unit type, <code>()</code>, and we keep that as the value returned in the
|
||
<code>Ok</code> case.</p>
|
||
<p>For the error type, we used the trait object <code>Box<dyn Error></code> (and we brought
|
||
<code>std::error::Error</code> into scope with a <code>use</code> statement at the top). We’ll cover
|
||
trait objects in <a href="../ch18/ch18-00-oop.html">Chapter 18</a><!-- ignore -->. For now, just know that
|
||
<code>Box<dyn Error></code> means the function will return a type that implements the
|
||
<code>Error</code> trait, but we don’t have to specify 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. The <code>dyn</code> keyword is short for
|
||
<em>dynamic</em>.</p>
|
||
<p>Second, we’ve removed the call to <code>expect</code> in favor of the <code>?</code> operator, as we
|
||
talked about in <a href="../ch09/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator">Chapter 9</a><!-- ignore -->. Rather than
|
||
<code>panic!</code> on an error, <code>?</code> will return the error value from the current function
|
||
for the caller to handle.</p>
|
||
<p>Third, the <code>run</code> function now returns an <code>Ok</code> value in the success case.
|
||
We’ve declared the <code>run</code> function’s success type as <code>()</code> in the signature,
|
||
which means we need to wrap the unit type value in the <code>Ok</code> value. This
|
||
<code>Ok(())</code> syntax might look a bit strange at first. But using <code>()</code> like this is
|
||
the idiomatic way to indicate that we’re calling <code>run</code> for its side effects
|
||
only; it doesn’t return a value we need.</p>
|
||
<p>When you run this code, it will compile but will display a warning:</p>
|
||
<pre><code class="language-console">$ cargo run -- the poem.txt
|
||
Compiling minigrep v0.1.0 (file:///projects/minigrep)
|
||
warning: unused `Result` that must be used
|
||
--> src/main.rs:19:5
|
||
|
|
||
19 | run(config);
|
||
| ^^^^^^^^^^^
|
||
|
|
||
= note: this `Result` may be an `Err` variant, which should be handled
|
||
= note: `#[warn(unused_must_use)]` on by default
|
||
help: use `let _ = ...` to ignore the resulting value
|
||
|
|
||
19 | let _ = run(config);
|
||
| +++++++
|
||
|
||
warning: `minigrep` (bin "minigrep") generated 1 warning
|
||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.71s
|
||
Running `target/debug/minigrep 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!
|
||
|
||
</code></pre>
|
||
<p>Rust tells us that our code ignored the <code>Result</code> value and the <code>Result</code> value
|
||
might indicate that an error occurred. But we’re not checking to see whether or
|
||
not there was an error, and the compiler reminds us that we probably meant to
|
||
have some error-handling code here! Let’s rectify that problem now.</p>
|
||
<h4 id="handling-errors-returned-from-run-in-main"><a class="header" href="#handling-errors-returned-from-run-in-main">Handling Errors Returned from <code>run</code> in <code>main</code></a></h4>
|
||
<p>We’ll check for errors and handle them using a technique similar to one we used
|
||
with <code>Config::build</code> in Listing 12-10, but with a slight difference:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust ignore"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::error::Error;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">use std::process;
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
// --snip--
|
||
|
||
<span class="boring"> let args: Vec<String> = env::args().collect();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let config = Config::build(&args).unwrap_or_else(|err| {
|
||
</span><span class="boring"> println!("Problem parsing arguments: {err}");
|
||
</span><span class="boring"> process::exit(1);
|
||
</span><span class="boring"> });
|
||
</span><span class="boring">
|
||
</span> println!("Searching for {}", config.query);
|
||
println!("In file {}", config.file_path);
|
||
|
||
if let Err(e) = run(config) {
|
||
println!("Application error: {e}");
|
||
process::exit(1);
|
||
}
|
||
}
|
||
<span class="boring">
|
||
</span><span class="boring">fn run(config: Config) -> Result<(), Box<dyn Error>> {
|
||
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
|
||
</span><span class="boring">
|
||
</span><span class="boring"> println!("With text:\n{contents}");
|
||
</span><span class="boring">
|
||
</span><span class="boring"> Ok(())
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Config {
|
||
</span><span class="boring"> query: String,
|
||
</span><span class="boring"> file_path: String,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Config {
|
||
</span><span class="boring"> fn build(args: &[String]) -> Result<Config, &'static str> {
|
||
</span><span class="boring"> if args.len() < 3 {
|
||
</span><span class="boring"> return Err("not enough arguments");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let query = args[1].clone();
|
||
</span><span class="boring"> let file_path = args[2].clone();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> Ok(Config { query, file_path })
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}</span></code></pre>
|
||
<p>We use <code>if let</code> rather than <code>unwrap_or_else</code> to check whether <code>run</code> returns an
|
||
<code>Err</code> value and to call <code>process::exit(1)</code> if it does. The <code>run</code> function
|
||
doesn’t return a value that we want to <code>unwrap</code> in the same way that
|
||
<code>Config::build</code> returns the <code>Config</code> instance. Because <code>run</code> returns <code>()</code> in
|
||
the success case, we only care about detecting an error, so we don’t need
|
||
<code>unwrap_or_else</code> to return the unwrapped value, which would only be <code>()</code>.</p>
|
||
<p>The bodies of the <code>if let</code> and the <code>unwrap_or_else</code> functions are the same in
|
||
both cases: We print the error and exit.</p>
|
||
<h3 id="splitting-code-into-a-library-crate"><a class="header" href="#splitting-code-into-a-library-crate">Splitting Code into a Library Crate</a></h3>
|
||
<p>Our <code>minigrep</code> project is looking good so far! Now we’ll split the
|
||
<em>src/main.rs</em> file and put some code into the <em>src/lib.rs</em> file. That way, we
|
||
can test the code and have a <em>src/main.rs</em> file with fewer responsibilities.</p>
|
||
<p>Let’s define the code responsible for searching text in <em>src/lib.rs</em> rather
|
||
than in <em>src/main.rs</em>, which will let us (or anyone else using our
|
||
<code>minigrep</code> library) call the searching function from more contexts than our
|
||
<code>minigrep</code> binary.</p>
|
||
<p>First, let’s define the <code>search</code> function signature in <em>src/lib.rs</em> as shown in
|
||
Listing 12-13, with a body that calls the <code>unimplemented!</code> macro. We’ll explain
|
||
the signature in more detail when we fill in the implementation.</p>
|
||
<figure class="listing" id="listing-12-13">
|
||
<span class="file-name">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust ignore does_not_compile">pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
|
||
unimplemented!();
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-12-13">Listing 12-13</a>: Defining the <code>search</code> function in <em>src/lib.rs</em></figcaption>
|
||
</figure>
|
||
<p>We’ve used the <code>pub</code> keyword on the function definition to designate <code>search</code>
|
||
as part of our library crate’s public API. We now have a library crate that we
|
||
can use from our binary crate and that we can test!</p>
|
||
<p>Now we need to bring the code defined in <em>src/lib.rs</em> into the scope of the
|
||
binary crate in <em>src/main.rs</em> and call it, as shown in Listing 12-14.</p>
|
||
<figure class="listing" id="listing-12-14">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore"><span class="boring">use std::env;
|
||
</span><span class="boring">use std::error::Error;
|
||
</span><span class="boring">use std::fs;
|
||
</span><span class="boring">use std::process;
|
||
</span><span class="boring">
|
||
</span>// --snip--
|
||
use minigrep::search;
|
||
|
||
fn main() {
|
||
// --snip--
|
||
<span class="boring"> let args: Vec<String> = env::args().collect();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let config = Config::build(&args).unwrap_or_else(|err| {
|
||
</span><span class="boring"> println!("Problem parsing arguments: {err}");
|
||
</span><span class="boring"> process::exit(1);
|
||
</span><span class="boring"> });
|
||
</span><span class="boring">
|
||
</span><span class="boring"> if let Err(e) = run(config) {
|
||
</span><span class="boring"> println!("Application error: {e}");
|
||
</span><span class="boring"> process::exit(1);
|
||
</span><span class="boring"> }
|
||
</span>}
|
||
|
||
// --snip--
|
||
|
||
<span class="boring">
|
||
</span><span class="boring">struct Config {
|
||
</span><span class="boring"> query: String,
|
||
</span><span class="boring"> file_path: String,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Config {
|
||
</span><span class="boring"> fn build(args: &[String]) -> Result<Config, &'static str> {
|
||
</span><span class="boring"> if args.len() < 3 {
|
||
</span><span class="boring"> return Err("not enough arguments");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">
|
||
</span><span class="boring"> let query = args[1].clone();
|
||
</span><span class="boring"> let file_path = args[2].clone();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> Ok(Config { query, file_path })
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn run(config: Config) -> Result<(), Box<dyn Error>> {
|
||
let contents = fs::read_to_string(config.file_path)?;
|
||
|
||
for line in search(&config.query, &contents) {
|
||
println!("{line}");
|
||
}
|
||
|
||
Ok(())
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-12-14">Listing 12-14</a>: Using the <code>minigrep</code> library crate’s <code>search</code> function in <em>src/main.rs</em></figcaption>
|
||
</figure>
|
||
<p>We add a <code>use minigrep::search</code> line to bring the <code>search</code> function from
|
||
the library crate into the binary crate’s scope. Then, in the <code>run</code> function,
|
||
rather than printing out the contents of the file, we call the <code>search</code>
|
||
function and pass the <code>config.query</code> value and <code>contents</code> as arguments. Then,
|
||
<code>run</code> will use a <code>for</code> loop to print each line returned from <code>search</code> that
|
||
matched the query. This is also a good time to remove the <code>println!</code> calls in
|
||
the <code>main</code> function that displayed the query and the file path so that our
|
||
program only prints the search results (if no errors occur).</p>
|
||
<p>Note that the search function will be collecting all the results into a vector
|
||
it returns before any printing happens. This implementation could be slow to
|
||
display results when searching large files, because results aren’t printed as
|
||
they’re found; we’ll discuss a possible way to fix this using iterators in
|
||
Chapter 13.</p>
|
||
<p>Whew! That was a lot of work, but we’ve set ourselves up for success in the
|
||
future. Now it’s much easier to handle errors, and we’ve made the code more
|
||
modular. Almost all of our work will be done in <em>src/lib.rs</em> from here on out.</p>
|
||
<p>Let’s take advantage of this newfound modularity by doing something that would
|
||
have been difficult with the old code but is easy with the new code: We’ll
|
||
write some tests!</p>
|
||
</body>
|
||
</html>
|