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. Fortunately, the compiler does this automatically for you in a process called monomorphization.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset