I have a newbie question about generics in Rust (version 1.0).
Say I'm writing a generic division function. Do not pay attention to the usefulness of such a function; this is a simple function to keep this question simple.
fn divide<T: std::ops::Div>(a: T, b: T) -> T { a / b } fn main() { println!("{}", divide(42, 18)) }
This program does not compile.
src/main.rs:2:5: 2:10 error: mismatched types: expected `T`, found `<T as core::ops::Div>::Output` (expected type parameter, found associated type) [E0308] src/main.rs:2 a / b ^~~~~
I understand that a compiler error tells me that the result of the division operation is the Output type, not T , and I see the Output type in the standard library documentation .
How do I convert from Output to T ? I am trying to use as to create.
fn divide<T: std::ops::Div>(a: T, b: T) -> T { (a / b) as T } fn main() { println!("{}", divide(42, 18)) }
This leads to another compiler error.
src/main.rs:2:5: 2:17 error: non-scalar cast: `<T as core::ops::Div>::Output` as `T` src/main.rs:2 (a / b) as T ^~~~~~~~~~~~
I have no ideas to do this work, and I understand that I lack an understanding of something fundamental in this language, but I donβt even know what to look for in order to do this work. Help?
source share