Merge pull request #436 from rust-lang/ch10-edits

Ready for review: revisions to ch 10
This commit is contained in:
Carol (Nichols || Goulding)
2017-02-20 11:00:20 -05:00
committed by GitHub
7 changed files with 3129 additions and 1709 deletions
+10
View File
@@ -5,6 +5,7 @@ abcdefghijklmnopqrstuvwxyz
adaptor adaptor
adaptors adaptors
Addr Addr
aggregator
aliasability aliasability
alignof alignof
Amir Amir
@@ -69,6 +70,7 @@ Dobrý
doccargo doccargo
doccratesio doccratesio
doesn doesn
ebooks
Edsger Edsger
else's else's
emoji emoji
@@ -110,8 +112,10 @@ Hoare
Hola Hola
homogenous homogenous
html html
Iceburgh
IEEE IEEE
impl impl
ImportantExcerpt
indices indices
init init
instantiation instantiation
@@ -146,6 +150,7 @@ Metadata
metaprogramming metaprogramming
mibbit mibbit
Mibbit Mibbit
mixup
mkdir mkdir
modifiability modifiability
monomorphization monomorphization
@@ -158,6 +163,7 @@ namespaced
namespaces namespaces
namespacing namespacing
newfound newfound
NewsArticle
newtype newtype
nocapture nocapture
nomicon nomicon
@@ -196,6 +202,7 @@ refactor
refactoring refactoring
RefCell RefCell
repr repr
retweet
ripgrep ripgrep
runtime runtime
Rustacean Rustacean
@@ -237,6 +244,7 @@ Submodules
suboptimal suboptimal
subtree subtree
subtyping subtyping
Summarizable
Supertraits Supertraits
That'd That'd
test's test's
@@ -267,8 +275,10 @@ UsState
utils utils
variable's variable's
vers vers
versa
Versioning Versioning
wasn wasn
WeatherForecast
whitespace whitespace
wildcards wildcards
workspace workspace
+1482 -818
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -45,10 +45,10 @@
- [Recoverable Errors with `Result`](ch09-02-recoverable-errors-with-result.md) - [Recoverable Errors with `Result`](ch09-02-recoverable-errors-with-result.md)
- [To `panic!` or Not To `panic!`](ch09-03-to-panic-or-not-to-panic.md) - [To `panic!` or Not To `panic!`](ch09-03-to-panic-or-not-to-panic.md)
- [Generics](ch10-00-generics.md) - [Generic Types, Traits, and Lifetimes](ch10-00-generics.md)
- [Syntax](ch10-01-syntax.md) - [Generic Data Types](ch10-01-syntax.md)
- [Traits](ch10-02-traits.md) - NEED DEFAULT METHOD IMPLEMENTATIONS - [Traits: Defining Shared Behavior](ch10-02-traits.md)
- [Lifetime syntax](ch10-03-lifetime-syntax.md) - [Validating References with Lifetimes](ch10-03-lifetime-syntax.md)
- [Testing](ch11-00-testing.md) - [Testing](ch11-00-testing.md)
- [Writing tests](ch11-01-writing-tests.md) - [Writing tests](ch11-01-writing-tests.md)
+118 -49
View File
@@ -1,23 +1,47 @@
# Generics # Generic Types, Traits, and Lifetimes
One of the core tools a programming language gives you is the ability to deal Every programming language has tools to deal effectively with duplication of
effectively with duplication of code. It's important to minimize the amount of concepts; in Rust, one of those tools is *generics*. Generics are abstract
code that is duplicated throughout a program to make maintenance easier and stand-ins for concrete types or other properties. We can express properties of
minimize logic errors. Maintenance will be easier if there's only one place generics, such as their behavior or how they relate to other generics, without
that you need to change the code if you change your mind about how the program needing to know when we're writing and compiling the code what will actually be
should work, rather than multiple places in the code. If your program's logic in their place.
is duplicated in different places and those places don't match, you'll get
errors or unexpected and undesired behavior from your program that could be In the same way that a function takes parameters whose value we don't know in
hard to track down. Rust has the concept of *generics* as one way to eliminate order to write code once that will be run on multiple concrete values, we can
duplicate code. Generics come in the form of generic types, traits that those write functions that take parameters of some generic type instead of a concrete
generic types have, and generic lifetimes. We'll cover how to use all of these type like `i32` or `String`. We've already used generics in Chapter 6 with
in this chapter. `Option<T>`, Chapter 8 with `Vec<T>` and `HashMap<K, V>`, and Chapter 9 with
`Result<T, E>`. In this chapter, we'll explore how to define our own types,
functions, and methods with generics!
First, we're going to review the mechanics of extracting a function that
reduces code duplication. Then we'll use the same mechanics to make a generic
function out of two functions that only differ in the types of their
parameters. We'll go over using generic types in struct and enum definitions
too.
After that, we'll discuss *traits*, which are a way to define behavior in a
generic way. Traits can be combined with generic types in order to constrain a
generic type to those types that have a particular behavior, rather than any
type at all.
Finally, we'll discuss *lifetimes*, which are a kind of generic that let us
give the compiler information about how references are related to each other.
Lifetimes are the feature in Rust that allow us to borrow values in many
situations and still have the compiler check that references will be valid.
## Removing Duplication by Extracting a Function ## Removing Duplication by Extracting a Function
Let's first go through a technique for dealing with duplication that you're Before getting into generics syntax, let's first review a technique for dealing
probably familiar with: extracting a function. Consider a small program that with duplication that doesn't use generic types: extracting a function. Once
finds the largest number in a list, shown in Listing 10-1: that's fresh in our minds, we'll use the same mechanics with generics to
extract a generic function! In the same way that you recognize duplicated code
to extract into a function, you'll start to recognize duplicated code that can
use generics.
Consider a small program that finds the largest number in a list, shown in
Listing 10-1:
<figure> <figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -35,6 +59,7 @@ fn main() {
} }
println!("The largest number is {}", largest); println!("The largest number is {}", largest);
# assert_eq!(largest, 100);
} }
``` ```
@@ -45,10 +70,19 @@ Listing 10-1: Code to find the largest number in a list of numbers
</figcaption> </figcaption>
</figure> </figure>
This code takes a list of integers, stored here in the variable `numbers`. It
puts the first item in the list in a variable named `largest`. Then it iterates
through all the numbers in the list, and if the current value is greater than
the number stored in `largest`, it replaces the value in `largest`. If the
current value is smaller than the largest value seen so far, `largest` is not
changed. When all the items in the list have been considered, `largest` will
hold the largest value, which in this case is 100.
If we needed to find the largest number in two different lists of numbers, we If we needed to find the largest number in two different lists of numbers, we
could duplicate the code in Listing 10-1 and have the same logic exist in two could duplicate the code in Listing 10-1 and have the same logic exist in two
places in the program: places in the program, as in Listing 10-2:
<figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
```rust ```rust
@@ -79,56 +113,91 @@ fn main() {
} }
``` ```
Copying code is tedious and error-prone, plus now we have two places to update <figcaption>
the logic if we need it to change. Rust, like many languages, gives us a way to
deal with this duplication by creating an abstraction, and in this case the
abstraction we'll use is a function. Here's a program where we've extracted the
code in Listing 10-1 that finds the largest number into a function named
`largest`. This program can find the largest number in two different lists of
numbers, but the code from Listing 10-1 only exists in one spot:
Listing 10-2: Code to find the largest number in *two* lists of numbers
</figcaption>
</figure>
While this code works, duplicating code is tedious and error-prone, and means
we have multiple places to update the logic if we need to change it.
<!-- Are we safe assuming the reader will be familiar with the term
"abstraction" in this context, or do we want to give a brief definition? -->
<!-- Yes, our audience will be familiar with this term. /Carol -->
To eliminate this duplication, we can create an abstraction, which in this case
will be in the form of a function that operates on any list of integers given
to the function in a parameter. This will increase the clarity of our code and
let us communicate and reason about the concept of finding the largest number
in a list independently of the specific places this concept is used.
In the program in Listing 10-3, we've extracted the code that finds the largest
number into a function named `largest`. This program can find the largest
number in two different lists of numbers, but the code from Listing 10-1 only
exists in one spot:
<figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
```rust ```rust
fn largest(numbers: Vec<i32>) { fn largest(list: &[i32]) -> i32 {
let mut largest = numbers[0]; let mut largest = list[0];
for number in numbers { for &item in list.iter() {
if number > largest { if item > largest {
largest = number; largest = item;
} }
} }
println!("The largest number is {}", largest); largest
} }
fn main() { fn main() {
let numbers = vec![34, 50, 25, 100, 65]; let numbers = vec![34, 50, 25, 100, 65];
largest(numbers); let result = largest(&numbers);
println!("The largest number is {}", result);
# assert_eq!(result, 100);
let numbers = vec![102, 34, 6000, 89, 54, 2, 43, 8]; let numbers = vec![102, 34, 6000, 89, 54, 2, 43, 8];
largest(numbers); let result = largest(&numbers);
println!("The largest number is {}", result);
# assert_eq!(result, 6000);
} }
``` ```
The function defines a parameter, `numbers`, which represents any concrete <figcaption>
`Vec<i32>` that we might pass into the function. The code in the function
definition operates on the `numbers` representation of any `Vec<i32>`. When
we call the `largest` function, the code actually runs on the specific values
that we pass in.
Functions aren't the only way to eliminate duplication. For example, our Listing 10-3: Abstracted code to find the largest number in two lists
`largest` function only works for vectors of `i32`. What if we wanted to find
the largest number in a list of floats? Or the largest value in some sort of
custom `struct` or `enum`? We can't solve those kinds of duplication with
regular functions.
To solve these kinds of problems, Rust provides a feature called *generics*. In </figcaption>
the same way that functions allow us to abstract over common code, generics </figure>
allow us to abstract over types. This ability gives us tremendous power to
write code that works in a large number of situations. First, we'll examine the The function has a parameter, `list`, which represents any concrete slice of
syntax of generics. Then, we'll talk about another feature that's used to `i32` values that we might pass into the function. The code in the function
augment generics: traits. Finally, we'll discuss one of Rust's most unique uses definition operates on the `list` representation of any `&[i32]`. When we call
of generics: lifetimes. the `largest` function, the code actually runs on the specific values that we
pass in.
The mechanics we went through to get from Listing 10-2 to Listing 10-3 were
these steps:
1. We noticed there was duplicate code.
2. We extracted the duplicate code into the body of the function, and specified
the inputs and return values of that code in the function signature.
3. We replaced the two concrete places that had the duplicated code to call the
function instead.
We can use these same steps with generics to reduce code duplication in
different ways in different scenarios. In the same way that the function body
is now operating on an abstract `list` instead of concrete values, code using
generics will operate on abstract types. The concepts powering generics are the
same concepts you already know that power functions, just applied in different
ways.
What if we had two functions, one that found the largest item in a slice of
`i32` values and one that found the largest item in a slice of `char` values?
How would we get rid of that duplication? Let's find out!
+421 -314
View File
@@ -1,171 +1,466 @@
## Generics Syntax ## Generic Data Types
We've already hinted at the idea of generics in previous chapters, but we Using generics where we usually place types, like in function signatures or
never dug into what exactly they are or how to use them. In places where we structs, lets us create definitions that we can use for many different concrete
specify a type, like function signatures or structs, instead we can use data types. Let's take a look at how to define functions, structs, enums, and
*generics*. Generics are stand-ins that represent an abstract set instead of something concrete. In this section, we're going to cover generic *data types*. methods using generics, and at the end of this section we'll discuss the
performance of code using generics.
You can recognize when any kind of generics are used by the way that they fit ### Using Generic Data Types in Function Definitions
into Rust's syntax: any time you see angle brackets, `<>`, you're dealing with
generics. Types we've seen before, like in Chapter 8 where we discussed vectors
with types like `Vec<i32>`, employ generics. The type that the standard library
defines for vectors is `Vec<T>`. That `T` is called a *type parameter*, and it
serves a similar function as parameters to functions: you fill in the parameter
with a concrete type, and that determines how the overall type works. In the
same way that a function like `foo(x: i32)` can be called with a specific value
such as `foo(5)`, a `Vec<T>` can be created with a specific type, like
`Vec<i32>`.
### Duplicated Enum Definitions We can define functions that use generics in the signature of the function
where the data types of the parameters and return value go. In this way, the
code we write can be more flexible and provide more functionality to callers of
our function, while not introducing code duplication.
Let's dive into generic data types in more detail. We learned about how to use Continuing with our `largest` function, Listing 10-4 shows two functions
the `Option<T>` enum in Chapter 6, but we never examined its definition. Let's providing the same functionality to find the largest value in a slice. The
try to imagine how we'd write it! We'll start from duplicated code like we did first function is the one we extracted in Listing 10-3 that finds the largest
in the "Removing Duplication by Extracting a Function" section. This time, `i32` in a slice. The second function finds the largest `char` in a slice:
we'll remove the duplication by extracting a generic data type instead of
extracting a function, but the mechanics of doing the extraction will be
similar. First, let's consider an `Option` enum with a `Some` variant that can
only hold an `i32`. We'll call this enum `OptionalNumber`:
<figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
```rust ```rust
enum OptionalNumber { fn largest_i32(list: &[i32]) -> i32 {
Some(i32), let mut largest = list[0];
None,
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn largest_char(list: &[char]) -> char {
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
} }
fn main() { fn main() {
let number = OptionalNumber::Some(5); let numbers = vec![34, 50, 25, 100, 65];
let no_number = OptionalNumber::None;
let result = largest_i32(&numbers);
println!("The largest number is {}", result);
# assert_eq!(result, 100);
let chars = vec!['y', 'm', 'a', 'q'];
let result = largest_char(&chars);
println!("The largest char is {}", result);
# assert_eq!(result, 'y');
} }
``` ```
This works just fine for `i32`s. But what if we also wanted to store `f64`s? We <figcaption>
would have to duplicate code to define a separate `Option` enum type for each
type we wanted to be able to hold in the `Some` variants. For example, here is
how we could define and use `OptionalFloatingPointNumber`:
Listing 10-4: Two functions that differ only in their names and the types in
their signatures
</figcaption>
</figure>
Here, the functions `largest_i32` and `largest_char` have the exact same body,
so it would be nice if we could turn these two functions into one and get rid
of the duplication. Luckily, we can do that by introducing a generic type
parameter!
To parameterize the types in the signature of the one function we're going to
define, we need to create a name for the type parameter, just like how we give
names for the value parameters to a function. We're going to choose the name
`T`. Any identifier can be used as a type parameter name, but we're choosing
`T` because Rust's type naming convention is CamelCase. Generic type parameter
names also tend to be short by convention, often just one letter. 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 in the signature so that the compiler knows what that name in the
body 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. Type
name declarations go in angle brackets between the name of the function and the
parameter list.
The function signature of the generic `largest` function we're going to define
will look like this:
```rust,ignore
fn largest<T>(list: &[T]) -> T {
```
We would read this as: the function `largest` is generic over some type `T`. It
has one parameter named `list`, and the type of `list` is a slice of values of
type `T`. The `largest` function will return a value of the same type `T`.
Listing 10-5 shows the unified `largest` function definition using the generic
data type in its signature, and shows how we'll be able to call `largest` with
either a slice of `i32` values or `char` values. Note that this code won't
compile yet!
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
fn largest<T>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
let numbers = vec![34, 50, 25, 100, 65];
let result = largest(&numbers);
println!("The largest number is {}", result);
let chars = vec!['y', 'm', 'a', 'q'];
let result = largest(&chars);
println!("The largest char is {}", result);
}
```
<figcaption>
Listing 10-5: A definition of the `largest` function that uses generic type
parameters but doesn't compile yet
</figcaption>
</figure>
If we try to compile this code right now, we'll get this error:
```text
error[E0369]: binary operation `>` cannot be applied to type `T`
|
5 | if item > largest {
| ^^^^
|
note: an implementation of `std::cmp::PartialOrd` might be missing for `T`
```
The note mentions `std::cmp::PartialOrd`, which is a *trait*. We're going to
talk about traits in the next section, but briefly, what this error is saying
is that the body of `largest` won't work for all possible types that `T` could
be; since we want to compare values of type `T` in the body, we can only use
types that know how to be ordered. The standard library has defined the trait
`std::cmp::PartialOrd` that types can implement to enable comparisons. We'll
come back to traits and how to specify that a generic type has a particular
trait in the next section, but let's set this example aside for a moment and
explore other places we can use generic type parameters first.
<!-- Liz: this is the reason we had the topics in the order we did in the first
draft of this chapter; it's hard to do anything interesting with generic types
in functions unless you also know about traits and trait bounds. I think this
ordering could work out okay, though, and keep a stronger thread with the
`longest` function going through the whole chapter, but we do pause with a
not-yet-compiling example here, which I know isn't ideal either. Let us know
what you think. /Carol -->
### Using Generic Data Types in Struct Definitions
We can define structs to use a generic type parameter in one or more of the
struct's fields with the `<>` syntax too. Listing 10-6 shows the definition and
use of a `Point` struct that can hold `x` and `y` coordinate values of any type:
<figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
```rust ```rust
enum OptionalFloatingPointNumber { struct Point<T> {
Some(f64), x: T,
None, y: T,
} }
fn main() { fn main() {
let number = OptionalFloatingPointNumber::Some(5.0); let integer = Point { x: 5, y: 10 };
let no_number = OptionalFloatingPointNumber::None; let float = Point { x: 1.0, y: 4.0 };
} }
``` ```
We've made the enum's name a bit long in order to drive the point home. With <figcaption>
what we currently know how to do in Rust, we would have to write a unique type
for every single kind of value we wanted to have either `Some` or `None` of. In
other words, the idea of "an optional value" is a more abstract concept than one
specific type. We want it to work for any type at all.
### Removing Duplication by Extracting a Generic Data Type Listing 10-6: A `Point` struct that holds `x` and `y` values of type `T`
Let's see how to get from duplicated types to the generic type. Here are the </figcaption>
definitions of our two enums side-by-side: </figure>
```text The syntax is similar to using generics in function definitions. First, we have
enum OptionalNumber { enum OptionalFloatingPointNumber { to declare the name of the type parameter within angle brackets just after the
Some(i32), Some(f64), name of the struct. Then we can use the generic type in the struct definition
None, None, where we would specify concrete data types.
} }
Note that because we've only used one generic type in the definition of
`Point`, what we're saying is that the `Point` struct is generic over some type
`T`, and the fields `x` and `y` are *both* that same type, whatever it ends up
being. If we try to create an instance of a `Point` that has values of
different types, as in Listing 10-7, our code won't compile:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
struct Point<T> {
x: T,
y: T,
}
fn main() {
let wont_work = Point { x: 5, y: 4.0 };
}
``` ```
Aside from the names, we have one line where the two definitions are very <figcaption>
close, but still different: the line with the `Some` definitions. The only
difference is the type of the data in that variant, `i32` and `f64`.
Just like we can parameterize arguments to a function by choosing a name, we Listing 10-7: The fields `x` and `y` must be the same type because both have
can parameterize the type by choosing a name. In this case, we've chosen the the same generic data type `T`
name `T`. We could choose any identifier here, but Rust style has type
parameters follow the same style as types themselves: CamelCase. In addition, </figcaption>
they tend to be short, often one letter. `T` is the traditional default choice, </figure>
short for 'type'. Let's use that name in our `Some` variant definitions where
the `i32` and `f64` types were: If we try to compile this, we'll get the following error:
```text ```text
enum OptionalNumber { enum OptionalFloatingPointNumber { error[E0308]: mismatched types
Some(T), Some(T), -->
None, None, |
} } 7 | let wont_work = Point { x: 5, y: 4.0 };
| ^^^ expected integral variable, found
floating-point variable
|
= note: expected type `{integer}`
= note: found type `{float}`
``` ```
There's one problem, though: we've *used* `T`, but not defined it. This would When we assigned the integer value 5 to `x`, the compiler then knows for this
be similar to using a parameter name in a function body without declaring it instance of `Point` that the generic type `T` will be an integer. Then when we
in the signature. We need to tell Rust that we've introduced a generic specified 4.0 for `y`, which is defined to have the same type as `x`, we get a
parameter. The syntax to do that is the angle brackets, like this: type mismatch error.
```text If we wanted to define a `Point` struct where `x` and `y` could have different
enum OptionalNumber<T> { enum OptionalFloatingPointNumber<T> { types but still have those types be generic, we can use multiple generic type
Some(T), Some(T), parameters. In listing 10-8, we've changed the definition of `Point` to be
None, None, generic over types `T` and `U`. The field `x` is of type `T`, and the field `y`
} } is of type `U`:
```
The `<>`s after the enum name indicate a list of type parameters, just like <figure>
`()` after a function name indicates a list of value parameters. Now the only <span class="filename">Filename: src/main.rs</span>
difference between our two `enum`s is the name. Since we've made them generic,
they're not specific to integers or floating point numbers anymore, so they can
have the same name:
```text
enum Option<T> { enum Option<T> {
Some(T), Some(T),
None, None,
} }
```
Now they're identical! We've made our type fully generic. This definition is
also how `Option` is defined in the standard library. If we were to read this
definition aloud, we'd say, "`Option` is an `enum` with one type parameter,
`T`. It has two variants: `Some`, which has a value with type `T`, and `None`,
which has no value." We can now use the same `Option` type whether we're holding an `i32` or an `f64`:
```rust ```rust
let integer = Option::Some(5); struct Point<T, U> {
let float = Option::Some(5.0); 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 };
}
``` ```
We've left in the `Option::` namespace for consistency with the previous <figcaption>
examples, but since `use Option::*` is in the prelude, it's not needed. Usually
using `Option` looks like this: Listing 10-8: A `Point` generic over two types so that `x` and `y` may be
values of different types
</figcaption>
</figure>
Now all of these instances of `Point` are allowed! You can use as many generic
type parameters in a definition as you want, but using more than a few gets
hard to read and understand. If you get to a point of needing lots of generic
types, it's probably a sign that your code could use some restructuring to be
separated into smaller pieces.
### Using Generic Data Types in Enum Definitions
Similarly to structs, enums can be defined to hold generic data types in their
variants. We used the `Option<T>` enum provided by the standard library in
Chapter 6, and now its definition should make more sense. Let's take another
look:
```rust
enum Option<T> {
Some(T),
None,
}
```
In other words, `Option<T>` is an enum generic in type `T`. It has two
variants: `Some`, which holds one value of type `T`, and a `None` variant that
doesn't hold any value. The standard library only has to have this one
definition to support the creation of values of this enum that have any
concrete type. The idea of "an optional value" is a more abstract concept than
one specific type, and Rust lets us express this abstract concept without lots
of duplication.
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`. `Result` 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 (and return a value of some
type `T`) or fail (and return an error of some type `E`). Recall Listing 9-2
when we opened a file: in that case, `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.
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
remove the duplication by using the same process we used with the function
definitions to introduce generic types instead.
### Using Generic Data Types in Method Definitions
Like we did in Chapter 5, we can implement methods on structs and enums that
have generic types in their definitions. Listing 10-9 shows the `Point<T>`
struct we defined in Listing 10-6. We've then defined a method named `x` on
`Point<T>` that returns a reference to the data in the field `x`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```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());
}
```
<figcaption>
Listing 10-9: Implementing a method named `x` on the `Point<T>` struct that
will return a reference to the `x` field, which is of type `T`.
</figcaption>
</figure>
Note that we have to declare `T` just after `impl`, so that we can use it when
we specify that we're implementing methods on the type `Point<T>`.
Generic type parameters in a struct definition aren't always the same generic
type parameters you want to use in that struct's method signatures. Listing
10-10 defines a method `mixup` on the `Point<T, U>` struct from Listing 10-8.
The method takes another `Point` as a parameter, which might have different
types than the `self` `Point` that we're calling `mixup` on. The method creates
a new `Point` instance that has the `x` value from the `self` `Point` (which is
of type `T`) and the `y` value from the passed-in `Point` (which is of type
`W`):
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
struct Point<T, U> {
x: T,
y: U,
}
impl<T, U> Point<T, U> {
fn mixup<V, W>(&self, other: &Point<V, W>) -> Point<T, W> {
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);
}
```
<figcaption>
Listing 10-10: Methods that use different generic types than their struct's
definition
</figcaption>
</figure>
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`). `p2` is a `Point` 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`, since `x` came from `p1`. `p3` will have a `char` for `y`,
since `y` came from `p2`. The `println!` will print `p3.x = 5, p3.y = c`.
Note that the generic parameters `T` and `U` are declared after `impl`, since
they go with the struct definition. The generic parameters `V` and `W` are
declared after `fn mixup`, since they are only relevant to the method.
### Performance of Code Using Generics
You may have been reading this section and wondering if there's a run-time cost
to using generic type parameters. Good news: the way that Rust has implemented
generics means that your code will not run any slower than if you had specified
concrete types instead of generic type parameters!
Rust accomplishes this by performing *monomorphization* of code using generics
at compile time. Monomorphization is the process of turning generic code into
specific code with the concrete types that are actually used filled in.
What the compiler does is the opposite of the steps that we performed to create
the generic function in Listing 10-5. The compiler looks at all the places that
generic code is called and generates code for the concrete types that the
generic code is called with.
Let's work through an example that uses the standard library's `Option` enum:
```rust ```rust
let integer = Some(5); let integer = Some(5);
let float = Some(5.0); let float = Some(5.0);
``` ```
When you recognize situations with almost-duplicate types like this in your When Rust compiles this code, it will perform monomorphization. The compiler
code, you can follow this process to reduce duplication using generics. will read the values that have been passed to `Option` and see that we have two
kinds of `Option<T>`: one is `i32`, and one is `f64`. As such, it will expand
the generic definition of `Option<T>` into `Option_i32` and `Option_f64`,
thereby replacing the generic definition with the specific ones.
### Monomorphization at Compile Time The monomorphized version of our code that the compiler generates looks like
this, with the uses of the generic `Option` replaced with the specific
Understanding this refactoring process is also useful in understanding how definitions created by the compiler:
generics work behind the scenes: the compiler does the exact opposite of this
process when compiling your code. *Monomorphization* means taking code that
uses generic type parameters and generating code that is specific for each
concrete type that is used with the generic code. Monomorphization is why
Rust's generics are extremely efficient at runtime. Consider this code that
uses the standard library's `Option`:
```rust
let integer = Some(5);
let float = Some(5.0);
```
When Rust compiles this code, it will perform monomorphization. What this means
is the compiler will see that we've used two kinds of `Option<T>`: one where
`T` is `i32`, and one where `T` is `f64`. As such, it will expand the generic
definition of `Option<T>` into `Option_i32` and `Option_f64`, thereby replacing
the generic definition with the specific ones. The more specific version looks
like the duplicated code we started with at the beginning of this section:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -186,196 +481,8 @@ fn main() {
} }
``` ```
In other words, we can write the non-duplicated form that uses generics in our We can write the non-duplicated code using generics, and Rust will compile that
code, but Rust will compile that into code that acts as though we wrote the into code that specifies the type in each instance. That means we pay no
specific type out in each instance. This means we pay no runtime cost for using runtime cost for using generics; when the code runs, it performs just like it
generics; it's just like we duplicated each particular definition. would if we had duplicated each particular definition by hand. The process of
monomorphization is what makes Rust's generics extremely efficient at runtime.
### Generic Structs
In a similar fashion as we did with enums, we can use `<>`s with structs as
well in order to define structs that have a generic type parameter in one or
more of their fields. Generic structs also get monomorphized into specialized
types at compile time. Listing 10-2 shows the definition and use of a `Point`
struct that could hold `x` and `y` coordinate values that are any type:
<figure>
<span class="filename">Filename: src/main.rs</span>
```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 };
}
```
<figcaption>
Listing 10-2: A `Point` struct that holds `x` and `y` values of type `T`
</figcaption>
</figure>
The syntax is the same with structs: add a `<T>` after the name of the struct,
then use `T` in the definition where you want to use that generic type instead
of a specific type.
### Multiple Type Parameters
Note that in the `Point` definition in Listing 10-2, we've used the same `T`
parameter for both fields. This means `x` and `y` must always be values of the
same type. Trying to instantiate a `Point` that uses an `i32` for `x` and an
`f64` for `y`, like this:
```rust,ignore
let p = Point { x: 5, y: 20.0 };
```
results in a compile-time error that indicates the type of `y` must match the
type of `x`:
```text
error[E0308]: mismatched types
|
7 | let p = Point { x: 5, y: 20.0 };
| ^^^^ expected integral variable, found floating-point variable
|
= note: expected type `{integer}`
= note: found type `{float}`
```
If we need to be able to have fields with generic but different types, we can
declare multiple type parameters within the angle brackets, separated by a
comma. Listing 10-3 shows how to define a `Point` that can have different types
for `x` and `y`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
struct Point<X, Y> {
x: X,
y: Y,
}
fn main() {
let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };
let p = Point { x: 5, y: 20.0 };
}
```
<figcaption>
Listing 10-3: A `Point` struct that holds an `x` value of type `X` and a `y`
value of type `Y`
</figcaption>
</figure>
Now `x` will have the type of `X`, and `y` will have the type of `Y`, and we
can instantiate a `Point` with an `i32` for `x` and an `f64` for `y`.
We can make `enum`s with multiple type parameters as well. Recall the enum
`Result<T, E>` from Chapter 9 that we used for recoverable errors. Here's its
definition:
```rust
enum Result<T, E> {
Ok(T),
Err(E),
}
```
Each variant stores a different kind of information, and they're both generic.
You can have as many type parameters as you'd like. Similarly to parameters of
values in function signatures, if you have a lot of parameters, the code can
get quite confusing, so try to keep the number of parameters defined in any one
type small if you can.
### Generic Functions and Methods
In a similar way to data structures, we can use the `<>` syntax in function or
method definitions. The angle brackets for type parameters go after the
function or method name and before the parameter list in parentheses:
```rust
fn generic_function<T>(value: T) {
// code goes here
}
```
We can use the same process that we used to refactor duplicated type
definitions using generics to refactor duplicated function definitions using
generics. Consider these two side-by-side function signatures that differ in
the type of `value`:
```text
fn takes_integer(value: i32) { fn takes_float(value: f64) {
// code goes here // code goes here
} }
```
We can add a type parameter list that declares the generic type `T` after the
function names, then use `T` where the specific `i32` and `f64` types were:
```text
fn takes_integer<T>(value: T) { fn takes_float<T>(value: T) {
// code goes here // code goes here
} }
```
At this point, only the names differ, so we could unify the two functions into
one:
```rust,ignore
fn takes<T>(value: T) {
// code goes here
}
```
There's one problem though. We've got some function *definitions* that work,
but if we try to use `value` in code in the function body, we'll get an
error. For example, the function definition in Listing 10-4 tries to print out
`value` in its body:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust,ignore
fn show_anything<T>(value: T) {
println!("I have something to show you!");
println!("It's: {}", value);
}
```
<figcaption>
Listing 10-4: A `show_anything` function definition that does not yet compile
</figcaption>
</figure>
Compiling this definition results in an error:
```text
error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
--> <anon>:3:37
|
3 | println!("It's: {}", value);
| ^^^^^ trait `T: std::fmt::Display` not satisfied
|
= help: consider adding a `where T: std::fmt::Display` bound
= note: required by `std::fmt::Display::fmt`
error: aborting due to previous error(s)
```
This error mentions something we haven't learned about yet: traits. In the next
section, we'll learn how to make this compile.
+447 -250
View File
@@ -1,306 +1,503 @@
## Traits ## Traits: Defining Shared Behavior
*Traits* are similar to a feature often called 'interfaces' in other languages, Traits allow us to use another kind of abstraction: they let us abstract over
but are also different. Traits let us do another kind of abstraction: they let behavior that types can have in common. A *trait* tells the Rust compiler about
us abstract over *behavior* that types can have in common. functionality a particular type has and might share with other types. In
situations where we use generic type parameters, we can use *trait bounds* to
specify, at compile time, that the generic type may be any type that implements
a trait and therefore has the behavior we want to use in that situation.
When we use a generic type parameter, we are telling Rust that any type is > Note: *Traits* are similar to a feature often called 'interfaces' in other
valid in that location. When other code *uses* a value that could be of any > languages, though with some differences.
type, we need to also tell Rust that the type has the functionality that we
need. Traits let us specify that, for example, we need any type `T` that has
methods defined on it that allow us to print a value of that type. This is
powerful because we can still leave our definitions generic to allow use of
many different types, but we can constrain the type at compile-time to types
that have the behavior we need to be able to use.
Listing 10-5 has an example definition of a trait named `Printable` with a ### Defining a Trait
method named `print`:
The behavior of a type 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
in order to define a set of behaviors necessary to accomplish some purpose.
For example, 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
place in the world, and a `Tweet` that can have at most 140 characters in its
content along with metadata like whether it was a retweet or a reply to another
tweet.
We want to make a media aggregator library that can display summaries of data
that might be stored in a `NewsArticle` or `Tweet` instance. The behavior we
need each struct to have is that it's able to be summarized, and that we can
ask for that summary by calling a `summary` method on an instance. Listing
10-11 shows the definition of a `Summarizable` trait that expresses this
concept:
<figure> <figure>
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: lib.rs</span>
```rust ```rust
trait Printable { pub trait Summarizable {
fn print(&self); fn summary(&self) -> String;
} }
``` ```
<figcaption> <figcaption>
Listing 10-5: A `Printable` trait definition with one method, `print` Listing 10-11: Definition of a `Summarizable` trait that consists of the
behavior provided by a `summary` method
</figcaption> </figcaption>
</figure> </figure>
We declare a trait with the `trait` keyword, then the trait's name. In this We declare a trait with the `trait` keyword, then the trait's name, in this
case, our trait will describe types which can be printed. Inside of curly case `Summarizable`. Inside curly braces we declare the method signatures that
braces, we declare a method signature, but instead of providing an describe the behaviors that types that implement this trait will need to have,
implementation inside curly braces, we put a semicolon after the signature. A in this case `fn summary(&self) -> String`. After the method signature, instead
trait can have multiple methods in its body, with the method signatures listed of providing an implementation within curly braces, we put a semicolon. Each
one per line and each line ending in a semicolon. type that implements this trait must then provide its own custom behavior for
the body of the method, but the compiler will enforce that any type that has
the `Summarizable` trait will have the method `summary` defined for it with
this signature exactly.
Implementing a trait for a particular type looks similar to implementing A trait can have multiple methods in its body, with the method signatures
methods on a type since it's also done with the `impl` keyword, but we specify listed one per line and each line ending in a semicolon.
the trait name as well. Inside the `impl` block, we specify definitions for the
trait's methods in the context of the specific type. Listing 10-6 has an ### Implementing a Trait on a Type
example of implementing the `Printable` trait from Listing 10-5 (that only has
the `print` method) for a `Temperature` enum: Now that we've defined the `Summarizable` trait, we can implement it on the
types in our media aggregator that we want to have this behavior. Listing 10-12
shows an implementation of the `Summarizable` trait on the `NewsArticle` struct
that uses the headline, the author, and the location to create the return value
of `summary`. For the `Tweet` struct, we've chosen to define `summary` as the
username followed by the whole text of the tweet, assuming that tweet content
is already limited to 140 characters.
<figure> <figure>
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: lib.rs</span>
```rust ```rust
# trait Printable { # pub trait Summarizable {
# fn print(&self); # fn summary(&self) -> String;
# } # }
# #
enum Temperature { pub struct NewsArticle {
Celsius(i32), pub headline: String,
Fahrenheit(i32), pub location: String,
pub author: String,
pub content: String,
} }
impl Printable for Temperature { impl Summarizable for NewsArticle {
fn print(&self) { fn summary(&self) -> String {
match *self { format!("{}, by {} ({})", self.headline, self.author, self.location)
Temperature::Celsius(val) => println!("{}°C", val), }
Temperature::Fahrenheit(val) => println!("{}°F", val), }
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summarizable for Tweet {
fn summary(&self) -> String {
format!("{}: {}", self.username, self.content)
} }
} }
``` ```
<figcaption> <figcaption>
Listing 10-6: Implementing the `Printable` trait on a `Temperature` enum Listing 10-12: Implementing the `Summarizable` trait on the `NewsArticle` and
`Tweet` types
</figcaption> </figcaption>
</figure> </figure>
In the same way `impl` lets us define methods, we've used it to define methods Implementing a trait on a type is similar to implementing methods that aren't
that pertain to our trait. We can call methods that our trait has defined just related to a trait. The difference is after `impl`, we put the trait name that
like we can call other methods: we want to implement, then say `for` and the name of the type that we want to
implement the trait for. Within the `impl` block, we put the method signatures
that the trait definition has defined, but instead of putting a semicolon after
each signature, we put curly braces and fill in the method body with the
specific behavior that we want the methods of the trait to have for the
particular type.
<span class="filename">Filename: src/main.rs</span> Once we've implemented the trait, we can call the methods on instances of
`NewsArticle` and `Tweet` in the same manner that we call methods that aren't
part of a trait:
```rust ```rust,ignore
# trait Printable { let tweet = Tweet {
# fn print(&self); username: String::from("horse_ebooks"),
# } content: String::from("of course, as you probably already know, people"),
# reply: false,
# enum Temperature { retweet: false,
# Celsius(i32), };
# Fahrenheit(i32),
# }
#
# impl Printable for Temperature {
# fn print(&self) {
# match *self {
# Temperature::Celsius(val) => println!("{}°C", val),
# Temperature::Fahrenheit(val) => println!("{}°F", val),
# }
# }
# }
#
fn main() {
let t = Temperature::Celsius(37);
t.print(); println!("1 new tweet: {}", tweet.summary());
```
This will print `1 new tweet: horse_ebooks: of course, as you probably already
know, people`.
Note that because we've defined the `Summarizable` trait and the `NewsArticle`
and `Tweet` types all in the same `lib.rs` in Listing 10-12, they're all in the
same scope. If this `lib.rs` is for a crate we've called `aggregator`, and
someone else wants to use our crate's functionality plus implement the
`Summarizable` trait on their `WeatherForecast` struct, their code would need
to import the `Summarizable` trait into their scope first before they could
implement it, like in Listing 10-13:
<figure>
<span class="filename">Filename: lib.rs</span>
```rust,ignore
extern crate aggregator;
use aggregator::Summarizable;
struct WeatherForecast {
high_temp: f64,
low_temp: f64,
chance_of_precipitation: f64,
}
impl Summarizable for WeatherForecast {
fn summary(&self) -> String {
format!("The high will be {}, and the low will be {}. The chance of
precipitation is {}%.", self.high_temp, self.low_temp,
self.chance_of_precipitation)
}
} }
``` ```
Note that in order to use a trait's methods, the trait itself must be in scope. <figcaption>
If the definition of `Printable` was in a module, the definition would need to
be defined as `pub` and we would need to `use` the trait in the scope where we Listing 10-13: Bringing the `Summarizable` trait from our `aggregator` crate
wanted to call the `print` method. This is because it's possible to have two into scope in another crate
traits that both define a method named `print`, and our `Temperature` enum might
implement both. Rust wouldn't know which `print` method we wanted unless we </figcaption>
brought the trait we wanted into our current scope with `use`. </figure>
This code also assumes `Summarizable` is a public trait, which it is because we
put the `pub` keyword before `trait` in Listing 10-11.
One restriction to note with trait implementations: we may implement a trait on
a type as long as either the trait or the type are local to our crate. In other
words, we aren't allowed to implement external traits on external types. We
can't implement the `Display` trait on `Vec`, for example, since both `Display`
and `Vec` are defined in the standard library. We are allowed to implement
standard library traits like `Display` on a custom type like `Tweet` as part of
our `aggregator` crate functionality. We could also implement `Summarizable` on
`Vec` in our `aggregator` crate, since we've defined `Summarizable` there. This
restriction is part of what's called the *orphan rule*, which you can look up
if you're interested in type theory. Briefly, it's called the orphan rule
because the parent type is not present. Without this rule, two crates could
implement the same trait for the same type, and the two implementations would
conflict: Rust wouldn't know which implementation to use. Because Rust enforces
the orphan rule, other people's code can't break your code and vice versa.
### Default Implementations
Sometimes it's useful to have default behavior for some or all of the methods
in a trait, instead of making every implementation on every type define custom
behavior. When we implement the trait on a particular type, we can choose to
keep or override each method's default behavior.
Listing 10-14 shows how we could have chosen to specify a default string for
the `summary` method of the `Summarize` trait instead of only choosing to only
define the method signature like we did in Listing 10-11:
<figure>
<span class="filename">Filename: lib.rs</span>
```rust
pub trait Summarizable {
fn summary(&self) -> String {
String::from("(Read more...)")
}
}
```
<figcaption>
Listing 10-14: Definition of a `Summarizable` trait with a default
implementation of the `summary` method
</figcaption>
</figure>
If we wanted to use this default implementation to summarize instances of
`NewsArticle` instead of defining a custom implementation like we did in
Listing 10-12, we would specify an empty `impl` block:
```rust,ignore
impl Summarizable for NewsArticle {}
```
Even though we're no longer choosing to define the `summary` method on
`NewsArticle` directly, since the `summary` method has a default implementation
and we specified that `NewsArticle` implements the `Summarizable` trait, we can
still call the `summary` method on an instance of `NewsArticle`:
```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.summary());
```
This code prints `New article available! (Read more...)`.
Changing the `Summarizable` trait to have a default implementation for
`summary` does not require us to change anything about the implementations of
`Summarizable` on `Tweet` in Listing 10-12 or `WeatherForecast` in Listing
10-13: the syntax for overriding a default implementation is exactly the same
as the syntax for implementing a trait method that doesn't have a default
implementation.
Default implementations are allowed to call the 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
implementers to specify a small part of it. We could choose to have the
`Summarizable` trait also have an `author_summary` method whose implementation
is required, then a `summary` method that has a default implementation that
calls the `author_summary` method:
```rust
pub trait Summarizable {
fn author_summary(&self) -> String;
fn summary(&self) -> String {
format!("(Read more from {}...)", self.author_summary())
}
}
```
In order to use this version of `Summarizable`, we're only required to define
`author_summary` when we implement the trait on a type:
```rust,ignore
impl Summarizable for Tweet {
fn author_summary(&self) -> String {
format!("@{}", self.username)
}
}
```
Once we define `author_summary`, we can call `summary` on instances of the
`Tweet` struct, and the default implementation of `summary` will call the
definition of `author_summary` that we've provided.
```rust,ignore
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
};
println!("1 new tweet: {}", tweet.summary());
```
This will print `1 new tweet: (Read more from @horse_ebooks...)`.
Note that it is not possible to call the default implementation from an
overridden implementation.
### Trait Bounds ### Trait Bounds
Defining traits with methods and implementing the trait methods on a particular Now that we've defined traits and implemented those traits on types, we can use
type gives Rust more information than just defining methods on a type directly. traits with generic type parameters. We can constrain generic types so that
The information Rust gets is that the type that implements the trait can be rather than being any type, the compiler will ensure that the type will be
used in places where the code specifies that it needs some type that implements limited to those types that implement a particular trait and thus have the
a trait. To illustrate this, Listing 10-7 has a `print_anything` function behavior that we need the types to have. This is called specifying *trait
definition. This is similar to the `show_anything` function from Listing 10-4, bounds* on a generic type.
but this function has a *trait bound* on the generic type `T` and uses the
`print` function from the trait. A trait bound constrains the generic type to
be any type that implements the trait specified, instead of any type at all.
With the trait bound, we're then allowed to use the trait method `print` in the
function body:
<figure> For example, in Listing 10-12, we implemented the `Summarizable` trait on the
<span class="filename">Filename: src/lib.rs</figure> types `NewsArticle` and `Tweet`. We can define a function `notify` that calls
the `summary` method on its parameter `item`, which is of the generic type `T`.
```rust To be able to call `summary` on `item` without getting an error, we can use
# trait Printable { trait bounds on `T` to specify that `item` must be of a type that implements
# fn print(&self); the `Summarizable` trait:
# }
#
fn print_anything<T: Printable>(value: T) {
println!("I have something to print for you!");
value.print();
}
```
<figcaption>
Listing 10-7: A `print_anything` function that uses the trait bound `Printable`
on type `T`
</figcaption>
</figure>
Trait bounds are specified in the type name declarations within the angle
brackets. After the name of the type that you want to apply the bound to, add a
colon (`:`) and then specify the name of the trait. This function now specifies
that it takes a `value` parameter that can be of any type, as long as that type
implements the trait `Printable`. We need to specify the `Printable` trait in
the type name declarations because we want to be able to call the `print`
method that is part of the `Printable` trait.
Now we are able to call the `print_anything` function from Listing 10-7 and
pass it a `Temperature` instance as the `value` parameter, since we implemented
the trait `Printable` on `Temperature` in Listing 10-6:
<span class="filename">Filename: src/main.rs</span>
```rust
# trait Printable {
# fn print(&self);
# }
#
# enum Temperature {
# Celsius(i32),
# Fahrenheit(i32),
# }
#
# impl Printable for Temperature {
# fn print(&self) {
# match *self {
# Temperature::Celsius(val) => println!("{}°C", val),
# Temperature::Fahrenheit(val) => println!("{}°F", val),
# }
# }
# }
#
# fn print_anything<T: Printable>(value: T) {
# println!("I have something to print for you!");
# value.print();
# }
#
fn main() {
let temperature = Temperature::Fahrenheit(98);
print_anything(temperature);
}
```
If we implement the `Printable` trait on other types, we can use them with the
`print_anything` method too. If we try to call `print_anything` with an `i32`,
which does *not* implement the `Printable` trait, we get a compile-time error
that looks like this:
```text
error[E0277]: the trait bound `{integer}: Printable` is not satisfied
|
29 | print_anything(3);
| ^^^^^^^^^^^^^^ trait `{integer}: Printable` not satisfied
|
= help: the following implementations were found:
= help: <Point as Printable>
= note: required by `print_anything`
```
Traits are an extremely useful feature of Rust. You'll almost never see generic
functions without an accompanying trait bound. There are many traits in the
standard library, and they're used for many, many different things. For
example, our `Printable` trait is similar to one of those traits, `Display`.
And in fact, that's how `println!` decides how to format things with `{}`. The
`Display` trait has a `fmt` method that determines how to format something.
Listing 10-8 shows our original example from Listing 10-3, but this time using
the standard library's `Display` trait in the trait bound on the generic type
in the `show_anything` function:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
use std::fmt::Display;
fn show_anything<T: Display>(value: T) {
println!("I have something to show you!");
println!("It's: {}", value);
}
```
<figcaption>
Listing 10-8: The `show_anything` function with trait bounds
</figcaption>
</figure>
Now that this function specifies that `T` can be any type as long as that type
implements the `Display` trait, this code will compile.
### Multiple Trait Bounds and `where` Syntax
Each generic type can have its own trait bounds. The signature for a function
that takes a type `T` that implements `Display` and a type `U` that implements
`Printable` looks like:
```rust,ignore ```rust,ignore
fn some_function<T: Display, U: Printable>(value: T, other_value: U) { pub fn notify<T: Summarizable>(item: T) {
``` println!("Breaking news! {}", item.summary());
To specify multiple trait bounds on one type, list the trait bounds in a list
with a `+` between each trait. For example, here's the signature of a function
that takes a type `T` that implements `Display` and `Clone` (which is another
standard library trait we have mentioned):
```rust,ignore
fn some_function<T: Display + Clone>(value: T) {
```
When trait bounds start getting complicated, there is another syntax that's a
bit cleaner: `where`. And in fact, the error we got when we ran the code from
Listing 10-3 referred to it:
```text
help: consider adding a `where T: std::fmt::Display` bound
```
The `where` syntax moves the trait bounds after the function parameters list.
This definition of `show_anything` means the exact same thing as the definition
in Listing 10-8, just said a different way:
<span class="filename">Filename: src/lib.rs</span>
```rust
use std::fmt::Display;
fn show_anything<T>(value: T) where T: Display {
println!("I have something to show you!");
println!("It's: {}", value);
} }
``` ```
Instead of `T: Display` going inside the angle brackets, they go after the Trait bounds go with the declaration of the generic type parameter, after a
`where` keyword at the end of the function signature. This can make complex colon and within the angle brackets. Because of the trait bound on `T`, we can
signatures easier to read. The `where` clause and its parts can also go on new call `notify` and pass in any instance of `NewsArticle` or `Tweet`. The
lines. Here's the signature of a function that takes three generic type external code from Listing 10-13 that's using our `aggregator` crate can call
parameters that each have multiple trait bounds: our `notify` function and pass in an instance of `WeatherForecast`, since
`Summarizable` is implemented for `WeatherForecast` as well. Code that calls
`notify` with any other type, like a `String` or an `i32`, won't compile, since
those types do not implement `Summarizable`.
We can specify multiple trait bounds on a generic type by using `+`. If we
needed to be able to use display formatting on the type `T` in a function as
well as the `summary` method, we can use the trait bounds `T: Summarizable +
Display`. This means `T` can be any type that implements both `Summarizable`
and `Display`.
For functions that have multiple generic type parameters, each generic has its
own trait bounds. Specifying lots of trait bound information in the angle
brackets between a function's name and its parameter list can get hard to read,
so there's an alternate syntax for specifying trait bounds that lets us move
them to a `where` clause after the function signature. So instead of:
```rust,ignore ```rust,ignore
fn some_function<T, U, V>(t: T, u: U, v: V) fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
```
We can write this instead with a `where` clause:
```rust,ignore
fn some_function<T, U>(t: T, u: U) -> i32
where T: Display + Clone, where T: Display + Clone,
U: Printable + Debug, U: Clone + Debug
V: Clone + Printable
{ {
``` ```
Generic type parameters and trait bounds are part of Rust's rich type system. This is less cluttered and makes this function's signature look more similar to
Another important kind of generic in Rust interacts with Rust's ownership and a function without lots of trait bounds, in that the function name, parameter
references features, and they're called *lifetimes*. list, and return type are close together.
### Fixing the `largest` Function with Trait Bounds
So any time you want to use behavior defined by a trait on a generic, you need
to specify that trait in the generic type parameter's type bounds. We can now
fix the definition of the `largest` function that uses a generic type parameter
from Listing 10-5! When we set that code aside, we were getting this error:
```text
error[E0369]: binary operation `>` cannot be applied to type `T`
|
5 | if item > largest {
| ^^^^
|
note: an implementation of `std::cmp::PartialOrd` might be missing for `T`
```
In the body of `largest` we wanted to be able to compare two values of type `T`
using the greater-than operator. That operator is defined as a default method
on the standard library trait `std::cmp::PartialOrd`. So in order to be able to
use the greater-than operator, we need to specify `PartialOrd` in the trait
bounds for `T` so that the `largest` function will work on slices of any type
that can be compared. We don't need to bring `PartialOrd` into scope because
it's in the prelude.
```rust,ignore
fn largest<T: PartialOrd>(list: &[T]) -> T {
```
If we try to compile this, we'll get different errors:
```text
error[E0508]: cannot move out of type `[T]`, a non-copy array
--> src/main.rs:4:23
|
4 | let mut largest = list[0];
| ----------- ^^^^^^^ cannot move out of here
| |
| hint: to prevent move, use `ref largest` or `ref mut largest`
error[E0507]: cannot move out of borrowed content
--> src/main.rs:6:9
|
6 | for &item in list.iter() {
| ^----
| ||
| |hint: to prevent move, use `ref item` or `ref mut item`
| cannot move out of borrowed content
```
The key to this error is `cannot move out of type [T], a non-copy array`.
With our non-generic versions of the `largest` function, we were only trying to
find the largest `i32` or `char`. As we discussed in Chapter 4, types like
`i32` and `char` that have a known size can be stored on the stack, so they
implement the `Copy` trait. When we changed the `largest` function to be
generic, it's now possible that the `list` parameter could have types in it
that don't implement the `Copy` trait, which means we wouldn't be able to move
the value out of `list[0]` and into the `largest` variable.
If we only want to be able to call this code with types that are `Copy`, we can
add `Copy` to the trait bounds of `T`! Listing 10-15 shows the complete code of
a generic `largest` function that will compile as long as the types of the
values in the slice that we pass into `largest` implement both the `PartialOrd`
and `Copy` traits, like `i32` and `char`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
use std::cmp::PartialOrd;
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
let numbers = vec![34, 50, 25, 100, 65];
let result = largest(&numbers);
println!("The largest number is {}", result);
let chars = vec!['y', 'm', 'a', 'q'];
let result = largest(&chars);
println!("The largest char is {}", result);
}
```
<figcaption>
Listing 10-15: A working definition of the `largest` function that works on any
generic type that implements the `PartialOrd` and `Copy` traits
</figcaption>
</figure>
If we don't want to restrict our `largest` function to only types that
implement the `Copy` trait, we could specify that `T` has the trait bound
`Clone` instead of `Copy` and clone each value in the slice when we want the
`largest` function to have ownership. Using the `clone` function means we're
potentially making more heap allocations, though, and heap allocations can be
slow if we're working with large amounts of data. Another way we could
implement `largest` is for the function to return a reference to a `T` value in
the slice. If we change the return type to be `&T` instead of `T` and change
the body of the function to return a reference, we wouldn't need either the
`Clone` or `Copy` trait bounds and we wouldn't be doing any heap allocations.
Try implementing these alternate solutions on your own!
Traits and trait bounds let us write code that uses generic type parameters in
order to reduce duplication, but still specify to the compiler exactly what
behavior our code needs the generic type to have. Because we've given the trait
bound information to the compiler, it can check that all the concrete types
used with our code provide the right behavior. In dynamically typed languages,
if we tried to call a method on a type that the type didn't implement, we'd get
an error at runtime. 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 since we've
already checked at compile time, which improves performance compared to other
languages without having to give up the flexibility of generics.
There's another kind of generics that we've been using without even realizing
it called *lifetimes*. Rather than helping us ensure that a type has the
behavior we need it to have, lifetimes help us ensure that references are valid
as long as we need them to be. Let's learn how lifetimes do that.
File diff suppressed because it is too large Load Diff