Doing that thing i do

This commit is contained in:
Carol (Nichols || Goulding)
2016-12-23 14:35:00 -05:00
parent 196b7ff6f8
commit f3e052020a
+379 -209
View File
@@ -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
<figure>
<span class="filename">Filename: src/main.rs</span>
```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`.
<figcaption>
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
</figcaption>
</figure>
<!-- Will add wingdings in libreoffice /Carol -->
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
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
use std::env;
@@ -125,8 +140,20 @@ fn main() {
}
```
<figcaption>
Listing 12-2: Create variables to hold the search argument and filename argument
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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
<span class="filename">Filename: poem.txt</span>
```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
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
use std::env;
@@ -207,20 +235,35 @@ fn main() {
}
```
<figcaption>
Listing 12-3: Read the contents of the file specified by the second argument
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```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)
}
```
<figcaption>
Listing 12-4: Extract a `parse_config` function from `main`
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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.
<!-- steve: cargo check is going to be in stable rust soon, so we should
include it here i think. Thoughts? -->
<!-- I haven't been keeping up with what cargo check does-- it just checks
syntax? If it seems worthwhile to check that but not the functionality, I'd
be into it! /Carol -->
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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
fn main() {
let args: Vec<String> = 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.
<figcaption>
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);
</figcaption>
</figure>
println!("Searching for {}", config.search);
println!("In file {}", config.filename);
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
fn main() {
let args: Vec<String> = 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:
<figcaption>
```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.
</figcaption>
</figure>
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:
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```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:
<figcaption>
Listing 12-7: Adding a check for the number of arguments
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```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.
<figcaption>
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:
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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<T, E>`: `unwrap_or_else`. This method does
something similar to `unwrap`; that is, if the `Result<T, E>` 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.
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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<T, E>`
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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
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);
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<T, E>` instead of `panic!`ing with `expect`. First, we need to add a
line at the top:
<figcaption>
```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:
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
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<T, E>` 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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
use std::error::Error;
// ...snip...
fn run(config: Config) -> Result<(), Box<Error>> {
let mut f = File::open(config.filename)?;
@@ -554,13 +714,23 @@ fn run(config: Config) -> Result<(), Box<Error>> {
}
```
We have three big changes here. The first is the return type: `Result<(),
Box<Error>>`. Previously, our function returned nothing, aka `()`, so that's
still our `Ok` case. For our error type, we're going to use `Box<Error>`. This
is called a "trait object," which we'll be covering in chapter XX. For now,
think of it like this: a `Box<Error>` 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.
<figcaption>
Listing 12-10: Changing the `run` function to return `Result`
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
We've made three big changes here. The first is the return type of the `run`
function is now `Result<(), Box<Error>>`. 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<Error>`. This is called a *trait object*,
which we'll be covering in Chapter XX. For now, think of it like this:
`Box<Error>` 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