1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-24 08:32:57 +02:00

Clarify that trait bounds give access to methods and add example of impl Trait. (#378)

This commit is contained in:
gendx 2023-02-09 21:50:34 +00:00 committed by GitHub
parent f912825411
commit 91eec89c52
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,19 +1,32 @@
# Trait Bounds # Trait Bounds
When working with generics, you often want to limit the types. You can do this When working with generics, you often want to require the types to implement
with `T: Trait` or `impl Trait`: some trait, so that you can call this trait's methods.
You can do this with `T: Trait` or `impl Trait`:
```rust,editable ```rust,editable
fn duplicate<T: Clone>(a: T) -> (T, T) { fn duplicate<T: Clone>(a: T) -> (T, T) {
(a.clone(), a.clone()) (a.clone(), a.clone())
} }
// Syntactic sugar for:
// fn add_42_millions<T: Into<i32>>(x: T) -> i32 {
fn add_42_millions(x: impl Into<i32>) -> i32 {
x.into() + 42_000_000
}
// struct NotClonable; // struct NotClonable;
fn main() { fn main() {
let foo = String::from("foo"); let foo = String::from("foo");
let pair = duplicate(foo); let pair = duplicate(foo);
println!("{pair:?}"); println!("{pair:?}");
let many = add_42_millions(42_i8);
println!("{many}");
let many_more = add_42_millions(10_000_000);
println!("{many_more}");
} }
``` ```