The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › The `?` Operator Shortcut

Listing 9-7: A function that returns errors to the calling code using the `?` operator (src/main.rs)
```rust
use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut username_file = File::open("hello.txt")?;
    let mut username = String::new();
    username_file.read_to_string(&mut username)?;
    Ok(username)
}
```
The `?` placed after a `Result` value is defined to work in almost the same way
as the `match` expressions that we defined to handle the `Result` values in
Listing 9-6. If the value of the `Result` is an `Ok`, the value inside the `Ok`
will get returned from this expression, and the program will continue. If the
value is an `Err`, the `Err` will be returned from the whole function as if we
had used the `return` keyword so that the error value gets propagated to the
calling code.
There is a difference between what the `match` expression from Listing 9-6 does
and what the `?` operator does: Error values that have the `?` operator called
on them go through the `from` function, defined in the `From` trait in the
standard library, which is used to convert values from one type into another.
When the `?` operator calls the `from` function, the error type received is
converted into the error type defined in the return type of the current
function. This is useful when a function returns one error type to represent
all the ways a function might fail, even if parts might fail for many different
reasons.


The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › The `?` Operator Shortcut

For example, we could change the `read_username_from_file` function in Listing
9-7 to return a custom error type named `OurError` that we define. If we also
define `impl From<io::Error> for OurError` to construct an instance of
`OurError` from an `io::Error`, then the `?` operator calls in the body of
`read_username_from_file` will call `from` and convert the error types without
needing to add any more code to the function.
In the context of Listing 9-7, the `?` at the end of the `File::open` call will
return the value inside an `Ok` to the variable `username_file`. If an error
occurs, the `?` operator will return early out of the whole function and give
any `Err` value to the calling code. The same thing applies to the `?` at the
end of the `read_to_string` call.
The `?` operator eliminates a lot of boilerplate and makes this function’s
implementation simpler. We could even shorten this code further by chaining
method calls immediately after the `?`, as shown in Listing 9-8.
Listing 9-8: Chaining method calls after the `?` operator (src/main.rs)
```rust
use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut username = String::new();

    File::open("hello.txt")?.read_to_string(&mut username)?;

    Ok(username)
}
```

Recoverable Errors with `Result`
Propagating Errors
The `?` Operator Shortcut


The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator

We’ve moved the creation of the new `String` in `username` to the beginning of
the function; that part hasn’t changed. Instead of creating a variable
`username_file`, we’ve chained the call to `read_to_string` directly onto the
result of `File::open("hello.txt")?`. We still have a `?` at the end of the
`read_to_string` call, and we still return an `Ok` value containing `username`
when both `File::open` and `read_to_string` succeed rather than returning
errors. The functionality is again the same as in Listing 9-6 and Listing 9-7;
this is just a different, more ergonomic way to write it.
Listing 9-9 shows a way to make this even shorter using `fs::read_to_string`.
Listing 9-9: Using `fs::read_to_string` instead of opening and then reading the file (src/main.rs)
```rust
use std::fs;
use std::io;

fn read_username_from_file() -> Result<String, io::Error> {
    fs::read_to_string("hello.txt")
}
```
Reading a file into a string is a fairly common operation, so the standard
library provides the convenient `fs::read_to_string` function that opens the
file, creates a new `String`, reads the contents of the file, puts the contents
into that `String`, and returns it. Of course, using `fs::read_to_string`
doesn’t give us the opportunity to explain all the error handling, so we did it
the longer way first.

Recoverable Errors with `Result`
Propagating Errors
Where to Use the `?` Operator


The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator

The `?` operator can only be used in functions whose return type is compatible
with the value the `?` is used on. This is because the `?` operator is defined
to perform an early return of a value out of the function, in the same manner
as the `match` expression we defined in Listing 9-6. In Listing 9-6, the
`match` was using a `Result` value, and the early return arm returned an
`Err(e)` value. The return type of the function has to be a `Result` so that
it’s compatible with this `return`.
In Listing 9-10, let’s look at the error we’ll get if we use the `?` operator
in a `main` function with a return type that is incompatible with the type of
the value we use `?` on.
Listing 9-10: Attempting to use the `?` in the `main` function that returns `()` won’t compile. (src/main.rs)
```rust,ignore,does_not_compile
use std::fs::File;

fn main() {
    let greeting_file = File::open("hello.txt")?;
}
```
This code opens a file, which might fail. The `?` operator follows the `Result`
value returned by `File::open`, but this `main` function has the return type of
`()`, not `Result`. When we compile this code, we get the following error
message:


The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator

```console
$ cargo run
   Compiling error-handling v0.1.0 (file:///projects/error-handling)
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
 --> src/main.rs:4:48
  |
3 | fn main() {
  | --------- this function should return `Result` or `Option` to accept `?`
4 |     let greeting_file = File::open("hello.txt")?;
  |                                                ^ cannot use the `?` operator in a function that returns `()`
  |
help: consider adding return type
  |
3 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
4 |     let greeting_file = File::open("hello.txt")?;
5 +     Ok(())
  |

For more information about this error, try `rustc --explain E0277`.
error: could not compile `error-handling` (bin "error-handling") due to 1 previous error
```
This error points out that we’re only allowed to use the `?` operator in a
function that returns `Result`, `Option`, or another type that implements
`FromResidual`.
To fix the error, you have two choices. One choice is to change the return type
of your function to be compatible with the value you’re using the `?` operator
on as long as you have no restrictions preventing that. The other choice is to
use a `match` or one of the `Result<T, E>` methods to handle the `Result<T, E>`
in whatever way is appropriate.


The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator

The error message also mentioned that `?` can be used with `Option<T>` values
as well. As with using `?` on `Result`, you can only use `?` on `Option` in a
function that returns an `Option`. The behavior of the `?` operator when called
on an `Option<T>` is similar to its behavior when called on a `Result<T, E>`:
If the value is `None`, the `None` will be returned early from the function at
that point. If the value is `Some`, the value inside the `Some` is the
resultant value of the expression, and the function continues. Listing 9-11 has
an example of a function that finds the last character of the first line in the
given text.
Listing 9-11
```rust
fn last_char_of_first_line(text: &str) -> Option<char> {
    text.lines().next()?.chars().last()
}
```
This function returns `Option<char>` because it’s possible that there is a
character there, but it’s also possible that there isn’t. This code takes the
`text` string slice argument and calls the `lines` method on it, which returns
an iterator over the lines in the string. Because this function wants to
examine the first line, it calls `next` on the iterator to get the first value
from the iterator. If `text` is the empty string, this call to `next` will
return `None`, in which case we use `?` to stop and return `None` from
`last_char_of_first_line`. If `text` is not the empty string, `next` will
return a `Some` value containing a string slice of the first line in `text`.


The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator

The `?` extracts the string slice, and we can call `chars` on that string slice
to get an iterator of its characters. We’re interested in the last character in
this first line, so we call `last` to return the last item in the iterator.
This is an `Option` because it’s possible that the first line is the empty
string; for example, if `text` starts with a blank line but has characters on
other lines, as in `"\nhi"`. However, if there is a last character on the first
line, it will be returned in the `Some` variant. The `?` operator in the middle
gives us a concise way to express this logic, allowing us to implement the
function in one line. If we couldn’t use the `?` operator on `Option`, we’d
have to implement this logic using more method calls or a `match` expression.
Note that you can use the `?` operator on a `Result` in a function that returns
`Result`, and you can use the `?` operator on an `Option` in a function that
returns `Option`, but you can’t mix and match. The `?` operator won’t
automatically convert a `Result` to an `Option` or vice versa; in those cases,
you can use methods like the `ok` method on `Result` or the `ok_or` method on
`Option` to do the conversion explicitly.
So far, all the `main` functions we’ve used return `()`. The `main` function is
special because it’s the entry point and exit point of an executable program,
and there are restrictions on what its return type can be for the program to
behave as expected.


The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator

Luckily, `main` can also return a `Result<(), E>`. Listing 9-12 has the code
from Listing 9-10, but we’ve changed the return type of `main` to be
`Result<(), Box<dyn Error>>` and added a return value `Ok(())` to the end. This
code will now compile.
Listing 9-12 (src/main.rs)
```rust,ignore
use std::error::Error;
use std::fs::File;

fn main() -> Result<(), Box<dyn Error>> {
    let greeting_file = File::open("hello.txt")?;

    Ok(())
}
```
The `Box<dyn Error>` type is a trait object, which we’ll talk about in “Using
Trait Objects to Abstract over Shared Behavior”
in Chapter 18. For now, you can read `Box<dyn Error>` to mean “any kind of
error.” Using `?` on a `Result` value in a `main` function with the error type
`Box<dyn Error>` is allowed because it allows any `Err` value to be returned
early. Even though the body of this `main` function will only ever return
errors of type `std::io::Error`, by specifying `Box<dyn Error>`, this signature
will continue to be correct even if more code that returns other errors is
added to the body of `main`.
When a `main` function returns a `Result<(), E>`, the executable will exit with
a value of `0` if `main` returns `Ok(())` and will exit with a nonzero value if
`main` returns an `Err` value. Executables written in C return integers when
they exit: Programs that exit successfully return the integer `0`, and programs
that error return some integer other than `0`. Rust also returns integers from
executables to be compatible with this convention.


The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator

The `main` function may return any types that implement the
`std::process::Termination` trait, which contains
a function `report` that returns an `ExitCode`. Consult the standard library
documentation for more information on implementing the `Termination` trait for
your own types.
Now that we’ve discussed the details of calling `panic!` or returning `Result`,
let’s return to the topic of how to decide which is appropriate to use in which
cases.


The Rust Programming Language › To `panic!` or Not to `panic!`

So, how do you decide when you should call `panic!` and when you should return
`Result`? When code panics, there’s no way to recover. You could call `panic!`
for any error situation, whether there’s a possible way to recover or not, but
then you’re making the decision that a situation is unrecoverable on behalf of
the calling code. When you choose to return a `Result` value, you give the
calling code options. The calling code could choose to attempt to recover in a
way that’s appropriate for its situation, or it could decide that an `Err`
value in this case is unrecoverable, so it can call `panic!` and turn your
recoverable error into an unrecoverable one. Therefore, returning `Result` is a
good default choice when you’re defining a function that might fail.
In situations such as examples, prototype code, and tests, it’s more
appropriate to write code that panics instead of returning a `Result`. Let’s
explore why, then discuss situations in which the compiler can’t tell that
failure is impossible, but you as a human can. The chapter will conclude with
some general guidelines on how to decide whether to panic in library code.


The Rust Programming Language › To `panic!` or Not to `panic!` › Examples, Prototype Code, and Tests

When you’re writing an example to illustrate some concept, also including
robust error-handling code can make the example less clear. In examples, it’s
understood that a call to a method like `unwrap` that could panic is meant as a
placeholder for the way you’d want your application to handle errors, which can
differ based on what the rest of your code is doing.
Similarly, the `unwrap` and `expect` methods are very handy when you’re
prototyping and you’re not yet ready to decide how to handle errors. They leave
clear markers in your code for when you’re ready to make your program more
robust.
If a method call fails in a test, you’d want the whole test to fail, even if
that method isn’t the functionality under test. Because `panic!` is how a test
is marked as a failure, calling `unwrap` or `expect` is exactly what should
happen.

To `panic!` or Not to `panic!`
Examples, Prototype Code, and Tests


The Rust Programming Language › To `panic!` or Not to `panic!` › When You Have More Information Than the Compiler

It would also be appropriate to call `expect` when you have some other logic
that ensures that the `Result` will have an `Ok` value, but the logic isn’t
something the compiler understands. You’ll still have a `Result` value that you
need to handle: Whatever operation you’re calling still has the possibility of
failing in general, even though it’s logically impossible in your particular
situation. If you can ensure by manually inspecting the code that you’ll never
have an `Err` variant, it’s perfectly acceptable to call `expect` and document
the reason you think you’ll never have an `Err` variant in the argument text.
Here’s an example:
```rust
    use std::net::IpAddr;

    let home: IpAddr = "127.0.0.1"
        .parse()
        .expect("Hardcoded IP address should be valid");
```
We’re creating an `IpAddr` instance by parsing a hardcoded string. We can see
that `127.0.0.1` is a valid IP address, so it’s acceptable to use `expect`
here. However, having a hardcoded, valid string doesn’t change the return type
of the `parse` method: We still get a `Result` value, and the compiler will
still make us handle the `Result` as if the `Err` variant is a possibility
because the compiler isn’t smart enough to see that this string is always a
valid IP address. If the IP address string came from a user rather than being
hardcoded into the program and therefore _did_ have a possibility of failure,
we’d definitely want to handle the `Result` in a more robust way instead.
Mentioning the assumption that this IP address is hardcoded will prompt us to
change `expect` to better error-handling code if, in the future, we need to get
the IP address from some other source instead.


The Rust Programming Language › To `panic!` or Not to `panic!` › Guidelines for Error Handling

It’s advisable to have your code panic when it’s possible that your code could
end up in a bad state. In this context, a _bad state_ is when some assumption,
guarantee, contract, or invariant has been broken, such as when invalid values,
contradictory values, or missing values are passed to your code—plus one or
more of the following:
- The bad state is something that is unexpected, as opposed to something that
  will likely happen occasionally, like a user entering data in the wrong
  format.
- Your code after this point needs to rely on not being in this bad state,
  rather than checking for the problem at every step.
- There’s not a good way to encode this information in the types you use. We’ll
  work through an example of what we mean in “Encoding States and Behavior as
  Types” in Chapter 18.
If someone calls your code and passes in values that don’t make sense, it’s
best to return an error if you can so that the user of the library can decide
what they want to do in that case. However, in cases where continuing could be
insecure or harmful, the best choice might be to call `panic!` and alert the
person using your library to the bug in their code so that they can fix it
during development. Similarly, `panic!` is often appropriate if you’re calling
external code that is out of your control and returns an invalid state that you
have no way of fixing.
However, when failure is expected, it’s more appropriate to return a `Result`
than to make a `panic!` call. Examples include a parser being given malformed
data or an HTTP request returning a status that indicates you have hit a rate
limit. In these cases, returning a `Result` indicates that failure is an
expected possibility that the calling code must decide how to handle.

To `panic!` or Not to `panic!`
Guidelines for Error Handling


The Rust Programming Language › To `panic!` or Not to `panic!` › Guidelines for Error Handling

When your code performs an operation that could put a user at risk if it’s
called using invalid values, your code should verify the values are valid first
and panic if the values aren’t valid. This is mostly for safety reasons:
Attempting to operate on invalid data can expose your code to vulnerabilities.
This is the main reason the standard library will call `panic!` if you attempt
an out-of-bounds memory access: Trying to access memory that doesn’t belong to
the current data structure is a common security problem. Functions often have
_contracts_: Their behavior is only guaranteed if the inputs meet particular
requirements. Panicking when the contract is violated makes sense because a
contract violation always indicates a caller-side bug, and it’s not a kind of
error you want the calling code to have to explicitly handle. In fact, there’s
no reasonable way for calling code to recover; the calling _programmers_ need
to fix the code. Contracts for a function, especially when a violation will
cause a panic, should be explained in the API documentation for the function.


The Rust Programming Language › To `panic!` or Not to `panic!` › Guidelines for Error Handling

However, having lots of error checks in all of your functions would be verbose
and annoying. Fortunately, you can use Rust’s type system (and thus the type
checking done by the compiler) to do many of the checks for you. If your
function has a particular type as a parameter, you can proceed with your code’s
logic knowing that the compiler has already ensured that you have a valid
value. For example, if you have a type rather than an `Option`, your program
expects to have _something_ rather than _nothing_. Your code then doesn’t have
to handle two cases for the `Some` and `None` variants: It will only have one
case for definitely having a value. Code trying to pass nothing to your
function won’t even compile, so your function doesn’t have to check for that
case at runtime. Another example is using an unsigned integer type such as
`u32`, which ensures that the parameter is never negative.


The Rust Programming Language › To `panic!` or Not to `panic!` › Custom Types for Validation

Let’s take the idea of using Rust’s type system to ensure that we have a valid
value one step further and look at creating a custom type for validation.
Recall the guessing game in Chapter 2 in which our code asked the user to guess
a number between 1 and 100. We never validated that the user’s guess was
between those numbers before checking it against our secret number; we only
validated that the guess was positive. In this case, the consequences were not
very dire: Our output of “Too high” or “Too low” would still be correct. But it
would be a useful enhancement to guide the user toward valid guesses and have
different behavior when the user guesses a number that’s out of range versus
when the user types, for example, letters instead.
One way to do this would be to parse the guess as an `i32` instead of only a
`u32` to allow potentially negative numbers, and then add a check for the
number being in range, like so:
Listing (src/main.rs)
```rust,ignore
    loop {
        // --snip--

        let guess: i32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        if guess < 1 || guess > 100 {
            println!("The secret number will be between 1 and 100.");
            continue;
        }

        match guess.cmp(&secret_number) {
            // --snip--
    }
```
The `if` expression checks whether our value is out of range, tells the user
about the problem, and calls `continue` to start the next iteration of the loop
and ask for another guess. After the `if` expression, we can proceed with the
comparisons between `guess` and the secret number knowing that `guess` is
between 1 and 100.

To `panic!` or Not to `panic!`
Custom Types for Validation


The Rust Programming Language › To `panic!` or Not to `panic!` › Custom Types for Validation

However, this is not an ideal solution: If it were absolutely critical that the
program only operated on values between 1 and 100, and it had many functions
with this requirement, having a check like this in every function would be
tedious (and might impact performance).
Instead, we can make a new type in a dedicated module and put the validations
in a function to create an instance of the type rather than repeating the
validations everywhere. That way, it’s safe for functions to use the new type
in their signatures and confidently use the values they receive. Listing 9-13
shows one way to define a `Guess` type that will only create an instance of
`Guess` if the `new` function receives a value between 1 and 100.
Listing 9-13: A `Guess` type that will only continue with values between 1 and 100 (src/guessing_game.rs)
```rust
pub struct Guess {
    value: i32,
}

impl Guess {
    pub fn new(value: i32) -> Guess {
        if value < 1 || value > 100 {
            panic!("Guess value must be between 1 and 100, got {value}.");
        }

        Guess { value }
    }

    pub fn value(&self) -> i32 {
        self.value
    }
}
```
Note that this code in *src/guessing_game.rs* depends on adding a module
declaration `mod guessing_game;` in *src/lib.rs* that we haven’t shown here.
Within this new module’s file, we define a struct named `Guess` that has a
field named `value` that holds an `i32`. This is where the number will be
stored.


The Rust Programming Language › To `panic!` or Not to `panic!` › Custom Types for Validation

Then, we implement an associated function named `new` on `Guess` that creates
instances of `Guess` values. The `new` function is defined to have one
parameter named `value` of type `i32` and to return a `Guess`. The code in the
body of the `new` function tests `value` to make sure it’s between 1 and 100.
If `value` doesn’t pass this test, we make a `panic!` call, which will alert
the programmer who is writing the calling code that they have a bug they need
to fix, because creating a `Guess` with a `value` outside this range would
violate the contract that `Guess::new` is relying on. The conditions in which
`Guess::new` might panic should be discussed in its public-facing API
documentation; we’ll cover documentation conventions indicating the possibility
of a `panic!` in the API documentation that you create in Chapter 14. If
`value` does pass the test, we create a new `Guess` with its `value` field set
to the `value` parameter and return the `Guess`.


The Rust Programming Language › To `panic!` or Not to `panic!` › Custom Types for Validation

Next, we implement a method named `value` that borrows `self`, doesn’t have any
other parameters, and returns an `i32`. This kind of method is sometimes called
a _getter_ because its purpose is to get some data from its fields and return
it. This public method is necessary because the `value` field of the `Guess`
struct is private. It’s important that the `value` field be private so that
code using the `Guess` struct is not allowed to set `value` directly: Code
outside the `guessing_game` module _must_ use the `Guess::new` function to
create an instance of `Guess`, thereby ensuring that there’s no way for a
`Guess` to have a `value` that hasn’t been checked by the conditions in the
`Guess::new` function.
A function that has a parameter or returns only numbers between 1 and 100 could
then declare in its signature that it takes or returns a `Guess` rather than an
`i32` and wouldn’t need to do any additional checks in its body.


The Rust Programming Language › Summary

Rust’s error-handling features are designed to help you write more robust code.
The `panic!` macro signals that your program is in a state it can’t handle and
lets you tell the process to stop instead of trying to proceed with invalid or
incorrect values. The `Result` enum uses Rust’s type system to indicate that
operations might fail in a way that your code could recover from. You can use
`Result` to tell code that calls your code that it needs to handle potential
success or failure as well. Using `panic!` and `Result` in the appropriate
situations will make your code more reliable in the face of inevitable problems.
Now that you’ve seen useful ways that the standard library uses generics with
the `Option` and `Result` enums, we’ll talk about how generics work and how you
can use them in your code.


The Rust Programming Language › Generic Types, Traits, and Lifetimes

Every programming language has tools for effectively handling the duplication
of concepts. In Rust, one such tool is _generics_: abstract stand-ins for
concrete types or other properties. We can express the behavior of generics or
how they relate to other generics without knowing what will be in their place
when compiling and running the code.
Functions can take parameters of some generic type, instead of a concrete type
like `i32` or `String`, in the same way they take parameters with unknown
values to run the same code on multiple concrete values. In fact, we already
used generics in Chapter 6 with `Option<T>`, in Chapter 8 with `Vec<T>` and
`HashMap<K, V>`, and in Chapter 9 with `Result<T, E>`. In this chapter, you’ll
explore how to define your own types, functions, and methods with generics!
First, we’ll review how to extract a function to reduce code duplication. We’ll
then use the same technique to make a generic function from two functions that
differ only in the types of their parameters. We’ll also explain how to use
generic types in struct and enum definitions.
Then, you’ll learn how to use traits to define behavior in a generic way. You
can combine traits with generic types to constrain a generic type to accept
only those types that have a particular behavior, as opposed to just any type.
Finally, we’ll discuss _lifetimes_: a variety of generics that give the
compiler information about how references relate to each other. Lifetimes allow
us to give the compiler enough information about borrowed values so that it can
ensure that references will be valid in more situations than it could without
our help.


The Rust Programming Language › Generic Types, Traits, and Lifetimes › Removing Duplication by Extracting a Function

Generics allow us to replace specific types with a placeholder that represents
multiple types to remove code duplication. Before diving into generics syntax,
let’s first look at how to remove duplication in a way that doesn’t involve
generic types by extracting a function that replaces specific values with a
placeholder that represents multiple values. Then, we’ll apply the same
technique to extract a generic function! By looking at how to recognize
duplicated code you can extract into a function, you’ll start to recognize
duplicated code that can use generics.
We’ll begin with the short program in Listing 10-1 that finds the largest
number in a list.
Listing 10-1: Finding the largest number in a list of numbers (src/main.rs)
```rust
fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let mut largest = &number_list[0];

    for number in &number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {largest}");
}
```
We store a list of integers in the variable `number_list` and place a reference
to the first number in the list in a variable named `largest`. We then iterate
through all the numbers in the list, and if the current number is greater than
the number stored in `largest`, we replace the reference in that variable.
However, if the current number is less than or equal to the largest number seen
so far, the variable doesn’t change, and the code moves on to the next number
in the list. After considering all the numbers in the list, `largest` should
refer to the largest number, which in this case is 100.


The Rust Programming Language › Generic Types, Traits, and Lifetimes › Removing Duplication by Extracting a Function

We’ve now been tasked with finding the largest number in two different lists of
numbers. To do so, we can choose to duplicate the code in Listing 10-1 and use
the same logic at two different places in the program, as shown in Listing 10-2.
Listing 10-2: Code to find the largest number in *two* lists of numbers (src/main.rs)
```rust
fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let mut largest = &number_list[0];

    for number in &number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {largest}");

    let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

    let mut largest = &number_list[0];

    for number in &number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {largest}");
}
```
Although this code works, duplicating code is tedious and error-prone. We also
have to remember to update the code in multiple places when we want to change
it.
To eliminate this duplication, we’ll create an abstraction by defining a
function that operates on any list of integers passed in as a parameter. This
solution makes our code clearer and lets us express the concept of finding the
largest number in a list abstractly.


The Rust Programming Language › Generic Types, Traits, and Lifetimes › Removing Duplication by Extracting a Function

In Listing 10-3, we extract the code that finds the largest number into a
function named `largest`. Then, we call the function to find the largest number
in the two lists from Listing 10-2. We could also use the function on any other
list of `i32` values we might have in the future.
Listing 10-3: Abstracted code to find the largest number in two lists (src/main.rs)
```rust
fn largest(list: &[i32]) -> &i32 {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest(&number_list);
    println!("The largest number is {result}");

    let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

    let result = largest(&number_list);
    println!("The largest number is {result}");
}
```
The `largest` function has a parameter called `list`, which represents any
concrete slice of `i32` values we might pass into the function. As a result,
when we call the function, the code runs on the specific values that we pass
in.
In summary, here are the steps we took to change the code from Listing 10-2 to
Listing 10-3:
1. Identify duplicate code.
1. Extract the duplicate code into the body of the function, and specify the
   inputs and return values of that code in the function signature.
1. Update the two instances of duplicated code to call the function instead.


The Rust Programming Language › Generic Types, Traits, and Lifetimes › Removing Duplication by Extracting a Function

Next, we’ll use these same steps with generics to reduce code duplication. In
the same way that the function body can operate on an abstract `list` instead
of specific values, generics allow code to operate on abstract types.
For example, say we had two functions: one that finds the largest item in a
slice of `i32` values and one that finds the largest item in a slice of `char`
values. How would we eliminate that duplication? Let’s find out!


The Rust Programming Language › Generic Data Types

We use generics to create definitions for items like function signatures or
structs, which we can then use with many different concrete data types. Let’s
first look at how to define functions, structs, enums, and methods using
generics. Then, we’ll discuss how generics affect code performance.


The Rust Programming Language › Generic Data Types › In Function Definitions

When defining a function that uses generics, we place the generics in the
signature of the function where we would usually specify the data types of the
parameters and return value. Doing so makes our code more flexible and provides
more functionality to callers of our function while preventing code duplication.
Continuing with our `largest` function, Listing 10-4 shows two functions that
both find the largest value in a slice. We’ll then combine these into a single
function that uses generics.
Listing 10-4: Two functions that differ only in their names and in the types in their signatures (src/main.rs)
```rust
fn largest_i32(list: &[i32]) -> &i32 {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn largest_char(list: &[char]) -> &char {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest_i32(&number_list);
    println!("The largest number is {result}");

    let char_list = vec!['y', 'm', 'a', 'q'];

    let result = largest_char(&char_list);
    println!("The largest char is {result}");
}
```
The `largest_i32` function is the one we extracted in Listing 10-3 that finds
the largest `i32` in a slice. The `largest_char` function finds the largest
`char` in a slice. The function bodies have the same code, so let’s eliminate
the duplication by introducing a generic type parameter in a single function.

Generic Data Types
In Function Definitions


The Rust Programming Language › Generic Data Types › In Function Definitions

To parameterize the types in a new single function, we need to name the type
parameter, just as we do for the value parameters to a function. You can use
any identifier as a type parameter name. But we’ll use `T` because, by
convention, type parameter names in Rust are short, often just one letter, and
Rust’s type-naming convention is UpperCamelCase. Short for _type_, `T` is the
default choice of most Rust programmers.
When we use a parameter in the body of the function, we have to declare the
parameter name in the signature so that the compiler knows what that name
means. Similarly, when we use a type parameter name in a function signature, we
have to declare the type parameter name before we use it. To define the generic
`largest` function, we place type name declarations inside angle brackets,
`<>`, between the name of the function and the parameter list, like this:
```rust,ignore
fn largest<T>(list: &[T]) -> &T {
```
We read this definition as “The function `largest` is generic over some type
`T`.” This function has one parameter named `list`, which is a slice of values
of type `T`. The `largest` function will return a reference to a value of the
same type `T`.
Listing 10-5 shows the combined `largest` function definition using the generic
data type in its signature. The listing also shows how we can call the function
with either a slice of `i32` values or `char` values. Note that this code won’t
compile yet.
Listing 10-5: The `largest` function using generic type parameters; this doesn’t compile yet (src/main.rs)


The Rust Programming Language › Generic Data Types › In Function Definitions

```rust,ignore,does_not_compile
fn largest<T>(list: &[T]) -> &T {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest(&number_list);
    println!("The largest number is {result}");

    let char_list = vec!['y', 'm', 'a', 'q'];

    let result = largest(&char_list);
    println!("The largest char is {result}");
}
```
If we compile this code right now, we’ll get this error:
```console
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> src/main.rs:5:17
  |
5 |         if item > largest {
  |            ---- ^ ------- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T {
  |             ++++++++++++++++++++++

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


The Rust Programming Language › Generic Data Types › In Function Definitions

The help text mentions `std::cmp::PartialOrd`, which is a trait, and we’re
going to talk about traits in the next section. For now, know that this error
states that the body of `largest` won’t work for all possible types that `T`
could be. Because we want to compare values of type `T` in the body, we can
only use types whose values can be ordered. To enable comparisons, the standard
library has the `std::cmp::PartialOrd` trait that you can implement on types
(see Appendix C for more on this trait). To fix Listing 10-5, we can follow the
help text’s suggestion and restrict the types valid for `T` to only those that
implement `PartialOrd`. The listing will then compile, because the standard
library implements `PartialOrd` on both `i32` and `char`.


The Rust Programming Language › Generic Data Types › In Struct Definitions

We can also define structs to use a generic type parameter in one or more
fields using the `<>` syntax. Listing 10-6 defines a `Point<T>` struct to hold
`x` and `y` coordinate values of any type.
Listing 10-6 (src/main.rs)
```rust
struct Point<T> {
    x: T,
    y: T,
}

fn main() {
    let integer = Point { x: 5, y: 10 };
    let float = Point { x: 1.0, y: 4.0 };
}
```
The syntax for using generics in struct definitions is similar to that used in
function definitions. First, we declare the name of the type parameter inside
angle brackets just after the name of the struct. Then, we use the generic type
in the struct definition where we would otherwise specify concrete data types.
Note that because we’ve used only one generic type to define `Point<T>`, this
definition says that the `Point<T>` struct is generic over some type `T`, and
the fields `x` and `y` are _both_ that same type, whatever that type may be. If
we create an instance of a `Point<T>` that has values of different types, as in
Listing 10-7, our code won’t compile.
Listing 10-7: The fields `x` and `y` must be the same type because both have the same generic data type `T`. (src/main.rs)
```rust,ignore,does_not_compile
struct Point<T> {
    x: T,
    y: T,
}

fn main() {
    let wont_work = Point { x: 5, y: 4.0 };
}
```

Generic Data Types
In Struct Definitions


The Rust Programming Language › Generic Data Types › In Struct Definitions

In this example, when we assign the integer value `5` to `x`, we let the
compiler know that the generic type `T` will be an integer for this instance of
`Point<T>`. Then, when we specify `4.0` for `y`, which we’ve defined to have
the same type as `x`, we’ll get a type mismatch error like this:
```console
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0308]: mismatched types
 --> src/main.rs:7:38
  |
7 |     let wont_work = Point { x: 5, y: 4.0 };
  |                                      ^^^ expected integer, found floating-point number

For more information about this error, try `rustc --explain E0308`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
```
To define a `Point` struct where `x` and `y` are both generics but could have
different types, we can use multiple generic type parameters. For example, in
Listing 10-8, we change the definition of `Point` to be generic over types `T`
and `U` where `x` is of type `T` and `y` is of type `U`.
Listing 10-8 (src/main.rs)
```rust
struct Point<T, U> {
    x: T,
    y: U,
}

fn main() {
    let both_integer = Point { x: 5, y: 10 };
    let both_float = Point { x: 1.0, y: 4.0 };
    let integer_and_float = Point { x: 5, y: 4.0 };
}
```


The Rust Programming Language › Generic Data Types › In Struct Definitions

Now all the instances of `Point` shown are allowed! You can use as many generic
type parameters in a definition as you want, but using more than a few makes
your code hard to read. If you’re finding you need lots of generic types in
your code, it could indicate that your code needs restructuring into smaller
pieces.


The Rust Programming Language › Generic Data Types › In Enum Definitions

As we did with structs, we can define enums to hold generic data types in their
variants. Let’s take another look at the `Option<T>` enum that the standard
library provides, which we used in Chapter 6:
```rust
enum Option<T> {
    Some(T),
    None,
}
```
This definition should now make more sense to you. As you can see, the
`Option<T>` enum is generic over type `T` and has two variants: `Some`, which
holds one value of type `T`, and a `None` variant that doesn’t hold any value.
By using the `Option<T>` enum, we can express the abstract concept of an
optional value, and because `Option<T>` is generic, we can use this abstraction
no matter what the type of the optional value is.
Enums can use multiple generic types as well. The definition of the `Result`
enum that we used in Chapter 9 is one example:
```rust
enum Result<T, E> {
    Ok(T),
    Err(E),
}
```
The `Result` enum is generic over two types, `T` and `E`, and has two variants:
`Ok`, which holds a value of type `T`, and `Err`, which holds a value of type
`E`. This definition makes it convenient to use the `Result` enum anywhere we
have an operation that might succeed (return a value of some type `T`) or fail
(return an error of some type `E`). In fact, this is what we used to open a
file in Listing 9-3, where `T` was filled in with the type `std::fs::File` when
the file was opened successfully and `E` was filled in with the type
`std::io::Error` when there were problems opening the file.


The Rust Programming Language › Generic Data Types › In Enum Definitions

When you recognize situations in your code with multiple struct or enum
definitions that differ only in the types of the values they hold, you can
avoid duplication by using generic types instead.


The Rust Programming Language › Generic Data Types › In Method Definitions

We can implement methods on structs and enums (as we did in Chapter 5) and use
generic types in their definitions too. Listing 10-9 shows the `Point<T>`
struct we defined in Listing 10-6 with a method named `x` implemented on it.
Listing 10-9 (src/main.rs)
```rust
struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

fn main() {
    let p = Point { x: 5, y: 10 };

    println!("p.x = {}", p.x());
}
```
Here, we’ve defined a method named `x` on `Point<T>` that returns a reference
to the data in the field `x`.
Note that we have to declare `T` just after `impl` so that we can use `T` to
specify that we’re implementing methods on the type `Point<T>`. By declaring
`T` as a generic type after `impl`, Rust can identify that the type in the
angle brackets in `Point` is a generic type rather than a concrete type. We
could have chosen a different name for this generic parameter than the generic
parameter declared in the struct definition, but using the same name is
conventional. If you write a method within an `impl` that declares a generic
type, that method will be defined on any instance of the type, no matter what
concrete type ends up substituting for the generic type.
We can also specify constraints on generic types when defining methods on the
type. We could, for example, implement methods only on `Point<f32>` instances
rather than on `Point<T>` instances with any generic type. In Listing 10-10, we
use the concrete type `f32`, meaning we don’t declare any types after `impl`.

Generic Data Types
In Method Definitions


The Rust Programming Language › Generic Data Types › In Method Definitions

Listing 10-10: An `impl` block that only applies to a struct with a particular concrete type for the generic type parameter `T` (src/main.rs)
```rust
impl Point<f32> {
    fn distance_from_origin(&self) -> f32 {
        (self.x.powi(2) + self.y.powi(2)).sqrt()
    }
}
```
This code means the type `Point<f32>` will have a `distance_from_origin`
method; other instances of `Point<T>` where `T` is not of type `f32` will not
have this method defined. The method measures how far our point is from the
point at coordinates (0.0, 0.0) and uses mathematical operations that are
available only for floating-point types.
Generic type parameters in a struct definition aren’t always the same as those
you use in that same struct’s method signatures. Listing 10-11 uses the generic
types `X1` and `Y1` for the `Point` struct and `X2` and `Y2` for the `mixup`
method signature to make the example clearer. The method creates a new `Point`
instance with the `x` value from the `self` `Point` (of type `X1`) and the `y`
value from the passed-in `Point` (of type `Y2`).
Listing 10-11: A method that uses generic types that are different from its struct’s definition (src/main.rs)


The Rust Programming Language › Generic Data Types › In Method Definitions

```rust
struct Point<X1, Y1> {
    x: X1,
    y: Y1,
}

impl<X1, Y1> Point<X1, Y1> {
    fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> {
        Point {
            x: self.x,
            y: other.y,
        }
    }
}

fn main() {
    let p1 = Point { x: 5, y: 10.4 };
    let p2 = Point { x: "Hello", y: 'c' };

    let p3 = p1.mixup(p2);

    println!("p3.x = {}, p3.y = {}", p3.x, p3.y);
}
```
In `main`, we’ve defined a `Point` that has an `i32` for `x` (with value `5`)
and an `f64` for `y` (with value `10.4`). The `p2` variable is a `Point` struct
that has a string slice for `x` (with value `"Hello"`) and a `char` for `y`
(with value `c`). Calling `mixup` on `p1` with the argument `p2` gives us `p3`,
which will have an `i32` for `x` because `x` came from `p1`. The `p3` variable
will have a `char` for `y` because `y` came from `p2`. The `println!` macro
call will print `p3.x = 5, p3.y = c`.


The Rust Programming Language › Generic Data Types › In Method Definitions

The purpose of this example is to demonstrate a situation in which some generic
parameters are declared with `impl` and some are declared with the method
definition. Here, the generic parameters `X1` and `Y1` are declared after
`impl` because they go with the struct definition. The generic parameters `X2`
and `Y2` are declared after `fn mixup` because they’re only relevant to the
method.


The Rust Programming Language › Generic Data Types › Performance of Code Using Generics

You might be wondering whether there is a runtime cost when using generic type
parameters. The good news is that using generic types won’t make your program
run any slower than it would with concrete types.
Rust accomplishes this by performing monomorphization of the code using
generics at compile time. _Monomorphization_ is the process of turning generic
code into specific code by filling in the concrete types that are used when
compiled. In this process, the compiler does the opposite of the steps we used
to create the generic function in Listing 10-5: The compiler looks at all the
places where generic code is called and generates code for the concrete types
the generic code is called with.
Let’s look at how this works by using the standard library’s generic
`Option<T>` enum:
```rust
let integer = Some(5);
let float = Some(5.0);
```
When Rust compiles this code, it performs monomorphization. During that
process, the compiler reads the values that have been used in `Option<T>`
instances and identifies two kinds of `Option<T>`: One is `i32` and the other
is `f64`. As such, it expands the generic definition of `Option<T>` into two
definitions specialized to `i32` and `f64`, thereby replacing the generic
definition with the specific ones.
The monomorphized version of the code looks similar to the following (the
compiler uses different names than what we’re using here for illustration):
Listing (src/main.rs)
```rust
enum Option_i32 {
    Some(i32),
    None,
}

enum Option_f64 {
    Some(f64),
    None,
}

fn main() {
    let integer = Option_i32::Some(5);
    let float = Option_f64::Some(5.0);
}
```

Generic Data Types
Performance of Code Using Generics


The Rust Programming Language › Generic Data Types › Performance of Code Using Generics

The generic `Option<T>` is replaced with the specific definitions created by
the compiler. Because Rust compiles generic code into code that specifies the
type in each instance, we pay no runtime cost for using generics. When the code
runs, it performs just as it would if we had duplicated each definition by
hand. The process of monomorphization makes Rust’s generics extremely efficient
at runtime.


The Rust Programming Language › Defining Shared Behavior with Traits

A _trait_ defines the functionality a particular type has and can share with
other types. We can use traits to define shared behavior in an abstract way. We
can use _trait bounds_ to specify that a generic type can be any type that has
certain behavior.
Note: Traits are similar to a feature often called _interfaces_ in other
languages, although with some differences.


The Rust Programming Language › Defining Shared Behavior with Traits › Defining a Trait

A type’s behavior consists of the methods we can call on that type. Different
types share the same behavior if we can call the same methods on all of those
types. Trait definitions are a way to group method signatures together to
define a set of behaviors necessary to accomplish some purpose.
For example, let’s say we have multiple structs that hold various kinds and
amounts of text: a `NewsArticle` struct that holds a news story filed in a
particular location and a `SocialPost` that can have, at most, 280 characters
along with metadata that indicates whether it was a new post, a repost, or a
reply to another post.
We want to make a media aggregator library crate named `aggregator` that can
display summaries of data that might be stored in a `NewsArticle` or
`SocialPost` instance. To do this, we need a summary from each type, and we’ll
request that summary by calling a `summarize` method on an instance. Listing
10-12 shows the definition of a public `Summary` trait that expresses this
behavior.
Listing 10-12: A `Summary` trait that consists of the behavior provided by a `summarize` method (src/lib.rs)
```rust,noplayground
pub trait Summary {
    fn summarize(&self) -> String;
}
```
Here, we declare a trait using the `trait` keyword and then the trait’s name,
which is `Summary` in this case. We also declare the trait as `pub` so that
crates depending on this crate can make use of this trait too, as we’ll see in
a few examples. Inside the curly brackets, we declare the method signatures
that describe the behaviors of the types that implement this trait, which in
this case is `fn summarize(&self) -> String`.

Defining Shared Behavior with Traits
Defining a Trait


The Rust Programming Language › Defining Shared Behavior with Traits › Defining a Trait

After the method signature, instead of providing an implementation within curly
brackets, we use a semicolon. Each type implementing this trait must provide
its own custom behavior for the body of the method. The compiler will enforce
that any type that has the `Summary` trait will have the method `summarize`
defined with this signature exactly.
A trait can have multiple methods in its body: The method signatures are listed
one per line, and each line ends in a semicolon.


The Rust Programming Language › Defining Shared Behavior with Traits › Implementing a Trait on a Type

Now that we’ve defined the desired signatures of the `Summary` trait’s methods,
we can implement it on the types in our media aggregator. Listing 10-13 shows
an implementation of the `Summary` trait on the `NewsArticle` struct that uses
the headline, the author, and the location to create the return value of
`summarize`. For the `SocialPost` struct, we define `summarize` as the username
followed by the entire text of the post, assuming that the post content is
already limited to 280 characters.
Listing 10-13: Implementing the `Summary` trait on the `NewsArticle` and `SocialPost` types (src/lib.rs)
```rust,noplayground
pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct SocialPost {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub repost: bool,
}

impl Summary for SocialPost {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}
```
Implementing a trait on a type is similar to implementing regular methods. The
difference is that after `impl`, we put the trait name we want to implement,
then use the `for` keyword, and then specify the name of the type we want to
implement the trait for. Within the `impl` block, we put the method signatures
that the trait definition has defined. Instead of adding a semicolon after each
signature, we use curly brackets and fill in the method body with the specific
behavior that we want the methods of the trait to have for the particular type.

Defining Shared Behavior with Traits
Implementing a Trait on a Type


The Rust Programming Language › Defining Shared Behavior with Traits › Implementing a Trait on a Type

Now that the library has implemented the `Summary` trait on `NewsArticle` and
`SocialPost`, users of the crate can call the trait methods on instances of
`NewsArticle` and `SocialPost` in the same way we call regular methods. The only
difference is that the user must bring the trait into scope as well as the
types. Here’s an example of how a binary crate could use our `aggregator`
library crate:
```rust,ignore
use aggregator::{SocialPost, Summary};

fn main() {
    let post = SocialPost {
        username: String::from("horse_ebooks"),
        content: String::from(
            "of course, as you probably already know, people",
        ),
        reply: false,
        repost: false,
    };

    println!("1 new post: {}", post.summarize());
}
```
This code prints `1 new post: horse_ebooks: of course, as you probably already
know, people`.
Other crates that depend on the `aggregator` crate can also bring the `Summary`
trait into scope to implement `Summary` on their own types. One restriction to
note is that we can implement a trait on a type only if either the trait or the
type, or both, are local to our crate. For example, we can implement standard
library traits like `Display` on a custom type like `SocialPost` as part of our
`aggregator` crate functionality because the type `SocialPost` is local to our
`aggregator` crate. We can also implement `Summary` on `Vec<T>` in our
`aggregator` crate because the trait `Summary` is local to our `aggregator`
crate.


The Rust Programming Language › Defining Shared Behavior with Traits › Implementing a Trait on a Type

But we can’t implement external traits on external types. For example, we can’t
implement the `Display` trait on `Vec<T>` within our `aggregator` crate,
because `Display` and `Vec<T>` are both defined in the standard library and
aren’t local to our `aggregator` crate. This restriction is part of a property
called _coherence_, and more specifically the _orphan rule_, so named because
the parent type is not present. This rule ensures that other people’s code
can’t break your code and vice versa. Without the rule, two crates could
implement the same trait for the same type, and Rust wouldn’t know which
implementation to use.


The Rust Programming Language › Defining Shared Behavior with Traits › Using Default Implementations

Sometimes it’s useful to have default behavior for some or all of the methods
in a trait instead of requiring implementations for all methods on every type.
Then, as we implement the trait on a particular type, we can keep or override
each method’s default behavior.
In Listing 10-14, we specify a default string for the `summarize` method of the
`Summary` trait instead of only defining the method signature, as we did in
Listing 10-12.
Listing 10-14: Defining a `Summary` trait with a default implementation of the `summarize` method (src/lib.rs)
```rust,noplayground
pub trait Summary {
    fn summarize(&self) -> String {
        String::from("(Read more...)")
    }
}
```
To use a default implementation to summarize instances of `NewsArticle`, we
specify an empty `impl` block with `impl Summary for NewsArticle {}`.
Even though we’re no longer defining the `summarize` method on `NewsArticle`
directly, we’ve provided a default implementation and specified that
`NewsArticle` implements the `Summary` trait. As a result, we can still call
the `summarize` method on an instance of `NewsArticle`, like this:
```rust,ignore
    let article = NewsArticle {
        headline: String::from("Penguins win the Stanley Cup Championship!"),
        location: String::from("Pittsburgh, PA, USA"),
        author: String::from("Iceburgh"),
        content: String::from(
            "The Pittsburgh Penguins once again are the best \
             hockey team in the NHL.",
        ),
    };

    println!("New article available! {}", article.summarize());
```
This code prints `New article available! (Read more...)`.

Defining Shared Behavior with Traits
Using Default Implementations


The Rust Programming Language › Defining Shared Behavior with Traits › Using Default Implementations

Creating a default implementation doesn’t require us to change anything about
the implementation of `Summary` on `SocialPost` in Listing 10-13. The reason is
that the syntax for overriding a default implementation is the same as the
syntax for implementing a trait method that doesn’t have a default
implementation.
Default implementations can call other methods in the same trait, even if those
other methods don’t have a default implementation. In this way, a trait can
provide a lot of useful functionality and only require implementors to specify
a small part of it. For example, we could define the `Summary` trait to have a
`summarize_author` method whose implementation is required, and then define a
`summarize` method that has a default implementation that calls the
`summarize_author` method:
```rust,noplayground
pub trait Summary {
    fn summarize_author(&self) -> String;

    fn summarize(&self) -> String {
        format!("(Read more from {}...)", self.summarize_author())
    }
}
```
To use this version of `Summary`, we only need to define `summarize_author`
when we implement the trait on a type:
```rust,ignore
impl Summary for SocialPost {
    fn summarize_author(&self) -> String {
        format!("@{}", self.username)
    }
}
```
After we define `summarize_author`, we can call `summarize` on instances of the
`SocialPost` struct, and the default implementation of `summarize` will call the
definition of `summarize_author` that we’ve provided. Because we’ve implemented
`summarize_author`, the `Summary` trait has given us the behavior of the
`summarize` method without requiring us to write any more code. Here’s what
that looks like:


The Rust Programming Language › Defining Shared Behavior with Traits › Using Default Implementations

```rust,ignore
    let post = SocialPost {
        username: String::from("horse_ebooks"),
        content: String::from(
            "of course, as you probably already know, people",
        ),
        reply: false,
        repost: false,
    };

    println!("1 new post: {}", post.summarize());
```
This code prints `1 new post: (Read more from @horse_ebooks...)`.
Note that it isn’t possible to call the default implementation from an
overriding implementation of that same method.


The Rust Programming Language › Defining Shared Behavior with Traits › Using Traits as Parameters › Trait Bound Syntax

Now that you know how to define and implement traits, we can explore how to use
traits to define functions that accept many different types. We’ll use the
`Summary` trait we implemented on the `NewsArticle` and `SocialPost` types in
Listing 10-13 to define a `notify` function that calls the `summarize` method
on its `item` parameter, which is of some type that implements the `Summary`
trait. To do this, we use the `impl Trait` syntax, like this:
```rust,ignore
pub fn notify(item: &impl Summary) {
    println!("Breaking news! {}", item.summarize());
}
```
Instead of a concrete type for the `item` parameter, we specify the `impl`
keyword and the trait name. This parameter accepts any type that implements the
specified trait. In the body of `notify`, we can call any methods on `item`
that come from the `Summary` trait, such as `summarize`. We can call `notify`
and pass in any instance of `NewsArticle` or `SocialPost`. Code that calls the
function with any other type, such as a `String` or an `i32`, won’t compile,
because those types don’t implement `Summary`.
The `impl Trait` syntax works for straightforward cases but is actually syntax
sugar for a longer form known as a _trait bound_; it looks like this:
```rust,ignore
pub fn notify<T: Summary>(item: &T) {
    println!("Breaking news! {}", item.summarize());
}
```
This longer form is equivalent to the example in the previous section but is
more verbose. We place trait bounds with the declaration of the generic type
parameter after a colon and inside angle brackets.

Defining Shared Behavior with Traits
Using Traits as Parameters
Trait Bound Syntax


The Rust Programming Language › Defining Shared Behavior with Traits › Using Traits as Parameters › Clearer Trait Bounds with `where` Clauses

The `impl Trait` syntax is convenient and makes for more concise code in simple
cases, while the fuller trait bound syntax can express more complexity in other
cases. For example, we can have two parameters that implement `Summary`. Doing
so with the `impl Trait` syntax looks like this:
```rust,ignore
pub fn notify(item1: &impl Summary, item2: &impl Summary) {
```
Using `impl Trait` is appropriate if we want this function to allow `item1` and
`item2` to have different types (as long as both types implement `Summary`). If
we want to force both parameters to have the same type, however, we must use a
trait bound, like this:
```rust,ignore
pub fn notify<T: Summary>(item1: &T, item2: &T) {
```
The generic type `T` specified as the type of the `item1` and `item2`
parameters constrains the function such that the concrete type of the value
passed as an argument for `item1` and `item2` must be the same.
We can also specify more than one trait bound. Say we wanted `notify` to use
display formatting as well as `summarize` on `item`: We specify in the `notify`
definition that `item` must implement both `Display` and `Summary`. We can do
so using the `+` syntax:
```rust,ignore
pub fn notify(item: &(impl Summary + Display)) {
```
The `+` syntax is also valid with trait bounds on generic types:
```rust,ignore
pub fn notify<T: Summary + Display>(item: &T) {
```
With the two trait bounds specified, the body of `notify` can call `summarize`
and use `{}` to format `item`.


The Rust Programming Language › Defining Shared Behavior with Traits › Using Traits as Parameters › Clearer Trait Bounds with `where` Clauses

Using too many trait bounds has its downsides. Each generic has its own trait
bounds, so functions with multiple generic type parameters can contain lots of
trait bound information between the function’s name and its parameter list,
making the function signature hard to read. For this reason, Rust has alternate
syntax for specifying trait bounds inside a `where` clause after the function
signature. So, instead of writing this:
```rust,ignore
fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {
```
we can use a `where` clause, like this:
```rust,ignore
fn some_function<T, U>(t: &T, u: &U) -> i32
where
    T: Display + Clone,
    U: Clone + Debug,
{
```
This function’s signature is less cluttered: The function name, parameter list,
and return type are close together, similar to a function without lots of trait
bounds.


The Rust Programming Language › Defining Shared Behavior with Traits › Returning Types That Implement Traits

We can also use the `impl Trait` syntax in the return position to return a
value of some type that implements a trait, as shown here:
```rust,ignore
fn returns_summarizable() -> impl Summary {
    SocialPost {
        username: String::from("horse_ebooks"),
        content: String::from(
            "of course, as you probably already know, people",
        ),
        reply: false,
        repost: false,
    }
}
```
By using `impl Summary` for the return type, we specify that the
`returns_summarizable` function returns some type that implements the `Summary`
trait without naming the concrete type. In this case, `returns_summarizable`
returns a `SocialPost`, but the code calling this function doesn’t need to know
that.
The ability to specify a return type only by the trait it implements is
especially useful in the context of closures and iterators, which we cover in
Chapter 13. Closures and iterators create types that only the compiler knows or
types that are very long to specify. The `impl Trait` syntax lets you concisely
specify that a function returns some type that implements the `Iterator` trait
without needing to write out a very long type.
However, you can only use `impl Trait` if you’re returning a single type. For
example, this code that returns either a `NewsArticle` or a `SocialPost` with
the return type specified as `impl Summary` wouldn’t work:

Defining Shared Behavior with Traits
Returning Types That Implement Traits


The Rust Programming Language › Defining Shared Behavior with Traits › Returning Types That Implement Traits

```rust,ignore,does_not_compile
fn returns_summarizable(switch: bool) -> impl Summary {
    if switch {
        NewsArticle {
            headline: String::from(
                "Penguins win the Stanley Cup Championship!",
            ),
            location: String::from("Pittsburgh, PA, USA"),
            author: String::from("Iceburgh"),
            content: String::from(
                "The Pittsburgh Penguins once again are the best \
                 hockey team in the NHL.",
            ),
        }
    } else {
        SocialPost {
            username: String::from("horse_ebooks"),
            content: String::from(
                "of course, as you probably already know, people",
            ),
            reply: false,
            repost: false,
        }
    }
}
```
Returning either a `NewsArticle` or a `SocialPost` isn’t allowed due to
restrictions around how the `impl Trait` syntax is implemented in the compiler.
We’ll cover how to write a function with this behavior in the “Using Trait
Objects to Abstract over Shared Behavior”
section of Chapter 18.


The Rust Programming Language › Defining Shared Behavior with Traits › Using Trait Bounds to Conditionally Implement Methods

By using a trait bound with an `impl` block that uses generic type parameters,
we can implement methods conditionally for types that implement the specified
traits. For example, the type `Pair<T>` in Listing 10-15 always implements the
`new` function to return a new instance of `Pair<T>` (recall from the “Method
Syntax” section of Chapter 5 that `Self` is a type
alias for the type of the `impl` block, which in this case is `Pair<T>`). But
in the next `impl` block, `Pair<T>` only implements the `cmp_display` method if
its inner type `T` implements the `PartialOrd` trait that enables comparison
_and_ the `Display` trait that enables printing.
Listing 10-15: Conditionally implementing methods on a generic type depending on trait bounds (src/lib.rs)
```rust,noplayground
use std::fmt::Display;

struct Pair<T> {
    x: T,
    y: T,
}

impl<T> Pair<T> {
    fn new(x: T, y: T) -> Self {
        Self { x, y }
    }
}

impl<T: Display + PartialOrd> Pair<T> {
    fn cmp_display(&self) {
        if self.x >= self.y {
            println!("The largest member is x = {}", self.x);
        } else {
            println!("The largest member is y = {}", self.y);
        }
    }
}
```
We can also conditionally implement a trait for any type that implements
another trait. Implementations of a trait on any type that satisfies the trait
bounds are called _blanket implementations_ and are used extensively in the
Rust standard library. For example, the standard library implements the
`ToString` trait on any type that implements the `Display` trait. The `impl`
block in the standard library looks similar to this code:


The Rust Programming Language › Defining Shared Behavior with Traits › Using Trait Bounds to Conditionally Implement Methods

```rust,ignore
impl<T: Display> ToString for T {
    // --snip--
}
```
Because the standard library has this blanket implementation, we can call the
`to_string` method defined by the `ToString` trait on any type that implements
the `Display` trait. For example, we can turn integers into their corresponding
`String` values like this because integers implement `Display`:
```rust
let s = 3.to_string();
```
Blanket implementations appear in the documentation for the trait in the
“Implementors” section.
Traits and trait bounds let us write code that uses generic type parameters to
reduce duplication but also specify to the compiler that we want the generic
type to have particular behavior. The compiler can then use the trait bound
information to check that all the concrete types used with our code provide the
correct behavior. In dynamically typed languages, we would get an error at
runtime if we called a method on a type that didn’t define the method. But Rust
moves these errors to compile time so that we’re forced to fix the problems
before our code is even able to run. Additionally, we don’t have to write code
that checks for behavior at runtime, because we’ve already checked at compile
time. Doing so improves performance without having to give up the flexibility
of generics.


The Rust Programming Language › Validating References with Lifetimes

Lifetimes are another kind of generic that we’ve already been using. Rather
than ensuring that a type has the behavior we want, lifetimes ensure that
references are valid as long as we need them to be.
One detail we didn’t discuss in the “References and
Borrowing” section in Chapter 4 is
that every reference in Rust has a lifetime, which is the scope for which
that reference is valid. Most of the time, lifetimes are implicit and inferred,
just like most of the time, types are inferred. We are only required to
annotate types when multiple types are possible. In a similar way, we must
annotate lifetimes when the lifetimes of references could be related in a few
different ways. Rust requires us to annotate the relationships using generic
lifetime parameters to ensure that the actual references used at runtime will
definitely be valid.
Annotating lifetimes is not even a concept most other programming languages
have, so this is going to feel unfamiliar. Although we won’t cover lifetimes in
their entirety in this chapter, we’ll discuss common ways you might encounter
lifetime syntax so that you can get comfortable with the concept.


The Rust Programming Language › Validating References with Lifetimes › Dangling References

The main aim of lifetimes is to prevent dangling references, which, if they
were allowed to exist, would cause a program to reference data other than the
data it’s intended to reference. Consider the program in Listing 10-16, which
has an outer scope and an inner scope.
Listing 10-16: An attempt to use a reference whose value has gone out of scope
```rust,ignore,does_not_compile
fn main() {
    let r;

    {
        let x = 5;
        r = &x;
    }

    println!("r: {r}");
}
```
Note: The examples in Listings 10-16, 10-17, and 10-23 declare variables
without giving them an initial value, so the variable name exists in the outer
scope. At first glance, this might appear to be in conflict with Rust having
no null values. However, if we try to use a variable before giving it a value,
we’ll get a compile-time error, which shows that indeed Rust does not allow
null values.
The outer scope declares a variable named `r` with no initial value, and the
inner scope declares a variable named `x` with the initial value of `5`. Inside
the inner scope, we attempt to set the value of `r` as a reference to `x`.
Then, the inner scope ends, and we attempt to print the value in `r`. This code
won’t compile, because the value that `r` is referring to has gone out of scope
before we try to use it. Here is the error message:

Validating References with Lifetimes
Dangling References


The Rust Programming Language › Validating References with Lifetimes › Dangling References

```console
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `x` does not live long enough
 --> src/main.rs:6:13
  |
5 |         let x = 5;
  |             - binding `x` declared here
6 |         r = &x;
  |             ^^ borrowed value does not live long enough
7 |     }
  |     - `x` dropped here while still borrowed
8 |
9 |     println!("r: {r}");
  |                   - borrow later used here

For more information about this error, try `rustc --explain E0597`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
```
The error message says that the variable `x` “does not live long enough.” The
reason is that `x` will be out of scope when the inner scope ends on line 7.
But `r` is still valid for the outer scope; because its scope is larger, we say
that it “lives longer.” If Rust allowed this code to work, `r` would be
referencing memory that was deallocated when `x` went out of scope, and
anything we tried to do with `r` wouldn’t work correctly. So, how does Rust
determine that this code is invalid? It uses a borrow checker.


The Rust Programming Language › Validating References with Lifetimes › The Borrow Checker

The Rust compiler has a _borrow checker_ that compares scopes to determine
whether all borrows are valid. Listing 10-17 shows the same code as Listing
10-16 but with annotations showing the lifetimes of the variables.
Listing 10-17: Annotations of the lifetimes of `r` and `x`, named `'a` and `'b`, respectively
```rust,ignore,does_not_compile
fn main() {
    let r;                // ---------+-- 'a
                          //          |
    {                     //          |
        let x = 5;        // -+-- 'b  |
        r = &x;           //  |       |
    }                     // -+       |
                          //          |
    println!("r: {r}");   //          |
}                         // ---------+
```
Here, we’ve annotated the lifetime of `r` with `'a` and the lifetime of `x`
with `'b`. As you can see, the inner `'b` block is much smaller than the outer
`'a` lifetime block. At compile time, Rust compares the size of the two
lifetimes and sees that `r` has a lifetime of `'a` but that it refers to memory
with a lifetime of `'b`. The program is rejected because `'b` is shorter than
`'a`: The subject of the reference doesn’t live as long as the reference.
Listing 10-18 fixes the code so that it doesn’t have a dangling reference and
it compiles without any errors.
Listing 10-18: A valid reference because the data has a longer lifetime than the reference

Validating References with Lifetimes
The Borrow Checker


The Rust Programming Language › Validating References with Lifetimes › The Borrow Checker

```rust
fn main() {
    let x = 5;            // ----------+-- 'b
                          //           |
    let r = &x;           // --+-- 'a  |
                          //   |       |
    println!("r: {r}");   //   |       |
                          // --+       |
}                         // ----------+
```
Here, `x` has the lifetime `'b`, which in this case is larger than `'a`. This
means `r` can reference `x` because Rust knows that the reference in `r` will
always be valid while `x` is valid.
Now that you know where the lifetimes of references are and how Rust analyzes
lifetimes to ensure that references will always be valid, let’s explore generic
lifetimes in function parameters and return values.


The Rust Programming Language › Validating References with Lifetimes › Generic Lifetimes in Functions

We’ll write a function that returns the longer of two string slices. This
function will take two string slices and return a single string slice. After
we’ve implemented the `longest` function, the code in Listing 10-19 should
print `The longest string is abcd`.
Listing 10-19: A `main` function that calls the `longest` function to find the longer of two string slices (src/main.rs)
```rust,ignore
fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is {result}");
}
```
Note that we want the function to take string slices, which are references,
rather than strings, because we don’t want the `longest` function to take
ownership of its parameters. Refer to “String Slices as
Parameters” in Chapter 4 for more
discussion about why the parameters we use in Listing 10-19 are the ones we
want.
If we try to implement the `longest` function as shown in Listing 10-20, it
won’t compile.
Listing 10-20: An implementation of the `longest` function that returns the longer of two string slices but does not yet compile (src/main.rs)
```rust,ignore,does_not_compile
fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() { x } else { y }
}
```
Instead, we get the following error that talks about lifetimes:

Validating References with Lifetimes
Generic Lifetimes in Functions


The Rust Programming Language › Validating References with Lifetimes › Generic Lifetimes in Functions

```console
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0106]: missing lifetime specifier
 --> src/main.rs:9:33
  |
9 | fn longest(x: &str, y: &str) -> &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 `x` or `y`
help: consider introducing a named lifetime parameter
  |
9 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
  |           ++++     ++          ++          ++

For more information about this error, try `rustc --explain E0106`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
```
The help text reveals that the return type needs a generic lifetime parameter
on it because Rust can’t tell whether the reference being returned refers to
`x` or `y`. Actually, we don’t know either, because the `if` block in the body
of this function returns a reference to `x` and the `else` block returns a
reference to `y`!


The Rust Programming Language › Validating References with Lifetimes › Generic Lifetimes in Functions

When we’re defining this function, we don’t know the concrete values that will
be passed into this function, so we don’t know whether the `if` case or the
`else` case will execute. We also don’t know the concrete lifetimes of the
references that will be passed in, so we can’t look at the scopes as we did in
Listings 10-17 and 10-18 to determine whether the reference we return will
always be valid. The borrow checker can’t determine this either, because it
doesn’t know how the lifetimes of `x` and `y` relate to the lifetime of the
return value. To fix this error, we’ll add generic lifetime parameters that
define the relationship between the references so that the borrow checker can
perform its analysis.


The Rust Programming Language › Validating References with Lifetimes › Lifetime Annotation Syntax

Lifetime annotations don’t change how long any of the references live. Rather,
they describe the relationships of the lifetimes of multiple references to each
other without affecting the lifetimes. Just as functions can accept any type
when the signature specifies a generic type parameter, functions can accept
references with any lifetime by specifying a generic lifetime parameter.
Lifetime annotations have a slightly unusual syntax: The names of lifetime
parameters must start with an apostrophe (`'`) and are usually all lowercase
and very short, like generic types. Most people use the name `'a` for the first
lifetime annotation. We place lifetime parameter annotations after the `&` of a
reference, using a space to separate the annotation from the reference’s type.
Here are some examples—a reference to an `i32` without a lifetime parameter, a
reference to an `i32` that has a lifetime parameter named `'a`, and a mutable
reference to an `i32` that also has the lifetime `'a`:
```rust,ignore
&i32        // a reference
&'a i32     // a reference with an explicit lifetime
&'a mut i32 // a mutable reference with an explicit lifetime
```
One lifetime annotation by itself doesn’t have much meaning, because the
annotations are meant to tell Rust how generic lifetime parameters of multiple
references relate to each other. Let’s examine how the lifetime annotations
relate to each other in the context of the `longest` function.

Validating References with Lifetimes
Lifetime Annotation Syntax


The Rust Programming Language › Validating References with Lifetimes › In Function Signatures

To use lifetime annotations in function signatures, we need to declare the
generic lifetime parameters inside angle brackets between the function name and
the parameter list, just as we did with generic type parameters.
We want the signature to express the following constraint: The returned
reference will be valid as long as both of the parameters are valid. This is
the relationship between lifetimes of the parameters and the return value.
We’ll name the lifetime `'a` and then add it to each reference, as shown in
Listing 10-21.
Listing 10-21: The `longest` function definition specifying that all the references in the signature must have the same lifetime `'a` (src/main.rs)
```rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
```
This code should compile and produce the result we want when we use it with the
`main` function in Listing 10-19.
The function signature now tells Rust that for some lifetime `'a`, the function
takes two parameters, both of which are string slices that live at least as
long as lifetime `'a`. The function signature also tells Rust that the string
slice returned from the function will live at least as long as lifetime `'a`.
In practice, it means that the lifetime of the reference returned by the
`longest` function is the same as the smaller of the lifetimes of the values
referred to by the function arguments. These relationships are what we want
Rust to use when analyzing this code.

Validating References with Lifetimes
In Function Signatures


The Rust Programming Language › Validating References with Lifetimes › In Function Signatures

Remember, when we specify the lifetime parameters in this function signature,
we’re not changing the lifetimes of any values passed in or returned. Rather,
we’re specifying that the borrow checker should reject any values that don’t
adhere to these constraints. Note that the `longest` function doesn’t need to
know exactly how long `x` and `y` will live, only that some scope can be
substituted for `'a` that will satisfy this signature.
When annotating lifetimes in functions, the annotations go in the function
signature, not in the function body. The lifetime annotations become part of
the contract of the function, much like the types in the signature. Having
function signatures contain the lifetime contract means the analysis the Rust
compiler does can be simpler. If there’s a problem with the way a function is
annotated or the way it is called, the compiler errors can point to the part of
our code and the constraints more precisely. If, instead, the Rust compiler
made more inferences about what we intended the relationships of the lifetimes
to be, the compiler might only be able to point to a use of our code many steps
away from the cause of the problem.
When we pass concrete references to `longest`, the concrete lifetime that is
substituted for `'a` is the part of the scope of `x` that overlaps with the
scope of `y`. In other words, the generic lifetime `'a` will get the concrete
lifetime that is equal to the smaller of the lifetimes of `x` and `y`. Because
we’ve annotated the returned reference with the same lifetime parameter `'a`,
the returned reference will also be valid for the length of the smaller of the
lifetimes of `x` and `y`.
Let’s look at how the lifetime annotations restrict the `longest` function by
passing in references that have different concrete lifetimes. Listing 10-22 is
a straightforward example.


The Rust Programming Language › Validating References with Lifetimes › In Function Signatures

Listing 10-22: Using the `longest` function with references to `String` values that have different concrete lifetimes (src/main.rs)
```rust
fn main() {
    let string1 = String::from("long string is long");

    {
        let string2 = String::from("xyz");
        let result = longest(string1.as_str(), string2.as_str());
        println!("The longest string is {result}");
    }
}
```
In this example, `string1` is valid until the end of the outer scope, `string2`
is valid until the end of the inner scope, and `result` references something
that is valid until the end of the inner scope. Run this code and you’ll see
that the borrow checker approves; it will compile and print `The longest string
is long string is long`.
Next, let’s try an example that shows that the lifetime of the reference in
`result` must be the smaller lifetime of the two arguments. We’ll move the
declaration of the `result` variable outside the inner scope but leave the
assignment of the value to the `result` variable inside the scope with
`string2`. Then, we’ll move the `println!` that uses `result` to outside the
inner scope, after the inner scope has ended. The code in Listing 10-23 will
not compile.
Listing 10-23: Attempting to use `result` after `string2` has gone out of scope (src/main.rs)
```rust,ignore,does_not_compile
fn main() {
    let string1 = String::from("long string is long");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
    }
    println!("The longest string is {result}");
}
```
When we try to compile this code, we get this error:


The Rust Programming Language › Validating References with Lifetimes › In Function Signatures

```console
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `string2` does not live long enough
 --> src/main.rs:6:44
  |
5 |         let string2 = String::from("xyz");
  |             ------- binding `string2` declared here
6 |         result = longest(string1.as_str(), string2.as_str());
  |                                            ^^^^^^^ borrowed value does not live long enough
7 |     }
  |     - `string2` dropped here while still borrowed
8 |     println!("The longest string is {result}");
  |                                      ------ borrow later used here

For more information about this error, try `rustc --explain E0597`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
```
The error shows that for `result` to be valid for the `println!` statement,
`string2` would need to be valid until the end of the outer scope. Rust knows
this because we annotated the lifetimes of the function parameters and return
values using the same lifetime parameter `'a`.
As humans, we can look at this code and see that `string1` is longer than
`string2`, and therefore, `result` will contain a reference to `string1`.
Because `string1` has not gone out of scope yet, a reference to `string1` will
still be valid for the `println!` statement. However, the compiler can’t see
that the reference is valid in this case. We’ve told Rust that the lifetime of
the reference returned by the `longest` function is the same as the smaller of
the lifetimes of the references passed in. Therefore, the borrow checker
disallows the code in Listing 10-23 as possibly having an invalid reference.


The Rust Programming Language › Validating References with Lifetimes › In Function Signatures

Try designing more experiments that vary the values and lifetimes of the
references passed in to the `longest` function and how the returned reference
is used. Make hypotheses about whether or not your experiments will pass the
borrow checker before you compile; then, check to see if you’re right!


The Rust Programming Language › Validating References with Lifetimes › Relationships

The way in which you need to specify lifetime parameters depends on what your
function is doing. For example, if we changed the implementation of the
`longest` function to always return the first parameter rather than the longest
string slice, we wouldn’t need to specify a lifetime on the `y` parameter. The
following code will compile:
Listing (src/main.rs)
```rust
fn longest<'a>(x: &'a str, y: &str) -> &'a str {
    x
}
```
We’ve specified a lifetime parameter `'a` for the parameter `x` and the return
type, but not for the parameter `y`, because the lifetime of `y` does not have
any relationship with the lifetime of `x` or the return value.
When returning a reference from a function, the lifetime parameter for the
return type needs to match the lifetime parameter for one of the parameters. If
the reference returned does _not_ refer to one of the parameters, it must refer
to a value created within this function. However, this would be a dangling
reference because the value will go out of scope at the end of the function.
Consider this attempted implementation of the `longest` function that won’t
compile:
Listing (src/main.rs)
```rust,ignore,does_not_compile
fn longest<'a>(x: &str, y: &str) -> &'a str {
    let result = String::from("really long string");
    result.as_str()
}
```
Here, even though we’ve specified a lifetime parameter `'a` for the return
type, this implementation will fail to compile because the return value
lifetime is not related to the lifetime of the parameters at all. Here is the
error message we get:

Validating References with Lifetimes
Relationships


The Rust Programming Language › Validating References with Lifetimes › Relationships

```console
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0515]: cannot return value referencing local variable `result`
  --> src/main.rs:11:5
   |
11 |     result.as_str()
   |     ------^^^^^^^^^
   |     |
   |     returns a value referencing data owned by the current function
   |     `result` is borrowed here

For more information about this error, try `rustc --explain E0515`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
```
The problem is that `result` goes out of scope and gets cleaned up at the end
of the `longest` function. We’re also trying to return a reference to `result`
from the function. There is no way we can specify lifetime parameters that
would change the dangling reference, and Rust won’t let us create a dangling
reference. In this case, the best fix would be to return an owned data type
rather than a reference so that the calling function is then responsible for
cleaning up the value.
Ultimately, lifetime syntax is about connecting the lifetimes of various
parameters and return values of functions. Once they’re connected, Rust has
enough information to allow memory-safe operations and disallow operations that
would create dangling pointers or otherwise violate memory safety.


The Rust Programming Language › Validating References with Lifetimes › In Struct Definitions

So far, the structs we’ve defined all hold owned types. We can define structs
to hold references, but in that case, we would need to add a lifetime
annotation on every reference in the struct’s definition. Listing 10-24 has a
struct named `ImportantExcerpt` that holds a string slice.
Listing 10-24: A struct that holds a reference, requiring a lifetime annotation (src/main.rs)
```rust
struct ImportantExcerpt<'a> {
    part: &'a str,
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().unwrap();
    let i = ImportantExcerpt {
        part: first_sentence,
    };
}
```
This struct has the single field `part` that holds a string slice, which is a
reference. As with generic data types, we declare the name of the generic
lifetime parameter inside angle brackets after the name of the struct so that
we can use the lifetime parameter in the body of the struct definition. This
annotation means an instance of `ImportantExcerpt` can’t outlive the reference
it holds in its `part` field.
The `main` function here creates an instance of the `ImportantExcerpt` struct
that holds a reference to the first sentence of the `String` owned by the
variable `novel`. The data in `novel` exists before the `ImportantExcerpt`
instance is created. In addition, `novel` doesn’t go out of scope until after
the `ImportantExcerpt` goes out of scope, so the reference in the
`ImportantExcerpt` instance is valid.

Validating References with Lifetimes
In Struct Definitions


The Rust Programming Language › Validating References with Lifetimes › Lifetime Elision

You’ve learned that every reference has a lifetime and that you need to specify
lifetime parameters for functions or structs that use references. However, we
had a function in Listing 4-9, shown again in Listing 10-25, that compiled
without lifetime annotations.
Listing 10-25: A function we defined in Listing 4-9 that compiled without lifetime annotations, even though the parameter and return type are references (src/lib.rs)
```rust
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}
```
The reason this function compiles without lifetime annotations is historical:
In early versions (pre-1.0) of Rust, this code wouldn’t have compiled, because
every reference needed an explicit lifetime. At that time, the function
signature would have been written like this:
```rust,ignore
fn first_word<'a>(s: &'a str) -> &'a str {
```
After writing a lot of Rust code, the Rust team found that Rust programmers
were entering the same lifetime annotations over and over in particular
situations. These situations were predictable and followed a few deterministic
patterns. The developers programmed these patterns into the compiler’s code so
that the borrow checker could infer the lifetimes in these situations and
wouldn’t need explicit annotations.
This piece of Rust history is relevant because it’s possible that more
deterministic patterns will emerge and be added to the compiler. In the future,
even fewer lifetime annotations might be required.

Validating References with Lifetimes
Lifetime Elision


The Rust Programming Language › Validating References with Lifetimes › Lifetime Elision

The patterns programmed into Rust’s analysis of references are called the
_lifetime elision rules_. These aren’t rules for programmers to follow; they’re
a set of particular cases that the compiler will consider, and if your code
fits these cases, you don’t need to write the lifetimes explicitly.
The elision rules don’t provide full inference. If there is still ambiguity
about what lifetimes the references have after Rust applies the rules, the
compiler won’t guess what the lifetime of the remaining references should be.
Instead of guessing, the compiler will give you an error that you can resolve
by adding the lifetime annotations.
Lifetimes on function or method parameters are called _input lifetimes_, and
lifetimes on return values are called _output lifetimes_.
The compiler uses three rules to figure out the lifetimes of the references
when there aren’t explicit annotations. The first rule applies to input
lifetimes, and the second and third rules apply to output lifetimes. If the
compiler gets to the end of the three rules and there are still references for
which it can’t figure out lifetimes, the compiler will stop with an error.
These rules apply to `fn` definitions as well as `impl` blocks.
The first rule is that the compiler assigns a lifetime parameter to each
parameter that’s a reference. In other words, a function with one parameter
gets one lifetime parameter: `fn foo<'a>(x: &'a i32)`; a function with two
parameters gets two separate lifetime parameters: `fn foo<'a, 'b>(x: &'a i32,
y: &'b i32)`; and so on.
The second rule is that, if there is exactly one input lifetime parameter, that
lifetime is assigned to all output lifetime parameters: `fn foo<'a>(x: &'a i32)
-> &'a i32`.