rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
96.62k stars 12.48k forks source link

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

Open M1cha opened 2 years ago

M1cha commented 2 years ago

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 commented 2 years ago

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 commented 1 year ago

@rustbot label +A-generators

vilunov commented 11 months ago

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