Pre-RFC: Generator resume args

I woke up this morning and for no other reason tried to figure out how to do the underlying implementation in a way that would make sense and resolved it would have to look like this.

I think it would work better conceptually if we considered the additional values to the generator to be ‘context’ rather than ‘args’ and for the type of that to be an associated type rather than a type argument of the trait. I say this as access to the args/context in a first-class generator would be accessed through some operator/keyword which would act like a variable within the generator, the type of which could be inferred to be a single concrete type.

In practice, I would expect to have some additional keyword/operation to access the current context of a generator within a given generator function or block which could be used to pass the context to the poll function.

It would also be nice to preserve the current generator API by doing something simple like defaulting the type of context on first-class generators to () and having an additional generator trait that subclasses the version with arguments/context where it has the type () that doesn’t require a context to be passed.

trait GeneratorWithContext {
    type Yield;
    type Return;
    type Context;

    fn resume(self: Pin<&mut Self>, context: Context) -> GeneratorState<Self::Yield, Self::Return>;
}

trait Generator: GeneratorWithContext<Context = ()> {
    fn resume(self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return>;
}
1 Like