⚡ Async Rust
The Future Trait
Concept
A Future is a value that represents an asynchronous computation. It produces a result eventually, but not necessarily right now. Futures in Rust are lazy — they do nothing until they are polled by an executor.
This is different from JavaScript promises, which start executing immediately. A Rust Future only runs when you .await it or pass it to an executor like Tokio.
example.rs
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
// A simple Future that immediately returns a value
struct ReadyFuture(i32);
impl Future for ReadyFuture {
type Output = i32;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<i32> {
Poll::Ready(self.0) // Ready means the value is available now
// Poll::Pending would mean "come back later"
}
}
// In practice you almost never implement Future manually.
// async fn generates a Future automatically:
async fn double(x: i32) -> i32 {
x * 2 // the compiler wraps this in a Future for you
}Quick Check
What happens if you create a Future but never .await it?
1 / 3