rust - Casting to a generic type -


i have newbie question generics in rust (version 1.0).

let's write generic function division. never mind usefulness of such function; it's simple function keep question simple.

fn divide<t: std::ops::div>(a: t, b: t) -> t {     / b }  fn main() {     println!("{}", divide(42, 18)) } 

this program fails compile.

src/main.rs:2:5: 2:10 error: mismatched types:  expected `t`,     found `<t core::ops::div>::output` (expected type parameter,     found associated type) [e0308] src/main.rs:2     / b                   ^~~~~ 

i understand compiler error telling me result of division operation type output, not t, , see output type in standard library documentation.

how convert output t? try use as cast.

fn divide<t: std::ops::div>(a: t, b: t) -> t {     (a / b) t }  fn main() {     println!("{}", divide(42, 18)) } 

this causes different compiler error.

src/main.rs:2:5: 2:17 error: non-scalar cast: `<t core::ops::div>::output` `t` src/main.rs:2     (a / b) t                   ^~~~~~~~~~~~ 

i'm out of ideas make work, , realize lack understanding of fundamental language here, don't know make work. help?

you have specify t::output return type of function:

fn divide<t: std::ops::div>(a: t, b: t) -> t::output {     / b } 

edit add more explanation on why cannot cast inside function

when in generic function divide, compiler yet doesn't know can cast t t::output, cast invalid. generic types, can anything, how compiler knows can cast t t::output ?

a / b produces of type t::output, in solution above there not cast, t::output right type.

edit add possible solution using std::convert::from

the (i think) generic implementation when know cast t::output t possible. can bound t implement from t::output. complete example:

use std::ops::div; use std::convert::from;  fn divide<t: div>(a: t, b: t) -> t     t: from<<t div>::output> {     t::from(a / b) }  #[derive(debug)] struct bip(u32);  impl div bip {     type output = f32;      fn div(self, rhs: bip) -> f32 {         (self.0 / rhs.0) f32     } }  impl from<f32> bip {     fn from(value: f32) -> self {         bip(value u32)     } }  fn main() {     println!("{:?}", divide(12, 4));     println!("{:?}", divide(bip(12), bip(4))); } 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -