Concret Opaque Type

Opaque Type are an execellent design in Rust as it prevents users from relying on the specific return type of a function, especially useful in the context of compiler-generated Future state machines. Consider the following codes:

trait Foo: Sized {
    async fn foo();
}

Please note the following two facts:

  1. Foo::foo returns an impl Future<Output=()> object: The opaque type here prevents external codes to rely on the size of this state machine.
  2. Foo requires the object to be Sized: This makes Foo no longer 'dyn compatible', then at everytime whether Foo::foo is called, the compiler knows the exact type of the return value (an impl Future<Output=()> object), but the user can't touch it.

This design makes sure the compiler can store it on the stack and allow further operations on the returned Future object. For instance, you can pass it to another function, call Box::pin to pin it on the stack, etc.

Calling foo.foo().await is good due to previous designs. However, opaque types become problematic when it comes to non-compiler generated state machines, as you have to write the following codes.

enum State {
    ...
    WaitingFoo(impl Future<Output=()>),
    ...
}

Note this is not valid in Rust now. Since rustc doesn't know the exact type of impl Future<Output=()>, it can't calculate the space it requires for storing this future.

A workaround for this issue is to store Pin<Box<dyn Future<Output=()>>>, but it requires an extra heap allocation and might lead to performance issue.

Therefore, I suggest Rust to add the so-called Concret Opaque Type. Since Opaque Type is currently only available at the return value of a function, it's possible to have some syntax like:

enum State {
    ...
    WaitingFoo(opaque_type!(Foo::foo)),
    ...
}

so developers can store these fields directly in the state machine rather than on the heap.

The opaque_type macro or something similar should take generic into consideration.

How is that different from dyn Trait?

(post deleted by author)