mirror of
https://github.com/darkicewolf50/RustBrock.git
synced 2025-07-07 03:27:13 -06:00
finished ch10
This commit is contained in:
@ -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
|
Reference in New Issue
Block a user