The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Returning a `Result` Instead of Calling `panic!`

This code is similar to the `Guess::new` function we wrote in Listing
9-13, where we called `panic!` when the
`value` 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 `args` is at least
`3` and the rest of the function can operate under the assumption that this
condition has been met. If `args` has fewer than three items, this condition
will be `true`, and we call the `panic!` macro to end the program immediately.
With these extra few lines of code in `new`, let’s run the program without any
arguments again to see what the error looks like now:
```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' (6023776) panicked at src/main.rs:26:13:
not enough arguments
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
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
`panic!` is more appropriate for a programming problem than a usage problem,
as discussed in Chapter 9. Instead,
we’ll use the other technique you learned about in Chapter 9—returning a
`Result` that indicates either success or an error.


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Returning a `Result` Instead of Calling `panic!`

We can instead return a `Result` value that will contain a `Config` instance in
the successful case and will describe the problem in the error case. We’re also
going to change the function name from `new` to `build` because many
programmers expect `new` functions to never fail. When `Config::build` is
communicating to `main`, we can use the `Result` type to signal there was a
problem. Then, we can change `main` to convert an `Err` variant into a more
practical error for our users without the surrounding text about `thread
'main'` and `RUST_BACKTRACE` that a call to `panic!` causes.
Listing 12-9 shows the changes we need to make to the return value of the
function we’re now calling `Config::build` and the body of the function needed
to return a `Result`. Note that this won’t compile until we update `main` as
well, which we’ll do in the next listing.
Listing 12-9: Returning a `Result` from `Config::build` (src/main.rs)
```rust,ignore,does_not_compile
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 })
    }
}
```
Our `build` function returns a `Result` with a `Config` instance in the success
case and a string literal in the error case. Our error values will always be
string literals that have the `'static` lifetime.


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Calling `Config::build` and Handling Errors

We’ve made two changes in the body of the function: Instead of calling `panic!`
when the user doesn’t pass enough arguments, we now return an `Err` value, and
we’ve wrapped the `Config` return value in an `Ok`. These changes make the
function conform to its new type signature.
Returning an `Err` value from `Config::build` allows the `main` function to
handle the `Result` value returned from the `build` function and exit the
process more cleanly in the error case.
To handle the error case and print a user-friendly message, we need to update
`main` to handle the `Result` being returned by `Config::build`, 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 `panic!` 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.
Listing 12-10: Exiting with an error code if building a `Config` fails (src/main.rs)
```rust,ignore
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--
```


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Calling `Config::build` and Handling Errors

In this listing, we’ve used a method we haven’t covered in detail yet:
`unwrap_or_else`, which is defined on `Result<T, E>` by the standard library.
Using `unwrap_or_else` allows us to define some custom, non-`panic!` error
handling. If the `Result` is an `Ok` value, this method’s behavior is similar
to `unwrap`: It returns the inner value that `Ok` is wrapping. However, if the
value is an `Err` value, this method calls the code in the closure, which is
an anonymous function we define and pass as an argument to `unwrap_or_else`.
We’ll cover closures in more detail in Chapter 13. For
now, you just need to know that `unwrap_or_else` will pass the inner value of
the `Err`, which in this case is the static string `"not enough arguments"`
that we added in Listing 12-9, to our closure in the argument `err` that
appears between the vertical pipes. The code in the closure can then use the
`err` value when it runs.
We’ve added a new `use` line to bring `process` 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 `err` value and then call `process::exit`. The
`process::exit` function will stop the program immediately and return the
number that was passed as the exit status code. This is similar to the
`panic!`-based handling we used in Listing 12-8, but we no longer get all the
extra output. Let’s try it:


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Calling `Config::build` and Handling Errors

```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
```
Great! This output is much friendlier for our users.


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Returning Errors from `run`

Now that we’ve finished refactoring the configuration parsing, let’s turn to
the program’s logic. As we stated in “Separating Concerns in Binary
Projects”, we’ll
extract a function named `run` that will hold all the logic currently in the
`main` function that isn’t involved with setting up configuration or handling
errors. When we’re done, the `main` function will be concise and easy to verify
by inspection, and we’ll be able to write tests for all the other logic.
Listing 12-11 shows the small, incremental improvement of extracting a `run`
function.
Listing 12-11: Extracting a `run` function containing the rest of the program logic (src/main.rs)
```rust,ignore
fn main() {
    // --snip--

    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--
```
The `run` function now contains all the remaining logic from `main`, starting
from reading the file. The `run` function takes the `Config` instance as an
argument.


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Returning Errors from `run`

With the remaining program logic separated into the `run` function, we can
improve the error handling, as we did with `Config::build` in Listing 12-9.
Instead of allowing the program to panic by calling `expect`, the `run`
function will return a `Result<T, E>` when something goes wrong. This will let
us further consolidate the logic around handling errors into `main` in a
user-friendly way. Listing 12-12 shows the changes we need to make to the
signature and body of `run`.
Listing 12-12: Changing the `run` function to return `Result` (src/main.rs)
```rust,ignore
use std::error::Error;

// --snip--

fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    println!("With text:\n{contents}");

    Ok(())
}
```
We’ve made three significant changes here. First, we changed the return type of
the `run` function to `Result<(), Box<dyn Error>>`. This function previously
returned the unit type, `()`, and we keep that as the value returned in the
`Ok` case.
For the error type, we used the trait object `Box<dyn Error>` (and we brought
`std::error::Error` into scope with a `use` statement at the top). We’ll cover
trait objects in Chapter 18. For now, just know that
`Box<dyn Error>` means the function will return a type that implements the
`Error` 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 `dyn` keyword is short for
_dynamic_.


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Returning Errors from `run`

Second, we’ve removed the call to `expect` in favor of the `?` operator, as we
talked about in Chapter 9. Rather than
`panic!` on an error, `?` will return the error value from the current function
for the caller to handle.
Third, the `run` function now returns an `Ok` value in the success case.
We’ve declared the `run` function’s success type as `()` in the signature,
which means we need to wrap the unit type value in the `Ok` value. This
`Ok(())` syntax might look a bit strange at first. But using `()` like this is
the idiomatic way to indicate that we’re calling `run` for its side effects
only; it doesn’t return a value we need.
When you run this code, it will compile but will display a warning:


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Handling Errors Returned from `run` in `main`

```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)]` (part of `#[warn(unused)]`) 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!

```
Rust tells us that our code ignored the `Result` value and the `Result` 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.
We’ll check for errors and handle them using a technique similar to one we used
with `Config::build` in Listing 12-10, but with a slight difference:
Filename: src/main.rs


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Handling Errors Returned from `run` in `main`

```rust,ignore
fn main() {
    // --snip--

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    if let Err(e) = run(config) {
        println!("Application error: {e}");
        process::exit(1);
    }
}
```
We use `if let` rather than `unwrap_or_else` to check whether `run` returns an
`Err` value and to call `process::exit(1)` if it does. The `run` function
doesn’t return a value that we want to `unwrap` in the same way that
`Config::build` returns the `Config` instance. Because `run` returns `()` in
the success case, we only care about detecting an error, so we don’t need
`unwrap_or_else` to return the unwrapped value, which would only be `()`.
The bodies of the `if let` and the `unwrap_or_else` functions are the same in
both cases: We print the error and exit.


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Splitting Code into a Library Crate

Our `minigrep` project is looking good so far! Now we’ll split the
_src/main.rs_ file and put some code into the _src/lib.rs_ file. That way, we
can test the code and have a _src/main.rs_ file with fewer responsibilities.
Let’s define the code responsible for searching text in _src/lib.rs_ rather
than in _src/main.rs_, which will let us (or anyone else using our
`minigrep` library) call the searching function from more contexts than our
`minigrep` binary.
First, let’s define the `search` function signature in _src/lib.rs_ as shown in
Listing 12-13, with a body that calls the `unimplemented!` macro. We’ll explain
the signature in more detail when we fill in the implementation.
Listing 12-13: Defining the `search` function in *src/lib.rs* (src/lib.rs)
```rust,ignore,does_not_compile
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    unimplemented!();
}
```
We’ve used the `pub` keyword on the function definition to designate `search`
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!
Now we need to bring the code defined in _src/lib.rs_ into the scope of the
binary crate in _src/main.rs_ and call it, as shown in Listing 12-14.
Listing 12-14: Using the `minigrep` library crate’s `search` function in *src/main.rs* (src/main.rs)


The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Splitting Code into a Library Crate

```rust,ignore
// --snip--
use minigrep::search;

fn main() {
    // --snip--
}

// --snip--

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(())
}
```
We add a `use minigrep::search` line to bring the `search` function from
the library crate into the binary crate’s scope. Then, in the `run` function,
rather than printing out the contents of the file, we call the `search`
function and pass the `config.query` value and `contents` as arguments. Then,
`run` will use a `for` loop to print each line returned from `search` that
matched the query. This is also a good time to remove the `println!` calls in
the `main` function that displayed the query and the file path so that our
program only prints the search results (if no errors occur).
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.
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 _src/lib.rs_ from here on out.
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!


The Rust Programming Language › Adding Functionality with Test-Driven Development

Now that we have the search logic in _src/lib.rs_ separate from the `main`
function, it’s much easier to write tests for the core functionality of our
code. We can call functions directly with various arguments and check return
values without having to call our binary from the command line.
In this section, we’ll add the searching logic to the `minigrep` program using
the test-driven development (TDD) process with the following steps:
1. Write a test that fails and run it to make sure it fails for the reason you
   expect.
2. Write or modify just enough code to make the new test pass.
3. Refactor the code you just added or changed and make sure the tests continue
   to pass.
4. Repeat from step 1!
Though it’s just one of many ways to write software, TDD can help drive code
design. Writing the test before you write the code that makes the test pass
helps maintain high test coverage throughout the process.
We’ll test-drive the implementation of the functionality that will actually do
the searching for the query string in the file contents and produce a list of
lines that match the query. We’ll add this functionality in a function called
`search`.

Adding Functionality with Test Driven Development


The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing a Failing Test

In _src/lib.rs_, we’ll add a `tests` module with a test function, as we did in
Chapter 11. The test function specifies the
behavior we want the `search` function to have: It will take a query and the
text to search, and it will return only the lines from the text that contain
the query. Listing 12-15 shows this test.
Listing 12-15: Creating a failing test for the `search` function for the functionality we wish we had (src/lib.rs)
```rust,ignore,does_not_compile
// --snip--

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }
}
```
This test searches for the string `"duct"`. The text we’re searching is three
lines, only one of which contains `"duct"` (note that the backslash after the
opening double quote tells Rust not to put a newline character at the beginning
of the contents of this string literal). We assert that the value returned from
the `search` function contains only the line we expect.
If we run this test, it will currently fail because the `unimplemented!` macro
panics with the message “not implemented”. In accordance with TDD principles,
we’ll take a small step of adding just enough code to get the test to not panic
when calling the function by defining the `search` function to always return an
empty vector, as shown in Listing 12-16. Then, the test should compile and fail
because an empty vector doesn’t match a vector containing the line `"safe,
fast, productive."`.


The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing a Failing Test

Listing 12-16: Defining just enough of the `search` function so that calling it won’t panic (src/lib.rs)
```rust,noplayground
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    vec![]
}
```
Now let’s discuss why we need to define an explicit lifetime `'a` in the
signature of `search` and use that lifetime with the `contents` argument and
the return value. Recall in Chapter 10 that
the lifetime parameters specify which argument lifetime is connected to the
lifetime of the return value. In this case, we indicate that the returned
vector should contain string slices that reference slices of the argument
`contents` (rather than the argument `query`).
In other words, we tell Rust that the data returned by the `search` function
will live as long as the data passed into the `search` function in the
`contents` argument. This is important! The data referenced _by_ a slice needs
to be valid for the reference to be valid; if the compiler assumes we’re making
string slices of `query` rather than `contents`, it will do its safety checking
incorrectly.
If we forget the lifetime annotations and try to compile this function, we’ll
get this error:


The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing a Failing Test

```console
$ cargo build
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
error[E0106]: missing lifetime specifier
 --> src/lib.rs:1:51
  |
1 | pub fn search(query: &str, contents: &str) -> Vec<&str> {
  |                      ----            ----         ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents`
help: consider introducing a named lifetime parameter
  |
1 | pub fn search<'a>(query: &'a str, contents: &'a str) -> Vec<&'a str> {
  |              ++++         ++                 ++              ++

For more information about this error, try `rustc --explain E0106`.
error: could not compile `minigrep` (lib) due to 1 previous error
```
Rust can’t know which of the two parameters we need for the output, so we need
to tell it explicitly. Note that the help text suggests specifying the same
lifetime parameter for all the parameters and the output type, which is
incorrect! Because `contents` is the parameter that contains all of our text
and we want to return the parts of that text that match, we know `contents` is
the only parameter that should be connected to the return value using the
lifetime syntax.
Other programming languages don’t require you to connect arguments to return
values in the signature, but this practice will get easier over time. You might
want to compare this example with the examples in the “Validating References
with Lifetimes” section
in Chapter 10.


The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing Code to Pass the Test › Searching Each Line for the Query

Currently, our test is failing because we always return an empty vector. To fix
that and implement `search`, our program needs to follow these steps:
1. Iterate through each line of the contents.
2. Check whether the line contains our query string.
3. If it does, add it to the list of values we’re returning.
4. If it doesn’t, do nothing.
5. Return the list of results that match.
Let’s work through each step, starting with iterating through lines.
Rust has a helpful method to handle line-by-line iteration of strings,
conveniently named `lines`, that works as shown in Listing 12-17. Note that
this won’t compile yet.
Listing 12-17: Iterating through each line in `contents` (src/lib.rs)
```rust,ignore,does_not_compile
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    for line in contents.lines() {
        // do something with line
    }
}
```
The `lines` method returns an iterator. We’ll talk about iterators in depth in
Chapter 13. But recall that you saw this way
of using an iterator in Listing 3-5, where we used a
`for` loop with an iterator to run some code on each item in a collection.
Next, we’ll check whether the current line contains our query string.
Fortunately, strings have a helpful method named `contains` that does this for
us! Add a call to the `contains` method in the `search` function, as shown in
Listing 12-18. Note that this still won’t compile yet.
Listing 12-18: Adding functionality to see whether the line contains the string in `query` (src/lib.rs)


The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing Code to Pass the Test › Storing Matching Lines

```rust,ignore,does_not_compile
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    for line in contents.lines() {
        if line.contains(query) {
            // do something with line
        }
    }
}
```
At the moment, we’re building up functionality. To get the code to compile, we
need to return a value from the body as we indicated we would in the function
signature.
To finish this function, we need a way to store the matching lines that we want
to return. For that, we can make a mutable vector before the `for` loop and
call the `push` method to store a `line` in the vector. After the `for` loop,
we return the vector, as shown in Listing 12-19.
Listing 12-19: Storing the lines that match so that we can return them (src/lib.rs)
```rust,ignore
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}
```
Now the `search` function should return only the lines that contain `query`,
and our test should pass. Let’s run the test:


The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing Code to Pass the Test › Storing Matching Lines

```console
$ cargo test
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 1.22s
     Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 1 test
test tests::one_result ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests minigrep

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

```
Our test passed, so we know it works!
At this point, we could consider opportunities for refactoring the
implementation of the search function while keeping the tests passing to
maintain the same functionality. The code in the search function isn’t too bad,
but it doesn’t take advantage of some useful features of iterators. We’ll
return to this example in Chapter 13, where
we’ll explore iterators in detail, and look at how to improve it.
Now the entire program should work! Let’s try it out, first with a word that
should return exactly one line from the Emily Dickinson poem: _frog_.


The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing Code to Pass the Test › Storing Matching Lines

```console
$ cargo run -- frog poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.38s
     Running `target/debug/minigrep frog poem.txt`
How public, like a frog
```
Cool! Now let’s try a word that will match multiple lines, like _body_:
```console
$ cargo run -- body poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep body poem.txt`
I'm nobody! Who are you?
Are you nobody, too?
How dreary to be somebody!
```
And finally, let’s make sure that we don’t get any lines when we search for a
word that isn’t anywhere in the poem, such as _monomorphization_:
```console
$ cargo run -- monomorphization poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep monomorphization poem.txt`
```
Excellent! We’ve built our own mini version of a classic tool and learned a lot
about how to structure applications. We’ve also learned a bit about file input
and output, lifetimes, testing, and command line parsing.
To round out this project, we’ll briefly demonstrate how to work with
environment variables and how to print to standard error, both of which are
useful when you’re writing command line programs.


The Rust Programming Language › Working with Environment Variables

We’ll improve the `minigrep` binary by adding an extra feature: an option for
case-insensitive searching that the user can turn on via an environment
variable. We could make this feature a command line option and require that
users enter it each time they want it to apply, but by instead making it an
environment variable, we allow our users to set the environment variable once
and have all their searches be case insensitive in that terminal session.


The Rust Programming Language › Working with Environment Variables › Writing a Failing Test for Case-Insensitive Search

We first add a new `search_case_insensitive` function to the `minigrep` library
that will be called when the environment variable has a value. We’ll continue
to follow the TDD process, so the first step is again to write a failing test.
We’ll add a new test for the new `search_case_insensitive` function and rename
our old test from `one_result` to `case_sensitive` to clarify the differences
between the two tests, as shown in Listing 12-20.
Listing 12-20: Adding a new failing test for the case-insensitive function we’re about to add (src/lib.rs)
```rust,ignore,does_not_compile
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
Note that we’ve edited the old test’s `contents` too. We’ve added a new line
with the text `"Duct tape."` using a capital _D_ that shouldn’t match the query
`"duct"` when we’re searching in a case-sensitive manner. Changing the old test
in this way helps ensure that we don’t accidentally break the case-sensitive
search functionality that we’ve already implemented. This test should pass now
and should continue to pass as we work on the case-insensitive search.


The Rust Programming Language › Working with Environment Variables › Writing a Failing Test for Case-Insensitive Search

The new test for the case-_insensitive_ search uses `"rUsT"` as its query. In
the `search_case_insensitive` function we’re about to add, the query `"rUsT"`
should match the line containing `"Rust:"` with a capital _R_ and match the
line `"Trust me."` even though both have different casing from the query. This
is our failing test, and it will fail to compile because we haven’t yet defined
the `search_case_insensitive` function. Feel free to add a skeleton
implementation that always returns an empty vector, similar to the way we did
for the `search` function in Listing 12-16 to see the test compile and fail.


The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function

The `search_case_insensitive` function, shown in Listing 12-21, will be almost
the same as the `search` function. The only difference is that we’ll lowercase
the `query` and each `line` so that whatever the case of the input arguments,
they’ll be the same case when we check whether the line contains the query.
Listing 12-21: Defining the `search_case_insensitive` function to lowercase the query and the line before comparing them (src/lib.rs)
```rust,noplayground
pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}
```
First, we lowercase the `query` string and store it in a new variable with the
same name, shadowing the original `query`. Calling `to_lowercase` on the query
is necessary so that no matter whether the user’s query is `"rust"`, `"RUST"`,
`"Rust"`, or `"rUsT"`, we’ll treat the query as if it were `"rust"` and be
insensitive to the case. While `to_lowercase` will handle basic Unicode, it
won’t be 100 percent accurate. If we were writing a real application, we’d want
to do a bit more work here, but this section is about environment variables,
not Unicode, so we’ll leave it at that here.


The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function

Note that `query` is now a `String` rather than a string slice because calling
`to_lowercase` creates new data rather than referencing existing data. Say the
query is `"rUsT"`, as an example: That string slice doesn’t contain a lowercase
`u` or `t` for us to use, so we have to allocate a new `String` containing
`"rust"`. When we pass `query` as an argument to the `contains` method now, we
need to add an ampersand because the signature of `contains` is defined to take
a string slice.
Next, we add a call to `to_lowercase` on each `line` to lowercase all
characters. Now that we’ve converted `line` and `query` to lowercase, we’ll
find matches no matter what the case of the query is.
Let’s see if this implementation passes the tests:


The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function

```console
$ cargo test
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 1.33s
     Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 2 tests
test tests::case_insensitive ... ok
test tests::case_sensitive ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests minigrep

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

```
Great! They passed. Now let’s call the new `search_case_insensitive` function
from the `run` function. First, we’ll add a configuration option to the `Config`
struct to switch between case-sensitive and case-insensitive search. Adding
this field will cause compiler errors because we aren’t initializing this field
anywhere yet:
Filename: src/main.rs
```rust,ignore,does_not_compile
pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}
```


The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function

We added the `ignore_case` field that holds a Boolean. Next, we need the `run`
function to check the `ignore_case` field’s value and use that to decide
whether to call the `search` function or the `search_case_insensitive`
function, as shown in Listing 12-22. This still won’t compile yet.
Listing 12-22: Calling either `search` or `search_case_insensitive` based on the value in `config.ignore_case` (src/main.rs)
```rust,ignore,does_not_compile
use minigrep::{search, search_case_insensitive};

// --snip--

fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}
```
Finally, we need to check for the environment variable. The functions for
working with environment variables are in the `env` module in the standard
library, which is already in scope at the top of _src/main.rs_. We’ll use the
`var` function from the `env` module to check to see if any value has been set
for an environment variable named `IGNORE_CASE`, as shown in Listing 12-23.
Listing 12-23: Checking for any value in an environment variable named `IGNORE_CASE` (src/main.rs)


The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function

```rust,ignore,noplayground
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();

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}
```
Here, we create a new variable, `ignore_case`. To set its value, we call the
`env::var` function and pass it the name of the `IGNORE_CASE` environment
variable. The `env::var` function returns a `Result` that will be the
successful `Ok` variant that contains the value of the environment variable if
the environment variable is set to any value. It will return the `Err` variant
if the environment variable is not set.
We’re using the `is_ok` method on the `Result` to check whether the environment
variable is set, which means the program should do a case-insensitive search.
If the `IGNORE_CASE` environment variable isn’t set to anything, `is_ok` will
return `false` and the program will perform a case-sensitive search. We don’t
care about the _value_ of the environment variable, just whether it’s set or
unset, so we’re checking `is_ok` rather than using `unwrap`, `expect`, or any
of the other methods we’ve seen on `Result`.
We pass the value in the `ignore_case` variable to the `Config` instance so
that the `run` function can read that value and decide whether to call
`search_case_insensitive` or `search`, as we implemented in Listing 12-22.


The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function

Let’s give it a try! First, we’ll run our program without the environment
variable set and with the query `to`, which should match any line that contains
the word _to_ in all lowercase:
```console
$ cargo run -- to poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep to poem.txt`
Are you nobody, too?
How dreary to be somebody!
```
Looks like that still works! Now let’s run the program with `IGNORE_CASE` set
to `1` but with the same query `to`:
```console
$ IGNORE_CASE=1 cargo run -- to poem.txt
```
If you’re using PowerShell, you will need to set the environment variable and
run the program as separate commands:
```console
PS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt
```
This will make `IGNORE_CASE` persist for the remainder of your shell session.
It can be unset with the `Remove-Item` cmdlet:
```console
PS> Remove-Item Env:IGNORE_CASE
```
We should get lines that contain _to_ that might have uppercase letters:
```console
Are you nobody, too?
How dreary to be somebody!
To tell your name the livelong day
To an admiring bog!
```
Excellent, we also got lines containing _To_! Our `minigrep` program can now do
case-insensitive searching controlled by an environment variable. Now you know
how to manage options set using either command line arguments or environment
variables.


The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function

Some programs allow arguments _and_ environment variables for the same
configuration. In those cases, the programs decide that one or the other takes
precedence. For another exercise on your own, try controlling case sensitivity
through either a command line argument or an environment variable. Decide
whether the command line argument or the environment variable should take
precedence if the program is run with one set to case sensitive and one set to
ignore case.
The `std::env` module contains many more useful features for dealing with
environment variables: Check out its documentation to see what is available.


The Rust Programming Language › Redirecting Errors to Standard Error

At the moment, we’re writing all of our output to the terminal using the
`println!` macro. In most terminals, there are two kinds of output: _standard
output_ (`stdout`) for general information and _standard error_ (`stderr`) for
error messages. This distinction enables users to choose to direct the
successful output of a program to a file but still print error messages to the
screen.
The `println!` macro is only capable of printing to standard output, so we have
to use something else to print to standard error.


The Rust Programming Language › Redirecting Errors to Standard Error › Checking Where Errors Are Written

First, let’s observe how the content printed by `minigrep` is currently being
written to standard output, including any error messages we want to write to
standard error instead. We’ll do that by redirecting the standard output stream
to a file while intentionally causing an error. We won’t redirect the standard
error stream, so any content sent to standard error will continue to display on
the screen.
Command line programs are expected to send error messages to the standard error
stream so that we can still see error messages on the screen even if we
redirect the standard output stream to a file. Our program is not currently
well behaved: We’re about to see that it saves the error message output to a
file instead!
To demonstrate this behavior, we’ll run the program with `>` and the file path,
_output.txt_, that we want to redirect the standard output stream to. We won’t
pass any arguments, which should cause an error:
```console
$ cargo run > output.txt
```
The `>` syntax tells the shell to write the contents of standard output to
_output.txt_ instead of the screen. We didn’t see the error message we were
expecting printed to the screen, so that means it must have ended up in the
file. This is what _output.txt_ contains:
```text
Problem parsing arguments: not enough arguments
```
Yup, our error message is being printed to standard output. It’s much more
useful for error messages like this to be printed to standard error so that
only data from a successful run ends up in the file. We’ll change that.

Redirecting Errors to Standard Error
Checking Where Errors Are Written


The Rust Programming Language › Redirecting Errors to Standard Error › Printing Errors to Standard Error

We’ll use the code in Listing 12-24 to change how error messages are printed.
Because of the refactoring we did earlier in this chapter, all the code that
prints error messages is in one function, `main`. The standard library provides
the `eprintln!` macro that prints to the standard error stream, so let’s change
the two places we were calling `println!` to print errors to use `eprintln!`
instead.
Listing 12-24: Writing error messages to standard error instead of standard output using `eprintln!` (src/main.rs)
```rust,ignore
fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    if let Err(e) = run(config) {
        eprintln!("Application error: {e}");
        process::exit(1);
    }
}
```
Let’s now run the program again in the same way, without any arguments and
redirecting standard output with `>`:
```console
$ cargo run > output.txt
Problem parsing arguments: not enough arguments
```
Now we see the error onscreen and _output.txt_ contains nothing, which is the
behavior we expect of command line programs.
Let’s run the program again with arguments that don’t cause an error but still
redirect standard output to a file, like so:
```console
$ cargo run -- to poem.txt > output.txt
```
We won’t see any output to the terminal, and _output.txt_ will contain our
results:
Filename: output.txt
```text
Are you nobody, too?
How dreary to be somebody!
```
This demonstrates that we’re now using standard output for successful output
and standard error for error output as appropriate.

Redirecting Errors to Standard Error
Printing Errors to Standard Error


The Rust Programming Language › Summary

This chapter recapped some of the major concepts you’ve learned so far and
covered how to perform common I/O operations in Rust. By using command line
arguments, files, environment variables, and the `eprintln!` macro for printing
errors, you’re now prepared to write command line applications. Combined with
the concepts in previous chapters, your code will be well organized, store data
effectively in the appropriate data structures, handle errors nicely, and be
well tested.
Next, we’ll explore some Rust features that were influenced by functional
languages: closures and iterators.


The Rust Programming Language › Functional Language Features: Iterators and Closures

Rust’s design has taken inspiration from many existing languages and
techniques, and one significant influence is _functional programming_.
Programming in a functional style often includes using functions as values by
passing them in arguments, returning them from other functions, assigning them
to variables for later execution, and so forth.
In this chapter, we won’t debate the issue of what functional programming is or
isn’t but will instead discuss some features of Rust that are similar to
features in many languages often referred to as functional.
More specifically, we’ll cover:
- _Closures_, a function-like construct you can store in a variable
- _Iterators_, a way of processing a series of elements
- How to use closures and iterators to improve the I/O project in Chapter 12
- The performance of closures and iterators (spoiler alert: They’re faster than
  you might think!)
We’ve already covered some other Rust features, such as pattern matching and
enums, that are also influenced by the functional style. Because mastering
closures and iterators is an important part of writing fast, idiomatic, Rust
code, we’ll devote this entire chapter to them.


The Rust Programming Language › Closures

Rust’s closures are anonymous functions you can save in a variable or pass as
arguments to other functions. You can create the closure in one place and then
call the closure elsewhere to evaluate it in a different context. Unlike
functions, closures can capture values from the scope in which they’re defined.
We’ll demonstrate how these closure features allow for code reuse and behavior
customization.


The Rust Programming Language › Closures › Capturing the Environment

We’ll first examine how we can use closures to capture values from the
environment they’re defined in for later use. Here’s the scenario: Every so
often, our T-shirt company gives away an exclusive, limited-edition shirt to
someone on our mailing list as a promotion. People on the mailing list can
optionally add their favorite color to their profile. If the person chosen for
a free shirt has their favorite color set, they get that color shirt. If the
person hasn’t specified a favorite color, they get whatever color the company
currently has the most of.
There are many ways to implement this. For this example, we’re going to use an
enum called `ShirtColor` that has the variants `Red` and `Blue` (limiting the
number of colors available for simplicity). We represent the company’s
inventory with an `Inventory` struct that has a field named `shirts` that
contains a `Vec<ShirtColor>` representing the shirt colors currently in stock.
The method `giveaway` defined on `Inventory` gets the optional shirt color
preference of the free-shirt winner, and it returns the shirt color the
person will get. This setup is shown in Listing 13-1.
Listing 13-1: Shirt company giveaway situation (src/main.rs)


The Rust Programming Language › Closures › Capturing the Environment

```rust,noplayground
#[derive(Debug, PartialEq, Copy, Clone)]
enum ShirtColor {
    Red,
    Blue,
}

struct Inventory {
    shirts: Vec<ShirtColor>,
}

impl Inventory {
    fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor {
        user_preference.unwrap_or_else(|| self.most_stocked())
    }

    fn most_stocked(&self) -> ShirtColor {
        let mut num_red = 0;
        let mut num_blue = 0;

        for color in &self.shirts {
            match color {
                ShirtColor::Red => num_red += 1,
                ShirtColor::Blue => num_blue += 1,
            }
        }
        if num_red > num_blue {
            ShirtColor::Red
        } else {
            ShirtColor::Blue
        }
    }
}

fn main() {
    let store = Inventory {
        shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue],
    };

    let user_pref1 = Some(ShirtColor::Red);
    let giveaway1 = store.giveaway(user_pref1);
    println!(
        "The user with preference {:?} gets {:?}",
        user_pref1, giveaway1
    );

    let user_pref2 = None;
    let giveaway2 = store.giveaway(user_pref2);
    println!(
        "The user with preference {:?} gets {:?}",
        user_pref2, giveaway2
    );
}
```
The `store` defined in `main` has two blue shirts and one red shirt remaining
to distribute for this limited-edition promotion. We call the `giveaway` method
for a user with a preference for a red shirt and a user without any preference.


The Rust Programming Language › Closures › Capturing the Environment

Again, this code could be implemented in many ways, and here, to focus on
closures, we’ve stuck to concepts you’ve already learned, except for the body of
the `giveaway` method that uses a closure. In the `giveaway` method, we get the
user preference as a parameter of type `Option<ShirtColor>` and call the
`unwrap_or_else` method on `user_preference`. The `unwrap_or_else` method on
`Option<T>` is defined by the standard library.
It takes one argument: a closure without any arguments that returns a value `T`
(the same type stored in the `Some` variant of the `Option<T>`, in this case
`ShirtColor`). If the `Option<T>` is the `Some` variant, `unwrap_or_else`
returns the value from within the `Some`. If the `Option<T>` is the `None`
variant, `unwrap_or_else` calls the closure and returns the value returned by
the closure.
We specify the closure expression `|| self.most_stocked()` as the argument to
`unwrap_or_else`. This is a closure that takes no parameters itself (if the
closure had parameters, they would appear between the two vertical pipes). The
body of the closure calls `self.most_stocked()`. We’re defining the closure
here, and the implementation of `unwrap_or_else` will evaluate the closure
later if the result is needed.
Running this code prints the following:
```console
$ cargo run
   Compiling shirt-company v0.1.0 (file:///projects/shirt-company)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s
     Running `target/debug/shirt-company`
The user with preference Some(Red) gets Red
The user with preference None gets Blue
```


The Rust Programming Language › Closures › Capturing the Environment

One interesting aspect here is that we’ve passed a closure that calls
`self.most_stocked()` on the current `Inventory` instance. The standard library
didn’t need to know anything about the `Inventory` or `ShirtColor` types we
defined, or the logic we want to use in this scenario. The closure captures an
immutable reference to the `self` `Inventory` instance and passes it with the
code we specify to the `unwrap_or_else` method. Functions, on the other hand,
are not able to capture their environment in this way.


The Rust Programming Language › Closures › Inferring and Annotating Closure Types

There are more differences between functions and closures. Closures don’t
usually require you to annotate the types of the parameters or the return value
like `fn` functions do. Type annotations are required on functions because the
types are part of an explicit interface exposed to your users. Defining this
interface rigidly is important for ensuring that everyone agrees on what types
of values a function uses and returns. Closures, on the other hand, aren’t used
in an exposed interface like this: They’re stored in variables, and they’re
used without naming them and exposing them to users of our library.
Closures are typically short and relevant only within a narrow context rather
than in any arbitrary scenario. Within these limited contexts, the compiler can
infer the types of the parameters and the return type, similar to how it’s able
to infer the types of most variables (there are rare cases where the compiler
needs closure type annotations too).
As with variables, we can add type annotations if we want to increase
explicitness and clarity at the cost of being more verbose than is strictly
necessary. Annotating the types for a closure would look like the definition
shown in Listing 13-2. In this example, we’re defining a closure and storing it
in a variable rather than defining the closure in the spot we pass it as an
argument, as we did in Listing 13-1.
Listing 13-2: Adding optional type annotations of the parameter and return value types in the closure (src/main.rs)
```rust
    let expensive_closure = |num: u32| -> u32 {
        println!("calculating slowly...");
        thread::sleep(Duration::from_secs(2));
        num
    };
```

Closures
Inferring and Annotating Closure Types


The Rust Programming Language › Closures › Inferring and Annotating Closure Types

With type annotations added, the syntax of closures looks more similar to the
syntax of functions. Here, we define a function that adds 1 to its parameter and
a closure that has the same behavior, for comparison. We’ve added some spaces
to line up the relevant parts. This illustrates how closure syntax is similar
to function syntax except for the use of pipes and the amount of syntax that is
optional:
```rust,ignore
fn  add_one_v1   (x: u32) -> u32 { x + 1 }
let add_one_v2 = |x: u32| -> u32 { x + 1 };
let add_one_v3 = |x|             { x + 1 };
let add_one_v4 = |x|               x + 1  ;
```
The first line shows a function definition and the second line shows a fully
annotated closure definition. In the third line, we remove the type annotations
from the closure definition. In the fourth line, we remove the brackets, which
are optional because the closure body has only one expression. These are all
valid definitions that will produce the same behavior when they’re called. The
`add_one_v3` and `add_one_v4` lines require the closures to be evaluated to be
able to compile because the types will be inferred from their usage. This is
similar to `let v = Vec::new();` needing either type annotations or values of
some type to be inserted into the `Vec` for Rust to be able to infer the type.


The Rust Programming Language › Closures › Inferring and Annotating Closure Types

For closure definitions, the compiler will infer one concrete type for each of
their parameters and for their return value. For instance, Listing 13-3 shows
the definition of a short closure that just returns the value it receives as a
parameter. This closure isn’t very useful except for the purposes of this
example. Note that we haven’t added any type annotations to the definition.
Because there are no type annotations, we can call the closure with any type,
which we’ve done here with `String` the first time. If we then try to call
`example_closure` with an integer, we’ll get an error.
Listing 13-3: Attempting to call a closure whose types are inferred with two different types (src/main.rs)
```rust,ignore,does_not_compile
    let example_closure = |x| x;

    let s = example_closure(String::from("hello"));
    let n = example_closure(5);
```
The compiler gives us this error:


The Rust Programming Language › Closures › Inferring and Annotating Closure Types

```console
$ cargo run
   Compiling closure-example v0.1.0 (file:///projects/closure-example)
error[E0308]: mismatched types
 --> src/main.rs:5:29
  |
5 |     let n = example_closure(5);
  |             --------------- ^ expected `String`, found integer
  |             |
  |             arguments to this function are incorrect
  |
note: expected because the closure was earlier called with an argument of type `String`
 --> src/main.rs:4:29
  |
4 |     let s = example_closure(String::from("hello"));
  |             --------------- ^^^^^^^^^^^^^^^^^^^^^ expected because this argument is of type `String`
  |             |
  |             in this closure call
note: closure parameter defined here
 --> src/main.rs:2:28
  |
2 |     let example_closure = |x| x;
  |                            ^
help: try using a conversion method
  |
5 |     let n = example_closure(5.to_string());
  |                              ++++++++++++

For more information about this error, try `rustc --explain E0308`.
error: could not compile `closure-example` (bin "closure-example") due to 1 previous error
```
The first time we call `example_closure` with the `String` value, the compiler
infers the type of `x` and the return type of the closure to be `String`. Those
types are then locked into the closure in `example_closure`, and we get a type
error when we next try to use a different type with the same closure.


The Rust Programming Language › Closures › Capturing References or Moving Ownership

Closures can capture values from their environment in three ways, which
directly map to the three ways a function can take a parameter: borrowing
immutably, borrowing mutably, and taking ownership. The closure will decide
which of these to use based on what the body of the function does with the
captured values.
In Listing 13-4, we define a closure that captures an immutable reference to
the vector named `list` because it only needs an immutable reference to print
the value.
Listing 13-4: Defining and calling a closure that captures an immutable reference (src/main.rs)
```rust
fn main() {
    let list = vec![1, 2, 3];
    println!("Before defining closure: {list:?}");

    let only_borrows = || println!("From closure: {list:?}");

    println!("Before calling closure: {list:?}");
    only_borrows();
    println!("After calling closure: {list:?}");
}
```
This example also illustrates that a variable can bind to a closure definition,
and we can later call the closure by using the variable name and parentheses as
if the variable name were a function name.
Because we can have multiple immutable references to `list` at the same time,
`list` is still accessible from the code before the closure definition, after
the closure definition but before the closure is called, and after the closure
is called. This code compiles, runs, and prints:


The Rust Programming Language › Closures › Capturing References or Moving Ownership

```console
$ cargo run
   Compiling closure-example v0.1.0 (file:///projects/closure-example)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s
     Running `target/debug/closure-example`
Before defining closure: [1, 2, 3]
Before calling closure: [1, 2, 3]
From closure: [1, 2, 3]
After calling closure: [1, 2, 3]
```
Next, in Listing 13-5, we change the closure body so that it adds an element to
the `list` vector. The closure now captures a mutable reference.
Listing 13-5: Defining and calling a closure that captures a mutable reference (src/main.rs)
```rust
fn main() {
    let mut list = vec![1, 2, 3];
    println!("Before defining closure: {list:?}");

    let mut borrows_mutably = || list.push(7);

    borrows_mutably();
    println!("After calling closure: {list:?}");
}
```
This code compiles, runs, and prints:
```console
$ cargo run
   Compiling closure-example v0.1.0 (file:///projects/closure-example)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s
     Running `target/debug/closure-example`
Before defining closure: [1, 2, 3]
After calling closure: [1, 2, 3, 7]
```


The Rust Programming Language › Closures › Capturing References or Moving Ownership

Note that there’s no longer a `println!` between the definition and the call of
the `borrows_mutably` closure: When `borrows_mutably` is defined, it captures a
mutable reference to `list`. We don’t use the closure again after the closure
is called, so the mutable borrow ends. Between the closure definition and the
closure call, an immutable borrow to print isn’t allowed, because no other
borrows are allowed when there’s a mutable borrow. Try adding a `println!`
there to see what error message you get!
If you want to force the closure to take ownership of the values it uses in the
environment even though the body of the closure doesn’t strictly need
ownership, you can use the `move` keyword before the parameter list.
This technique is mostly useful when passing a closure to a new thread to move
the data so that it’s owned by the new thread. We’ll discuss threads and why
you would want to use them in detail in Chapter 16 when we talk about
concurrency, but for now, let’s briefly explore spawning a new thread using a
closure that needs the `move` keyword. Listing 13-6 shows Listing 13-4 modified
to print the vector in a new thread rather than in the main thread.
Listing 13-6: Using `move` to force the closure for the thread to take ownership of `list` (src/main.rs)
```rust
use std::thread;

fn main() {
    let list = vec![1, 2, 3];
    println!("Before defining closure: {list:?}");

    thread::spawn(move || println!("From thread: {list:?}"))
        .join()
        .unwrap();
}
```


The Rust Programming Language › Closures › Capturing References or Moving Ownership

We spawn a new thread, giving the thread a closure to run as an argument. The
closure body prints out the list. In Listing 13-4, the closure only captured
`list` using an immutable reference because that's the least amount of access
to `list` needed to print it. In this example, even though the closure body
still only needs an immutable reference, we need to specify that `list` should
be moved into the closure by putting the `move` keyword at the beginning of the
closure definition. If the main thread performed more operations before calling
`join` on the new thread, the new thread might finish before the rest of the
main thread finishes, or the main thread might finish first. If the main thread
maintained ownership of `list` but ended before the new thread and drops
`list`, the immutable reference in the thread would be invalid. Therefore, the
compiler requires that `list` be moved into the closure given to the new thread
so that the reference will be valid. Try removing the `move` keyword or using
`list` in the main thread after the closure is defined to see what compiler
errors you get!


The Rust Programming Language › Closures › Moving Captured Values Out of Closures

Once a closure has captured a reference or captured ownership of a value from
the environment where the closure is defined (thus affecting what, if anything,
is moved _into_ the closure), the code in the body of the closure defines what
happens to the references or values when the closure is evaluated later (thus
affecting what, if anything, is moved _out of_ the closure).
A closure body can do any of the following: Move a captured value out of the
closure, mutate the captured value, neither move nor mutate the value, or
capture nothing from the environment to begin with.
The way a closure captures and handles values from the environment affects
which traits the closure implements, and traits are how functions and structs
can specify what kinds of closures they can use. Closures will automatically
implement one, two, or all three of these `Fn` traits, in an additive fashion,
depending on how the closure’s body handles the values:
* `FnOnce` applies to closures that can be called once. All closures implement
  at least this trait because all closures can be called. A closure that moves
  captured values out of its body will only implement `FnOnce` and none of the
  other `Fn` traits because it can only be called once.
* `FnMut` applies to closures that don’t move captured values out of their body
  but might mutate the captured values. These closures can be called more than
  once.
* `Fn` applies to closures that don’t move captured values out of their body
  and don’t mutate captured values, as well as closures that capture nothing
  from their environment. These closures can be called more than once without
  mutating their environment, which is important in cases such as calling a closure multiple times concurrently.
Let’s look at the definition of the `unwrap_or_else` method on `Option<T>` that
we used in Listing 13-1:

Closures
Moving Captured Values Out of Closures


The Rust Programming Language › Closures › Moving Captured Values Out of Closures

```rust,ignore
impl<T> Option<T> {
    pub fn unwrap_or_else<F>(self, f: F) -> T
    where
        F: FnOnce() -> T
    {
        match self {
            Some(x) => x,
            None => f(),
        }
    }
}
```
Recall that `T` is the generic type representing the type of the value in the
`Some` variant of an `Option`. That type `T` is also the return type of the
`unwrap_or_else` function: Code that calls `unwrap_or_else` on an
`Option<String>`, for example, will get a `String`.
Next, notice that the `unwrap_or_else` function has the additional generic type
parameter `F`. The `F` type is the type of the parameter named `f`, which is
the closure we provide when calling `unwrap_or_else`.
The trait bound specified on the generic type `F` is `FnOnce() -> T`, which
means `F` must be able to be called once, take no arguments, and return a `T`.
Using `FnOnce` in the trait bound expresses the constraint that
`unwrap_or_else` will not call `f` more than once. In the body of
`unwrap_or_else`, we can see that if the `Option` is `Some`, `f` won’t be
called. If the `Option` is `None`, `f` will be called once. Because all
closures implement `FnOnce`, `unwrap_or_else` accepts all three kinds of
closures and is as flexible as it can be.


The Rust Programming Language › Closures › Moving Captured Values Out of Closures

Note: If what we want to do doesn’t require capturing a value from the
environment, we can use the name of a function rather than a closure where we
need something that implements one of the `Fn` traits. For example, on an
`Option<Vec<T>>` value, we could call `unwrap_or_else(Vec::new)` to get a
new, empty vector if the value is `None`. The compiler automatically
implements whichever of the `Fn` traits is applicable for a function
definition.
Now let’s look at the standard library method `sort_by_key`, defined on slices,
to see how that differs from `unwrap_or_else` and why `sort_by_key` uses
`FnMut` instead of `FnOnce` for the trait bound. The closure gets one argument
in the form of a reference to the current item in the slice being considered,
and it returns a value of type `K` that can be ordered. This function is useful
when you want to sort a slice by a particular attribute of each item. In
Listing 13-7, we have a list of `Rectangle` instances, and we use `sort_by_key`
to order them by their `width` attribute from low to high.
Listing 13-7: Using `sort_by_key` to order rectangles by width (src/main.rs)
```rust
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let mut list = [
        Rectangle { width: 10, height: 1 },
        Rectangle { width: 3, height: 5 },
        Rectangle { width: 7, height: 12 },
    ];

    list.sort_by_key(|r| r.width);
    println!("{list:#?}");
}
```
This code prints:


The Rust Programming Language › Closures › Moving Captured Values Out of Closures

```console
$ cargo run
   Compiling rectangles v0.1.0 (file:///projects/rectangles)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.41s
     Running `target/debug/rectangles`
[
    Rectangle {
        width: 3,
        height: 5,
    },
    Rectangle {
        width: 7,
        height: 12,
    },
    Rectangle {
        width: 10,
        height: 1,
    },
]
```
The reason `sort_by_key` is defined to take an `FnMut` closure is that it calls
the closure multiple times: once for each item in the slice. The closure `|r|
r.width` doesn’t capture, mutate, or move anything out from its environment, so
it meets the trait bound requirements.
In contrast, Listing 13-8 shows an example of a closure that implements just
the `FnOnce` trait, because it moves a value out of the environment. The
compiler won’t let us use this closure with `sort_by_key`.
Listing 13-8: Attempting to use an `FnOnce` closure with `sort_by_key` (src/main.rs)
```rust,ignore,does_not_compile
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let mut list = [
        Rectangle { width: 10, height: 1 },
        Rectangle { width: 3, height: 5 },
        Rectangle { width: 7, height: 12 },
    ];

    let mut sort_operations = vec![];
    let value = String::from("closure called");

    list.sort_by_key(|r| {
        sort_operations.push(value);
        r.width
    });
    println!("{list:#?}");
}
```


The Rust Programming Language › Closures › Moving Captured Values Out of Closures

This is a contrived, convoluted way (that doesn’t work) to try to count the
number of times `sort_by_key` calls the closure when sorting `list`. This code
attempts to do this counting by pushing `value`—a `String` from the closure’s
environment—into the `sort_operations` vector. The closure captures `value` and
then moves `value` out of the closure by transferring ownership of `value` to
the `sort_operations` vector. This closure can be called once; trying to call
it a second time wouldn’t work, because `value` would no longer be in the
environment to be pushed into `sort_operations` again! Therefore, this closure
only implements `FnOnce`. When we try to compile this code, we get this error
that `value` can’t be moved out of the closure because the closure must
implement `FnMut`:


The Rust Programming Language › Closures › Moving Captured Values Out of Closures

```console
$ cargo run
   Compiling rectangles v0.1.0 (file:///projects/rectangles)
error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure
  --> src/main.rs:18:30
   |
15 |     let value = String::from("closure called");
   |         -----   ------------------------------ move occurs because `value` has type `String`, which does not implement the `Copy` trait
   |         |
   |         captured outer variable
16 |
17 |     list.sort_by_key(|r| {
   |                      --- captured by this `FnMut` closure
18 |         sort_operations.push(value);
   |                              ^^^^^ `value` is moved here
   |
help: `Fn` and `FnMut` closures require captured values to be able to be consumed multiple times, but `FnOnce` closures may consume them only once
  --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/alloc/src/slice.rs:249:11
help: consider cloning the value if the performance cost is acceptable
   |
18 |         sort_operations.push(value.clone());
   |                                   ++++++++

For more information about this error, try `rustc --explain E0507`.
error: could not compile `rectangles` (bin "rectangles") due to 1 previous error
```


The Rust Programming Language › Closures › Moving Captured Values Out of Closures

The error points to the line in the closure body that moves `value` out of the
environment. To fix this, we need to change the closure body so that it doesn’t
move values out of the environment. Keeping a counter in the environment and
incrementing its value in the closure body is a more straightforward way to
count the number of times the closure is called. The closure in Listing 13-9
works with `sort_by_key` because it is only capturing a mutable reference to the
`num_sort_operations` counter and can therefore be called more than once.
Listing 13-9: Using an `FnMut` closure with `sort_by_key` is allowed. (src/main.rs)
```rust
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let mut list = [
        Rectangle { width: 10, height: 1 },
        Rectangle { width: 3, height: 5 },
        Rectangle { width: 7, height: 12 },
    ];

    let mut num_sort_operations = 0;
    list.sort_by_key(|r| {
        num_sort_operations += 1;
        r.width
    });
    println!("{list:#?}, sorted in {num_sort_operations} operations");
}
```
The `Fn` traits are important when defining or using functions or types that
make use of closures. In the next section, we’ll discuss iterators. Many
iterator methods take closure arguments, so keep these closure details in mind
as we continue!


The Rust Programming Language › Processing a Series of Items with Iterators

The iterator pattern allows you to perform some task on a sequence of items in
turn. An iterator is responsible for the logic of iterating over each item and
determining when the sequence has finished. When you use iterators, you don’t
have to reimplement that logic yourself.
In Rust, iterators are _lazy_, meaning they have no effect until you call
methods that consume the iterator to use it up. For example, the code in
Listing 13-10 creates an iterator over the items in the vector `v1` by calling
the `iter` method defined on `Vec<T>`. This code by itself doesn’t do anything
useful.
Listing 13-10: Creating an iterator (src/main.rs)
```rust
    let v1 = vec![1, 2, 3];

    let v1_iter = v1.iter();
```
The iterator is stored in the `v1_iter` variable. Once we’ve created an
iterator, we can use it in a variety of ways. In Listing 3-5, we iterated over
an array using a `for` loop to execute some code on each of its items. Under
the hood, this implicitly created and then consumed an iterator, but we glossed
over how exactly that works until now.
In the example in Listing 13-11, we separate the creation of the iterator from
the use of the iterator in the `for` loop. When the `for` loop is called using
the iterator in `v1_iter`, each element in the iterator is used in one
iteration of the loop, which prints out each value.
Listing 13-11: Using an iterator in a `for` loop (src/main.rs)
```rust
    let v1 = vec![1, 2, 3];

    let v1_iter = v1.iter();

    for val in v1_iter {
        println!("Got: {val}");
    }
```


The Rust Programming Language › Processing a Series of Items with Iterators

In languages that don’t have iterators provided by their standard libraries,
you would likely write this same functionality by starting a variable at index
0, using that variable to index into the vector to get a value, and
incrementing the variable value in a loop until it reached the total number of
items in the vector.
Iterators handle all of that logic for you, cutting down on repetitive code you
could potentially mess up. Iterators give you more flexibility to use the same
logic with many different kinds of sequences, not just data structures you can
index into, like vectors. Let’s examine how iterators do that.


The Rust Programming Language › Processing a Series of Items with Iterators › The `Iterator` Trait and the `next` Method

All iterators implement a trait named `Iterator` that is defined in the
standard library. The definition of the trait looks like this:
```rust
pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;

    // methods with default implementations elided
}
```
Notice that this definition uses some new syntax: `type Item` and `Self::Item`,
which are defining an associated type with this trait. We’ll talk about
associated types in depth in Chapter 20. For now, all you need to know is that
this code says implementing the `Iterator` trait requires that you also define
an `Item` type, and this `Item` type is used in the return type of the `next`
method. In other words, the `Item` type will be the type returned from the
iterator.
The `Iterator` trait only requires implementors to define one method: the
`next` method, which returns one item of the iterator at a time, wrapped in
`Some`, and, when iteration is over, returns `None`.
We can call the `next` method on iterators directly; Listing 13-12 demonstrates
what values are returned from repeated calls to `next` on the iterator created
from the vector.
Listing 13-12: Calling the `next` method on an iterator (src/lib.rs)
```rust,noplayground
    #[test]
    fn iterator_demonstration() {
        let v1 = vec![1, 2, 3];

        let mut v1_iter = v1.iter();

        assert_eq!(v1_iter.next(), Some(&1));
        assert_eq!(v1_iter.next(), Some(&2));
        assert_eq!(v1_iter.next(), Some(&3));
        assert_eq!(v1_iter.next(), None);
    }
```


The Rust Programming Language › Processing a Series of Items with Iterators › The `Iterator` Trait and the `next` Method

Note that we needed to make `v1_iter` mutable: Calling the `next` method on an
iterator changes internal state that the iterator uses to keep track of where
it is in the sequence. In other words, this code _consumes_, or uses up, the
iterator. Each call to `next` eats up an item from the iterator. We didn’t need
to make `v1_iter` mutable when we used a `for` loop, because the loop took
ownership of `v1_iter` and made it mutable behind the scenes.
Also note that the values we get from the calls to `next` are immutable
references to the values in the vector. The `iter` method produces an iterator
over immutable references. If we want to create an iterator that takes
ownership of `v1` and returns owned values, we can call `into_iter` instead of
`iter`. Similarly, if we want to iterate over mutable references, we can call
`iter_mut` instead of `iter`.


The Rust Programming Language › Processing a Series of Items with Iterators › Methods That Consume the Iterator

The `Iterator` trait has a number of different methods with default
implementations provided by the standard library; you can find out about these
methods by looking in the standard library API documentation for the `Iterator`
trait. Some of these methods call the `next` method in their definition, which
is why you’re required to implement the `next` method when implementing the
`Iterator` trait.
Methods that call `next` are called _consuming adapters_ because calling them
uses up the iterator. One example is the `sum` method, which takes ownership of
the iterator and iterates through the items by repeatedly calling `next`, thus
consuming the iterator. As it iterates through, it adds each item to a running
total and returns the total when iteration is complete. Listing 13-13 has a
test illustrating a use of the `sum` method.
Listing 13-13: Calling the `sum` method to get the total of all items in the iterator (src/lib.rs)
```rust,noplayground
    #[test]
    fn iterator_sum() {
        let v1 = vec![1, 2, 3];

        let v1_iter = v1.iter();

        let total: i32 = v1_iter.sum();

        assert_eq!(total, 6);
    }
```
We aren’t allowed to use `v1_iter` after the call to `sum`, because `sum` takes
ownership of the iterator we call it on.


The Rust Programming Language › Processing a Series of Items with Iterators › Methods That Produce Other Iterators

_Iterator adapters_ are methods defined on the `Iterator` trait that don’t
consume the iterator. Instead, they produce different iterators by changing
some aspect of the original iterator.
Listing 13-14 shows an example of calling the iterator adapter method `map`,
which takes a closure to call on each item as the items are iterated through.
The `map` method returns a new iterator that produces the modified items. The
closure here creates a new iterator in which each item from the vector will be
incremented by 1.
Listing 13-14: Calling the iterator adapter `map` to create a new iterator (src/main.rs)
```rust,not_desired_behavior
    let v1: Vec<i32> = vec![1, 2, 3];

    v1.iter().map(|x| x + 1);
```
However, this code produces a warning:
```console
$ cargo run
   Compiling iterators v0.1.0 (file:///projects/iterators)
warning: unused `Map` that must be used
 --> src/main.rs:4:5
  |
4 |     v1.iter().map(|x| x + 1);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: iterators are lazy and do nothing unless consumed
  = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
help: use `let _ = ...` to ignore the resulting value
  |
4 |     let _ = v1.iter().map(|x| x + 1);
  |     +++++++

warning: `iterators` (bin "iterators") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.47s
     Running `target/debug/iterators`
```


The Rust Programming Language › Processing a Series of Items with Iterators › Methods That Produce Other Iterators

The code in Listing 13-14 doesn’t do anything; the closure we’ve specified
never gets called. The warning reminds us why: Iterator adapters are lazy, and
we need to consume the iterator here.
To fix this warning and consume the iterator, we’ll use the `collect` method,
which we used with `env::args` in Listing 12-1. This method consumes the
iterator and collects the resultant values into a collection data type.
In Listing 13-15, we collect the results of iterating over the iterator that’s
returned from the call to `map` into a vector. This vector will end up
containing each item from the original vector, incremented by 1.
Listing 13-15: Calling the `map` method to create a new iterator, and then calling the `collect` method to consume the new iterator and create a vector (src/main.rs)
```rust
    let v1: Vec<i32> = vec![1, 2, 3];

    let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();

    assert_eq!(v2, vec![2, 3, 4]);
```
Because `map` takes a closure, we can specify any operation we want to perform
on each item. This is a great example of how closures let you customize some
behavior while reusing the iteration behavior that the `Iterator` trait
provides.
You can chain multiple calls to iterator adapters to perform complex actions in
a readable way. But because all iterators are lazy, you have to call one of the
consuming adapter methods to get results from calls to iterator adapters.


The Rust Programming Language › Processing a Series of Items with Iterators › Closures That Capture Their Environment

Many iterator adapters take closures as arguments, and commonly the closures
we’ll specify as arguments to iterator adapters will be closures that capture
their environment.
For this example, we’ll use the `filter` method that takes a closure. The
closure gets an item from the iterator and returns a `bool`. If the closure
returns `true`, the value will be included in the iterator produced by
`filter`. If the closure returns `false`, the value won’t be included.
In Listing 13-16, we use `filter` with a closure that captures the `shoe_size`
variable from its environment to iterate over a collection of `Shoe` struct
instances. It will return only shoes that are the specified size.
Listing 13-16: Using the `filter` method with a closure that captures `shoe_size` (src/lib.rs)


The Rust Programming Language › Processing a Series of Items with Iterators › Closures That Capture Their Environment

```rust,noplayground
#[derive(PartialEq, Debug)]
struct Shoe {
    size: u32,
    style: String,
}

fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
    shoes.into_iter().filter(|s| s.size == shoe_size).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn filters_by_size() {
        let shoes = vec![
            Shoe {
                size: 10,
                style: String::from("sneaker"),
            },
            Shoe {
                size: 13,
                style: String::from("sandal"),
            },
            Shoe {
                size: 10,
                style: String::from("boot"),
            },
        ];

        let in_my_size = shoes_in_size(shoes, 10);

        assert_eq!(
            in_my_size,
            vec![
                Shoe {
                    size: 10,
                    style: String::from("sneaker")
                },
                Shoe {
                    size: 10,
                    style: String::from("boot")
                },
            ]
        );
    }
}
```
The `shoes_in_size` function takes ownership of a vector of shoes and a shoe
size as parameters. It returns a vector containing only shoes of the specified
size.
In the body of `shoes_in_size`, we call `into_iter` to create an iterator that
takes ownership of the vector. Then, we call `filter` to adapt that iterator
into a new iterator that only contains elements for which the closure returns
`true`.
The closure captures the `shoe_size` parameter from the environment and
compares the value with each shoe’s size, keeping only shoes of the size
specified. Finally, calling `collect` gathers the values returned by the
adapted iterator into a vector that’s returned by the function.


The Rust Programming Language › Processing a Series of Items with Iterators › Closures That Capture Their Environment

The test shows that when we call `shoes_in_size`, we get back only shoes that
have the same size as the value we specified.


The Rust Programming Language › Improving Our I/O Project

With this new knowledge about iterators, we can improve the I/O project in
Chapter 12 by using iterators to make places in the code clearer and more
concise. Let’s look at how iterators can improve our implementation of the
`Config::build` function and the `search` function.


The Rust Programming Language › Improving Our I/O Project › Removing a `clone` Using an Iterator

In Listing 12-6, we added code that took a slice of `String` values and created
an instance of the `Config` struct by indexing into the slice and cloning the
values, allowing the `Config` struct to own those values. In Listing 13-17,
we’ve reproduced the implementation of the `Config::build` function as it was
in Listing 12-23.
Listing 13-17: Reproduction of the `Config::build` function from Listing 12-23 (src/main.rs)
```rust,ignore
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();

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}
```
At the time, we said not to worry about the inefficient `clone` calls because
we would remove them in the future. Well, that time is now!
We needed `clone` here because we have a slice with `String` elements in the
parameter `args`, but the `build` function doesn’t own `args`. To return
ownership of a `Config` instance, we had to clone the values from the `query`
and `file_path` fields of `Config` so that the `Config` instance can own its
values.
With our new knowledge about iterators, we can change the `build` function to
take ownership of an iterator as its argument instead of borrowing a slice.
We’ll use the iterator functionality instead of the code that checks the length
of the slice and indexes into specific locations. This will clarify what the
`Config::build` function is doing because the iterator will access the values.

Improving Our I/O Project
Removing a `clone` Using an Iterator


The Rust Programming Language › Improving Our I/O Project › Removing a `clone` Using an Iterator › Using the Returned Iterator Directly

Once `Config::build` takes ownership of the iterator and stops using indexing
operations that borrow, we can move the `String` values from the iterator into
`Config` rather than calling `clone` and making a new allocation.
Open your I/O project’s _src/main.rs_ file, which should look like this:
Filename: src/main.rs
```rust,ignore
fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    // --snip--
}
```
We’ll first change the start of the `main` function that we had in Listing
12-24 to the code in Listing 13-18, which this time uses an iterator. This
won’t compile until we update `Config::build` as well.
Listing 13-18: Passing the return value of `env::args` to `Config::build` (src/main.rs)
```rust,ignore,does_not_compile
fn main() {
    let config = Config::build(env::args()).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    // --snip--
}
```
The `env::args` function returns an iterator! Rather than collecting the
iterator values into a vector and then passing a slice to `Config::build`, now
we’re passing ownership of the iterator returned from `env::args` to
`Config::build` directly.
Next, we need to update the definition of `Config::build`. Let’s change the
signature of `Config::build` to look like Listing 13-19. This still won’t
compile, because we need to update the function body.

Improving Our I/O Project
Removing a `clone` Using an Iterator
Using the Returned Iterator Directly


The Rust Programming Language › Improving Our I/O Project › Removing a `clone` Using an Iterator › Using `Iterator` Trait Methods

Listing 13-19: Updating the signature of `Config::build` to expect an iterator (src/main.rs)
```rust,ignore,does_not_compile
impl Config {
    fn build(
        mut args: impl Iterator<Item = String>,
    ) -> Result<Config, &'static str> {
        // --snip--
```
The standard library documentation for the `env::args` function shows that the
type of the iterator it returns is `std::env::Args`, and that type implements
the `Iterator` trait and returns `String` values.
We’ve updated the signature of the `Config::build` function so that the
parameter `args` has a generic type with the trait bounds `impl Iterator<Item =
String>` instead of `&[String]`. This usage of the `impl Trait` syntax we
discussed in the “Using Traits as Parameters”
section of Chapter 10 means that `args` can be any type that implements the
`Iterator` trait and returns `String` items.
Because we’re taking ownership of `args` and we’ll be mutating `args` by
iterating over it, we can add the `mut` keyword into the specification of the
`args` parameter to make it mutable.
Next, we’ll fix the body of `Config::build`. Because `args` implements the
`Iterator` trait, we know we can call the `next` method on it! Listing 13-20
updates the code from Listing 12-23 to use the `next` method.
Listing 13-20: Changing the body of `Config::build` to use iterator methods (src/main.rs)

Improving Our I/O Project
Removing a `clone` Using an Iterator
Using `Iterator` Trait Methods


The Rust Programming Language › Improving Our I/O Project › Removing a `clone` Using an Iterator › Using `Iterator` Trait Methods

```rust,ignore,noplayground
impl Config {
    fn build(
        mut args: impl Iterator<Item = String>,
    ) -> Result<Config, &'static str> {
        args.next();

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string"),
        };

        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a file path"),
        };

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}
```
Remember that the first value in the return value of `env::args` is the name of
the program. We want to ignore that and get to the next value, so first we call
`next` and do nothing with the return value. Then, we call `next` to get the
value we want to put in the `query` field of `Config`. If `next` returns
`Some`, we use a `match` to extract the value. If it returns `None`, it means
not enough arguments were given, and we return early with an `Err` value. We do
the same thing for the `file_path` value.


The Rust Programming Language › Improving Our I/O Project › Clarifying Code with Iterator Adapters

We can also take advantage of iterators in the `search` function in our I/O
project, which is reproduced here in Listing 13-21 as it was in Listing 12-19.
Listing 13-21: The implementation of the `search` function from Listing 12-19 (src/lib.rs)
```rust,ignore
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}
```
We can write this code in a more concise way using iterator adapter methods.
Doing so also lets us avoid having a mutable intermediate `results` vector. The
functional programming style prefers to minimize the amount of mutable state to
make code clearer. Removing the mutable state might enable a future enhancement
to make searching happen in parallel because we wouldn’t have to manage
concurrent access to the `results` vector. Listing 13-22 shows this change.
Listing 13-22: Using iterator adapter methods in the implementation of the `search` function (src/lib.rs)
```rust,ignore
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
        .lines()
        .filter(|line| line.contains(query))
        .collect()
}
```

Improving Our I/O Project
Clarifying Code with Iterator Adapters


The Rust Programming Language › Improving Our I/O Project › Clarifying Code with Iterator Adapters

Recall that the purpose of the `search` function is to return all lines in
`contents` that contain the `query`. Similar to the `filter` example in Listing
13-16, this code uses the `filter` adapter to keep only the lines for which
`line.contains(query)` returns `true`. We then collect the matching lines into
another vector with `collect`. Much simpler! Feel free to make the same change
to use iterator methods in the `search_case_insensitive` function as well.
For a further improvement, return an iterator from the `search` function by
removing the call to `collect` and changing the return type to `impl
Iterator<Item = &'a str>` so that the function becomes an iterator adapter.
Note that you’ll also need to update the tests! Search through a large file
using your `minigrep` tool before and after making this change to observe the
difference in behavior. Before this change, the program won’t print any results
until it has collected all of the results, but after the change, the results
will be printed as each matching line is found because the `for` loop in the
`run` function is able to take advantage of the laziness of the iterator.


The Rust Programming Language › Improving Our I/O Project › Choosing Between Loops and Iterators

The next logical question is which style you should choose in your own code and
why: the original implementation in Listing 13-21 or the version using
iterators in Listing 13-22 (assuming we’re collecting all the results before
returning them rather than returning the iterator). Most Rust programmers
prefer to use the iterator style. It’s a bit tougher to get the hang of at
first, but once you get a feel for the various iterator adapters and what they
do, iterators can be easier to understand. Instead of fiddling with the various
bits of looping and building new vectors, the code focuses on the high-level
objective of the loop. This abstracts away some of the commonplace code so that
it’s easier to see the concepts that are unique to this code, such as the
filtering condition each element in the iterator must pass.
But are the two implementations truly equivalent? The intuitive assumption
might be that the lower-level loop will be faster. Let’s talk about performance.

Improving Our I/O Project
Choosing Between Loops and Iterators


The Rust Programming Language › Performance in Loops vs. Iterators

To determine whether to use loops or iterators, you need to know which
implementation is faster: the version of the `search` function with an explicit
`for` loop or the version with iterators.
We ran a benchmark by loading the entire contents of _The Adventures of
Sherlock Holmes_ by Sir Arthur Conan Doyle into a `String` and looking for the
word _the_ in the contents. Here are the results of the benchmark on the
version of `search` using the `for` loop and the version using iterators:
```text
test bench_search_for  ... bench:  19,620,300 ns/iter (+/- 915,700)
test bench_search_iter ... bench:  19,234,900 ns/iter (+/- 657,200)
```
The two implementations have similar performance! We won’t explain the
benchmark code here because the point is not to prove that the two versions
are equivalent but to get a general sense of how these two implementations
compare performance-wise.
For a more comprehensive benchmark, you should check using various texts of
various sizes as the `contents`, different words and words of different lengths
as the `query`, and all kinds of other variations. The point is this:
Iterators, although a high-level abstraction, get compiled down to roughly the
same code as if you’d written the lower-level code yourself. Iterators are one
of Rust’s _zero-cost abstractions_, by which we mean that using the abstraction
imposes no additional runtime overhead. This is analogous to how Bjarne
Stroustrup, the original designer and implementor of C++, defines
zero-overhead in his 2012 ETAPS keynote presentation “Foundations of C++”:


The Rust Programming Language › Performance in Loops vs. Iterators

In general, C++ implementations obey the zero-overhead principle: What you
don’t use, you don’t pay for. And further: What you do use, you couldn’t hand
code any better.
In many cases, Rust code using iterators compiles to the same assembly you’d
write by hand. Optimizations such as loop unrolling and eliminating bounds
checking on array access apply and make the resultant code extremely efficient.
Now that you know this, you can use iterators and closures without fear! They
make code seem like it’s higher level but don’t impose a runtime performance
penalty for doing so.


The Rust Programming Language › Summary

Closures and iterators are Rust features inspired by functional programming
language ideas. They contribute to Rust’s capability to clearly express
high-level ideas at low-level performance. The implementations of closures and
iterators are such that runtime performance is not affected. This is part of
Rust’s goal to strive to provide zero-cost abstractions.
Now that we’ve improved the expressiveness of our I/O project, let’s look at
some more features of `cargo` that will help us share the project with the
world.


The Rust Programming Language › More About Cargo and Crates.io

So far, we’ve used only the most basic features of Cargo to build, run, and
test our code, but it can do a lot more. In this chapter, we’ll discuss some of
its other, more advanced features to show you how to do the following:
- Customize your build through release profiles.
- Publish libraries on crates.io.
- Organize large projects with workspaces.
- Install binaries from crates.io.
- Extend Cargo using custom commands.
Cargo can do even more than the functionality we cover in this chapter, so for
a full explanation of all its features, see its documentation.