src/generics/trait-bounds.md
When working with generics, you often want to require the types to implement some trait, so that you can call this trait's methods.
You can do this with T: Trait:
# // Copyright 2022 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
fn duplicate<T: Clone>(a: T) -> (T, T) {
(a.clone(), a.clone())
}
struct NotCloneable;
fn main() {
let foo = String::from("foo");
let pair = duplicate(foo);
println!("{pair:?}");
}
Try making a NotCloneable and passing it to duplicate.
When multiple traits are necessary, use + to join them.
Show a where clause, students will encounter it when reading code.
# // Copyright 2022 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
fn duplicate<T>(a: T) -> (T, T)
where
T: Clone,
{
(a.clone(), a.clone())
}
Option<T>.Note that Rust does not (yet) support specialization. For example, given the
original duplicate, it is invalid to add a specialized duplicate(a: u32).