0

I have a trait

trait MyTrait {
    fn generic_method<T: OtherTrait>() -> T;
}

I also have a struct

struct MyStruct<T: OtherTrait> {...}

I'd like to bind the generic type from MyStruct to generic_method when implementing the trait.

Something like

impl<T: OtherTrait> MyTrait for MyStruct<T> {
    fn generic_method() -> T {...}
}

Is there a way to do it?

Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22
  • 1
    I am not too good with rust but couldn't you also do `fn generic_method()`? – SharedRory Oct 26 '21 at 16:15
  • 1
    The current definition of `MyTrait` requires an implementation of `generic_method` to work for any `T` defined by the caller. This `T` needs to be moved to the scope of that trait, either as a parameter type or as an associated type. – E_net4 Oct 26 '21 at 16:17
  • 1
    See also: https://stackoverflow.com/a/53085395/1233251 – E_net4 Oct 26 '21 at 16:19
  • I tried all the suggestions: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d6db57b37afed1cb140294a0665a210e I don't think it will compile without changing `MyTrait` – Alexandre Senges Oct 26 '21 at 16:22
  • 1
    Yes, you'll have to change the trait if `.generic_method()` actually returns a specific, non-generic type determined by the implementer. Here's your trait using an associated type: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=03253aedddcedf1b9653afe1d4c27a2b – kmdreko Oct 26 '21 at 18:14

0 Answers0