Coroutines / Generators - Resume with a value after a Yield?
from van2z@lemmy.world to rust@programming.dev on 17 Jan 2024 14:30
https://lemmy.world/post/10827369

Please let me know if this is possible…

I would like to be able to have a coroutine / generator yield to resume with a value.

This is a simplified version of what I am looking for:

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=8be2f397f600236b66970fce5c0ecab6

In this example, yield would end up requesting from the parent, that it wants to read the next byte, and the parent would resume the coroutine with the next byte. (In this case, it’s hardcoded to 54, but it can be any value.)

Yet it seems like Rust doesn’t have the ability to resume a yield with a value.

Is there any way I can get this to work?

#rust

threaded - newest

taladar@sh.itjust.works on 17 Jan 2024 15:29 next collapse

I think your playground link might be broken because of all the amp bits.

van2z@lemmy.world on 17 Jan 2024 15:49 collapse

You are right. I fixed it just now. That is an annoying “feature” of lemmy…

sugar_in_your_tea@sh.itjust.works on 17 Jan 2024 16:27 next collapse

Amp is a Google thing, not a Lemmy thing. I can’t see the original, so I can’t tell if it’s a Lemmy thing or some client that has issues.

lolcatnip@reddthat.com on 17 Jan 2024 22:57 collapse

They’re talking about &, the HTML code for an ampersand.

sugar_in_your_tea@sh.itjust.works on 17 Jan 2024 23:38 collapse

Ah, thanks. :)

mac@programming.dev on 17 Jan 2024 16:34 collapse

Converting ampersands to say amp instead is a bug that got fixed in version 0.19, world hasnt upgraded yet though

sugar_in_your_tea@sh.itjust.works on 18 Jan 2024 01:18 collapse

Is there any way I can get this to work?

Probably not, but it has been suggested. I’m a little surprised that yield is an expression here, because the RFC seems to only allow it as a statement.

The only way I can think of doing it is to use something like a channel (send the receive end to the coroutine) and read right after yielding. Nothing in the API suggests that they’ve taken that into account yet.

Maybe it’s going to be addressed in a follow-up RFC? Like maybe there will be an optional resume_with_value() or something?