Something you may have noticed
If we compare the two different implementations of the code (generic and non-generic), the main difference is that we have reduced the amount of code we need as the two structs were the same in all but the name. We have also simplified the code so that we have a single call to calc and allow the compiler to decide which one we need based on the type passed in.
Generics - a small aside
Code reduction and simplification is always a good thing (well, mostly at least!). However, with generics, there is always a trade-off and it's not always apparent.
Let's consider the following piece of code:
fn my_multiply<T: Mul<Output = T>>(a: T, b: T) -> T { return a * b; }
This returns a value of type T
by multiplying two variables (of type T
).
The question is: You can send a number of types into that function - how will the compiler know what to do if it doesn't know what type T
is? The only safe way is to create a version of my_multiply
for each possible type....