finished ch10

This commit is contained in:
2025-02-05 11:14:05 -07:00
parent 89f9705f62
commit b00b78a773
4 changed files with 75 additions and 14 deletions

View File

@ -18,4 +18,33 @@ This chapter covers 3 things
1. [Reducing Code duplication](Reducing_Code_Duplication.md)
1. [Generics](Generics.md)
1. [Traits](Traits.md)
1. [Lifetimes](Lifetimes.md)
2. [Lifetimes](Lifetimes.md)
## Generic Type Parameters, Trait Bounds, and Lifetimes Together
Here is an example with all of them together
```rust
use std::fmt::Display;
fn longest_with_an_announcement<'a, T>(
x: &'a str,
y: &'a str,
ann: T,
) -> &'a str
where
T: Display,
{
println!("Announcement! {ann}");
if x.len() > y.len() {
x
} else {
y
}
}
```
This is the `longest` function that returns the longer of the two string slices.
Now it has a parameter called `ann` of the generic type `T` which can only be any type that implements the `Display` trait as specified by the `where` clause
The `ann` parameter will be printed using `{}`, which is why the `Display` trait is necessary
Because lifetimes are a type of generic the declarations of the lifetime parameter `'a` and the generic type parameter `T` go in the same list inside the angle brackets after the function name