Parameterized Fruit
We'll cover the following...
I said we were allowed to write a trait implementation for types we created ourselves. Let’s write a Fruit
struct and provide it a Double
implementation:
Press + to interact
trait Double {fn double(&self) -> Self;}impl Double for i32 {fn double(&self) -> Self {self * 2}}struct Fruit {apples: i32,bananas: i32,}impl Double for Fruit {fn double(&self) -> Self {Fruit {apples: self.apples.double(),bananas: self.bananas.double(),}}}fn main() {let fruit = Fruit {apples: 5,bananas: 10,};println!("Apples plus bananas is {} and then doubled, apples plus bananas is {}.", fruit.apples + fruit.bananas, fruit.apples.double() + fruit.bananas.double());}
Look at that, we were even able to reuse our double
trait method inside the implementation of double
for Fruit
. How convenient! But after we learned about parameterized structs, it feels a bit limiting to tie ourselves down to an i32
. Can we parameterize Fruit
? Let’s try it. ...