Trait bounds and impl Trait
Let's go back to the job posting. So far we have looked at the applicants: how each one carries out the duties. Now let's look at the employer. Any guard will do, as long as it can make a noise, and whether it is a dog or a goose doesn't matter.
In a program, the employer is a generic function. It accepts a value of any type T, but requires T to be able to do what it needs. You have written such a requirement already: T: PartialOrd in the function largest. Any trait can be a bound, such as the Debug you know:
use std::fmt::Debug;
fn show<T: Debug>(x: T) {
println!("[{:?}]", x);
}
fn main() {
show(7); // [7]
show("hi"); // ["hi"]
show(Some(2.5)); // [Some(2.5)]
}Let's go through the example line by line:
use std::fmt::Debug;makes the name of the traitDebugavailable.PartialOrdneeds no such line: its name is always available.fn show<T: Debug>(x: T)accepts a value of any type that can be printed with{:?}.- Inside the function,
{:?}is allowed forx: the bound promises it. - The three calls fill in three different types:
i32,&strandOption<f64>. All of them haveDebug, and the program prints[7],["hi"]and[Some(2.5)].
Your own trait as a bound
Your own trait works in a bound the same way a standard one does. Here is an employer for the trait Speak:
trait Speak {
fn speak(&self) -> String {
String::from("...")
}
}
struct Fish;
impl Speak for Fish {}
fn call<T: Speak>(animal: &T) {
println!("{}!", animal.speak());
}
call(&Fish); // ...!Let's go through it line by line:
- The method
speakhas a default body, so the empty implementationimpl Speak for Fish {}is complete. fn call<T: Speak>(animal: &T)accepts a reference to a value of any type with the traitSpeak.- Inside
call, the callanimal.speak()is allowed: the bound promises this method. call(&Fish)fills inT = Fishand prints...!.
The function call knows nothing about Fish or any other type. Write impl Speak for Dog tomorrow, and call(&Dog) will work without a single edit to call.
Several bounds and where
An employer can require several skills at once. Bounds are joined with +: T: Speak + Debug means "can make a noise and can be printed with {:?}".
When there are many bounds, the header gets long. Then they move into a where clause after the parameter list. These two forms mean the same thing:
fn report<T: Speak + Debug>(animal: &T);fn report<T>(animal: &T) where T: Speak + Debug.
With where, the function's name and parameters are visible at once, and the requirements on the type stand apart. It is a matter of readability: the compiler checks both forms the same way.
The impl Trait form
There is also a short form: impl Trait in place of a type name. It goes in two places, and it means different things in each:
fn call_any(animal: &impl Speak) {
println!("{}!", animal.speak());
}
fn pet() -> impl Speak {
Fish
}
call_any(&pet()); // ...!In a parameter
animal: &impl Speak is shorthand for a generic function. call_any works the same way as call<T: Speak>: the call picks the type. The short form is handy when the type parameter is needed in one place.
In the result
fn pet() -> impl Speak means "I return some type with the trait Speak, and I won't say which". The function itself picks the type, here Fish. The calling code knows only that the result has a speak method.
Such a function returns exactly one type. If one branch of an if returns Fish and the other returns Dog, the build stops with error[E0308]: `if` and `else` have incompatible types, even when both types implement Speak.
Interviewers often ask how impl Trait in a parameter differs from impl Trait in the result. In a parameter the calling code picks the type, while in the result the function itself picks it, and it is always one type.
Here the job posting picture is off. A real employer checks a skill once the applicant has already shown up. The compiler checks a bound at build time, at every call: a type without the required trait never reaches the function.
Common mistake
The function is called with a type that lacks the required trait:
trait Speak {
fn speak(&self) -> String;
}
struct Rock;
fn call<T: Speak>(animal: &T) {
println!("{}!", animal.speak());
}
fn main() {
call(&Rock); // ✗
}error[E0277]: the trait bound `Rock: Speak` is not satisfiedThe program does not compile: call requires T: Speak, and Rock has no implementation of Speak. The compiler checks the bound before anything runs, so there is no panic here. The fix is to write impl Speak for Rock, or to pass a type that has an implementation.
Key points
- A bound
T: Speakallows the trait's methods in the body and lets only types with that trait into the function. - Several bounds are joined with
+, and a long list moves intowhere. impl Traitin a parameter is shorthand for a generic function: the call picks the type.impl Traitin the result hides one concrete type that the function itself picks.