Trait Bounds
We'll cover the following...
I want to quadruple my numbers. I could do * 4
, but that’s so pedestrian. I’ve already got a double
method. So why not simply call it twice?
Press + to interact
fn quadruple(x: i32) -> i32 {x.double().double()}fn main() {println!("quadruple 5_i32 == {}", quadruple(5_i32));}trait Double {fn double(&self) -> Self;}impl Double for i32 {fn double(&self) -> Self {self * 2}}impl Double for i64 {fn double(&self) -> Self {self * 2}}
That’s great, but it only works for an i32
. If I try ...