Multiple Bounds
We'll cover the following...
I want to write a function, info,
that prints out some information about a number. It’s easier if I just show it to you:
Press + to interact
trait Double {fn double(self) -> Self;}impl Double for i32 {fn double(self) -> i32 { self * 2 }}fn info(x: i32) {println!("Original number: {}", x);println!("Doubled number: {}", x.double());println!("Quadrupled number: {}", x.double().double());}fn main() {info(5);}
Since our info
is defined in terms of the double
method only, though, it seems like we should be able to parameterize. Try changing the signature from i32
to a type parameter:
Press + to interact
fn info<T: Double>(x: T)
This generates an error message:
error[E0277]:
...Access this course and 1400+ top-rated courses and projects.