Created
January 1, 2026 19:32
-
-
Save oconnor663/0577313b0873c38c0fc8102d5b148432 to your computer and use it in GitHub Desktop.
`return` from inside a `async` block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use core::pin::pin; | |
| use core::sync::atomic::{AtomicBool, Ordering::Relaxed}; | |
| use core::task::Poll; | |
| async fn foo() -> std::io::Result<i32> { | |
| let no_return = AtomicBool::new(false); | |
| let mut value = None; | |
| let mut fut = pin!(async { | |
| value = Some({ | |
| // begin user code | |
| if rand::random() { | |
| std::fs::File::open("non_existent_file")?; | |
| } | |
| 42 | |
| // end user code | |
| }); | |
| no_return.store(true, Relaxed); | |
| core::future::pending().await | |
| }); | |
| if let Some(ret) = core::future::poll_fn(|cx| { | |
| let ret = fut.as_mut().poll(cx); | |
| if no_return.load(Relaxed) { | |
| Poll::Ready(None) | |
| } else { | |
| ret.map(Some) | |
| } | |
| }) | |
| .await | |
| { | |
| return ret; | |
| } | |
| Ok(value.unwrap()) | |
| } | |
| #[tokio::main] | |
| async fn main() { | |
| for _ in 0..10 { | |
| eprintln!("{:?}", foo().await); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment