mcd
mcd

Reputation: 121

Generic type conversion for objects with traits in Rust

I have a trait Mode, several structs MyModeN and an object-like struct <MyMode: Mode> Obj<MyMode>.

I want to build a general conversion function that outputs the new object, with some reinitialization. Writing the function is not the issue, getting the type-signature and the impl block correctly is.

I tried

impl <MyMode: Mode, NewMode: Mode> Obj<MyMode> {
    pub fn convert(self, m: NewMode) -> Obj<NewMode> { unimplemented!() }
}

but this fails because NewMode is not specified in the object itself. Using impl instead of NewMode, i.e.

pub fn convert(self, m: impl Mode) -> Obj<impl Mode>

also does not help since then I cannot use

impl Obj<MyModeN> { .. }

blocks.

How can I achieve my desired behavior?

Upvotes: 2

Views: 606

Answers (1)

Isaac van Bakel
Isaac van Bakel

Reputation: 1862

Try adding the 2nd generic parameter to the function instead of the impl block:

pub fn convert<NewMode: Mode>(self, m: NewMode)...

Upvotes: 1

Related Questions