Specialization, associated types (again?) and type alias impl taits

I'm playing around the nightly rust and I run into a problem of providing default implementation for traits:

trait Trait {
    type Foo<'a>: Future<Output = u32>;
    fn foo<'a>(&'a self) -> Self::Foo<'a>;
    type FooMany<'a>: Future<Output = ()>;
    fn foo_many<'a>(&'a self, out: &mut [u32]) -> FooMany<'a>;
    type Bar;
    fn bar(&self, bar: Self::Bar);
}

It would be nice if foo_many could be provided with default implementation:

default trait Tait {
    type FooMany<'a> = impl Future<Output = ()>;
    fn foo_many<'a>(&'a self, out: &mut [u32]) -> FooMany<'a> {
        for elem in out.iter_mut() {
            *elem = self.foo().await;
        }
    }
    type Bar = Void;
    fn bar(&self, bar: Self::Bar) {
        unreachable(bar);
    }
}

This won't work as Self::FooMany is still considered unknown by compiler. Are there any plans to lift the restriction so that such code is allowed?

I would assume that if the restriction is lifted the code:

impl Trait for u32 {
    type Foo<'a> = impl Future<Output = u32>;
    fn foo<'a>(&'a self) -> Self::Foo<'a> {
        async move {
            *self
        }
    }
    type FooMany<'a> = ...;
    type Bar = something other than void;
}

Would fail with appropiate error.

I will also note that Bar can be workaround by:

trait TraitAux {
    type Bar;
}
trait Trait {
    type Foo<'a>: Future<Output = u32>;
    fn foo<'a>(&'a self) -> Self::Foo<'a>;
    type FooMany<'a>: Future<Output = ()>;
    fn foo_many<'a>(&'a self, out: &mut [u32]) -> FooMany<'a>;
    type Bar;
    fn bar(&self, bar: Self::Bar);
}

default impl<T> TraitAux for T {
   type Bar = Void;
}

default impl<T: Trait<Bar = Void>> Trait for T {
    fn bar(&self, bar: Self::Bar) {
        unreachable(bar);
    }
}

But it doesn't work for impl Trait.

You could try using existential types. This question is better directed towards users.rust-lang.org. Internals is for discussions around the design and implementation of The Rust Programming Language.

Sorry. I will in future.

Anyway - existential types don't seem to be implemented yet?

They should be implemented on nightly... what did you try?

The syntax implemented on nightly is different from the original RFC. It's described in RFC 2515 (impl Trait in type aliases). It requires the unstable #![feature(type_alias_impl_trait)].

Thanks. I tried several variation of the syntax. Anyway - that doesn't seems to solve the issue from the original post as I already use min_type_alias_impl_trait?

I tried several iterations but I fail to see how it solves default implementation as I was only able to do it in impl block and it doesn't seem to lift restrictions?

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