Skip to content

Generators should be able to yield references to local variables #98740

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
M1cha opened this issue Jun 30, 2022 · 3 comments
Open

Generators should be able to yield references to local variables #98740

M1cha opened this issue Jun 30, 2022 · 3 comments
Labels
A-coroutines Area: Coroutines

Comments

@M1cha
Copy link

M1cha commented Jun 30, 2022

Consider this:

let mut generator = || {
    let mut buf = [0u8; 4];
    yield &buf[..];
    
    buf[0] = 0;
    yield &buf[..];
};

Currently, this causes:
error[E0515]: cannot yield value referencing local variable buf

I don't see a reason why the compiler couldn't track that lifetime like it does when returning references to self from synchronous functions. As long as you want to use the return value, you'd simply not be allowed to call resume() since you'd need a reference to the generator for that.

Admittedly it'd currently be impossible (to my knowledge) to write a reference-yielding Generator manually by implementing the trait since you can't specify the lifetimes properly. It might be possible using GAT but afaik that'd require a change to the signature of the Generator trait.

@compiler-errors
Copy link
Member

Admittedly it'd currently be impossible (to my knowledge) to write a reference-yielding Generator manually by implementing the trait since you can't specify the lifetimes properly.

I think this is exactly why this is an issue. Generators just lower down to special objects that implement the Generator trait -- there's no way to express this lifetime relationship, since the yield type of a generator cannot capture the lifetime of the self passed in.

@clubby789
Copy link
Contributor

@rustbot label +A-generators

@rustbot rustbot added the A-coroutines Area: Coroutines label Mar 30, 2023
@vilunov
Copy link

vilunov commented Sep 19, 2023

I think this particular feature would be possible after something like #69268 is implemented

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-coroutines Area: Coroutines
Projects
None yet
Development

No branches or pull requests

5 participants