January 2019
Beginner to intermediate
554 pages
13h 31m
English
The other syntax for declaring trait bounds is the impl trait syntax, which is a recent addition to the compiler. Using this syntax, you can also write a generic function with trait bounds like this:
// impl_trait_syntax.rsuse std::fmt::Display;fn show_me(val: impl Display) { println!("{}", val);}fn main() { show_me("Trait bounds are awesome");}
Instead of specifying T: Display, we directly use impl Display. This is the impl trait syntax. This provides advantages in cases where we want to return a complex or unrepresentable type, such as a closure from a function. Without this syntax, you had to return it by putting it behind a pointer using the Box smart pointer type, which involves heap allocation. Closures ...
Read now
Unlock full access