Impl Trait in trait definitions?

I was writing some sketch code to show someone impl Trait and it involved something like

trait Action {
  fn act(&self) -> impl Future<Item=(), Error=Error>;
  fn description(&self) -> String;
}

(playground)

but I found out this isn’t possible, as impl Trait is only allowed on free functions and inherent impls. But I think there’s a reasonable desugaring of this and wanted to get your thoughts:

trait Action {
  type ActReturn: Future<Item=(), Error=Error>;
  fn act(&self) -> ActReturn;
  fn description(&self) -> String;
}

ActReturn is a a generated symbol (I don’t know what this is called in the compiler, but it exists in MIR for impl Trait I think?).

On an impl,

struct MyAction;
impl Action for MyAction {
  fn act(&self) -> impl Future<Item=(), Error=Error> {
    // ...
  }
  fn description(&self) -> { "my action".to_owned() }
}

would desugar into

impl Action for MyAction {
  type ActReturn = MyActReturn;
  fn act(&self) -> Self::ActReturn {
    // ...
  }
  fn description(&self) -> { "my action".to_owned() }
}

where again, MyActReturn is a generated symbol for the unnameable type.

I imagine there are issues with visibility, but I don’t know what the rules are. I’m also sure I’m missing other stuff. Is this a workable approach? Are there insurmountable blockers?

We want to support this in the future & afaik there are just design questions, not blockers per se.

3 Likes

Missing link destination (no href)

Sorry, fixed!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.