I am attempting to create simplest possible example that can get async fn hello()
to eventually print out Hello World!
. This should happen without any external dependency like tokio
, just plain Rust and std
. Bonus points if we can get it done without ever using unsafe
.
#![feature(async_await)]
async fn hello() {
println!("Hello, World!");
}
fn main() {
let task = hello();
// Something beautiful happens here, and `Hello, World!` is printed on screen.
}
- I know
async/await
is still a nightly feature, and it is subject to change in the foreseeable future.
- I know there is a whole lot of
Future
implementations, I am aware of the existence of tokio
.
- I am just trying to educate myself on the inner workings of standard library futures.
My helpless, clumsy endeavours
My vague understanding is that, first off, I need to Pin
task down. So I went ahead and
let pinned_task = Pin::new(&mut task);
but
the trait `std::marker::Unpin` is not implemented for `std::future::GenFuture<[static generator@src/main.rs:7:18: 9:2 {}]>`
so I thought, of course, I probably need to Box
it, so I'm sure it won't move around in memory. Somewhat surprisingly, I get the same error.
What I could get so far is
let pinned_task = unsafe {
Pin::new_unchecked(&mut task)
};
which is obviously not something I should do. Even so, let's say I got my hands on the Pin
ned Future
. Now I need to poll()
it somehow. For that, I need a Waker
.
So I tried to look around on how to get my hands on a Waker
. On the doc it kinda looks like the only way to get a Waker
is with another new_unchecked
that accepts a RawWaker
. From there I got here and from there here, where I just curled up on the floor and started crying.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…