2

I would like to create this trait:

trait Functor<A> {
    fn map<B, F>(self, f: F) -> Functor<B>
    where
        F: Fn(A) -> B;
}

I have this error:

warning: trait objects without an explicit `dyn` are deprecated
 --> src/lib.rs:2:33
  |
2 |     fn map<B, F>(self, f: F) -> Functor<B>
  |                                 ^^^^^^^^^^ help: use `dyn`: `dyn Functor<B>`
  |
  = note: `#[warn(bare_trait_objects)]` on by default

error: associated item referring to unboxed trait object for its own trait
 --> src/lib.rs:2:33
  |
1 | trait Functor<A> {
  |       ------- in this trait
2 |     fn map<B, F>(self, f: F) -> Functor<B>
  |                                 ^^^^^^^^^^
  |
help: you might have meant to use `Self` to refer to the implementing type
  |
2 |     fn map<B, F>(self, f: F) -> Self
  |                                 ^^^^

error[E0038]: the trait `Functor` cannot be made into an object
 --> src/lib.rs:2:33
  |
1 | trait Functor<A> {
  |       ------- this trait cannot be made into an object...
2 |     fn map<B, F>(self, f: F) -> Functor<B>
  |        ---                      ^^^^^^^^^^ the trait `Functor` cannot be made into an object
  |        |
  |        ...because method `map` has generic type parameters
  |
  = help: consider moving `map` to another trait

It seems that there is no way to achieve this kind of thing.

Instead of returning Functor<B> from the map method, I'd rather return something like Self<B> because I want the implementation to return itself (with generic B instead of A), but I don't know how to write it.

I initially tried with an associated type instead of a generic because I thought it was more appropriate, but it didn't work any better.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
chapa
  • 21
  • 2
  • 1
    Someday you might be able to use [*generic associated types*](https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md) to [solve your problem](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=0cf5e78259f2781032fc1b8b29ebc74c). See also [Is there any way to simulate Generic Associated Types / Associated Type Constructors in Rust?](https://stackoverflow.com/q/54161441/155423) – Shepmaster Oct 26 '20 at 16:18

0 Answers0