From 91eec89c52498588b8948e0b9b33a8552ce0c635 Mon Sep 17 00:00:00 2001 From: gendx Date: Thu, 9 Feb 2023 21:50:34 +0000 Subject: [PATCH] Clarify that trait bounds give access to methods and add example of impl Trait. (#378) --- src/generics/trait-bounds.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/generics/trait-bounds.md b/src/generics/trait-bounds.md index adbd0af0..9e5f5eb6 100644 --- a/src/generics/trait-bounds.md +++ b/src/generics/trait-bounds.md @@ -1,19 +1,32 @@ # Trait Bounds -When working with generics, you often want to limit the types. You can do this -with `T: Trait` or `impl Trait`: +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` or `impl Trait`: ```rust,editable fn duplicate(a: T) -> (T, T) { (a.clone(), a.clone()) } +// Syntactic sugar for: +// fn add_42_millions>(x: T) -> i32 { +fn add_42_millions(x: impl Into) -> i32 { + x.into() + 42_000_000 +} + // struct NotClonable; fn main() { let foo = String::from("foo"); let pair = duplicate(foo); println!("{pair:?}"); + + let many = add_42_millions(42_i8); + println!("{many}"); + let many_more = add_42_millions(10_000_000); + println!("{many_more}"); } ```