I have a newbie question about generics in Rust (version 1.0).
Let's say I write a generic function to do division. Never mind the usefulness of such a function; it's 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 fails to 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 the compiler error is telling me that the result of the division operation is type Output
, not T
, and I see the Output
type in the standard library documentation.
How do I convert from Output
to T
? I try to use as
to cast.
fn divide<T: std::ops::Div>(a: T, b: T) -> T {
(a / b) as T
}
fn main() {
println!("{}", divide(42, 18))
}
This causes a different 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'm out of ideas to make this work, and I realize I lack understanding of something fundamental about the language here, but I don't even know what to look for to make this work. Help?