« futures do nothing unless you .await or poll them » : Future et .await en Rust (E0728) "futures do nothing unless you .await or poll them": Future and .await in Rust (E0728)

En Rust, appeler une async fn ne lance rien : l'appel rend un future, une valeur inerte tant que personne ne la poll. Pourquoi une fonction async oubliée ne fait rien (warning « unused implementer of Future »), ce que font vraiment poll, Pending et Ready, pourquoi .await est refusé hors d'un contexte async (E0728) et pourquoi main ne peut pas être async (E0752). Animation et sorties réelles de rustc.In Rust, calling an async fn starts nothing: the call returns a future, a value that stays inert until someone polls it. Why a forgotten async function does nothing (the "unused implementer of Future" warning), what poll, Pending and Ready really do, why .await is refused outside an async context (E0728) and why main cannot be async (E0752). Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
AsyncAsync
PubliéPublished

En bref. Avec les threads, spawn lance le travail tout de suite. Avec async, c’est l’inverse : appeler une async fn ne lance rien. L’appel rend un future, et ce future ne fait rien tant que personne ne l’interroge. Ce modèle explique le bug silencieux le plus courant en Rust asynchrone (une fonction appelée qui ne s’exécute jamais) et les erreurs qu’on rencontre en premier : E0728, E0752, et le E0308 « found future ».

Le modèle en une phrase

Un future est une valeur qui décrit un calcul, pas un calcul en cours. Le créer ne lance rien. C’est poll qui le fait avancer, jusqu’au prochain .await, et .await est la façon normale de demander ce poll.

Si tu viens de JavaScript, c’est le point à désapprendre : une Promise est déjà partie quand tu la reçois, un Future Rust attend qu’on le pousse.

In short. With threads, spawn starts the work right away. With async, it’s the opposite: calling an async fn starts nothing. The call returns a future, and that future does nothing until someone queries it. This model explains the most common silent bug in asynchronous Rust (a function that is called and never runs) and the errors you meet first: E0728, E0752, and the E0308 “found future”.

The model in one sentence

A future is a value that describes a computation, not a computation in progress. Creating it starts nothing. poll is what makes it advance, up to the next .await, and .await is the normal way to ask for that poll.

If you come from JavaScript, this is the point to unlearn: a Promise is already running when you receive it, a Rust Future waits to be pushed.

println!("avant");
let f = telecharge();
println!("future créé");
Un futureA futureune valeur qui décrit un calcula value that describes a computationles états du futurethe future’s statessortie du programmeprogram outputpas démarrénot startedcorps non exécutébody not runterminédonepoll 1?avantfuture crééétat courantcurrent statedéjà exécuté ou détruitalready run or droppedsorties : rustc 1.100output: rustc 1.100un future est une valeur : on la stocke, on la passe, on la détruita future is a value: you store it, pass it around, drop ittelecharge() rend un future : rien n’a démarrételecharge() returns a future: nothing has started
  1. Appeler une async fn n'exécute pas son corps : l'appel rend un future, une valeur qui décrit le calcul. Ici « avant » et « future créé » s'affichent, mais pas « téléchargement lancé ». C'est l'inverse d'une promesse JavaScript, qui démarre dès sa création.Calling an async fn doesn't run its body: the call returns a future, a value that describes the computation. Here "avant" and "future créé" are printed, but not "téléchargement lancé". It's the opposite of a JavaScript promise, which starts as soon as it is created.
  2. Le bug silencieux : appeler sans .await. Le future est créé puis détruit aussitôt, sans jamais avoir été exécuté. Le programme affiche « avant » puis « après », et le téléchargement n'a pas eu lieu. Le compilateur ne refuse pas, il avertit.The silent bug: calling without .await. The future is created and dropped right away, without ever running. The program prints "avant" then "après", and the download never happened. The compiler doesn't refuse, it warns.
  3. Autre symptôme : traiter le future comme son résultat. telecharge() n'est pas un u32, c'est un future qui en produira un. Le compilateur le dit (E0308, « found future ») et propose la correction : .await.Another symptom: treating the future as its result. telecharge() isn't a u32, it's a future that will produce one. The compiler says so (E0308, "found future") and suggests the fix: .await.
  4. Pour qu'un future avance, quelqu'un doit l'interroger avec poll. Dans du code async, c'est .await qui s'en charge ; tout en haut, c'est un exécuteur (ici un block_on de dix lignes). Le corps ne s'exécute qu'à ce moment : « téléchargement lancé » arrive après « future créé ».For a future to make progress, someone has to query it with poll. In async code, .await takes care of it; at the very top, an executor does (here a ten-line block_on). The body only runs at that point: "téléchargement lancé" comes after "future créé".
Un future Rust est inerte : appeler une async fn n’exécute pas son corps. Sans .await, le compilateur avertit « unused implementer of `Future` that must be used » et rien ne se passe ; c’est le poll, déclenché par .await ou par un exécuteur, qui lance le calcul.A Rust future is inert: calling an async fn doesn’t run its body. Without .await, the compiler warns "unused implementer of `Future` that must be used" and nothing happens; the poll, triggered by .await or by an executor, is what starts the computation.

Créer n’est pas lancer

async fn telecharge() -> u32 {
    println!("  téléchargement lancé");
    42
}

fn main() {
    println!("avant");
    telecharge();
    println!("après");
}
warning: unused implementer of `Future` that must be used
 --> inerte.rs:8:5
  |
8 |     telecharge();
  |     ^^^^^^^^^^^^
  |
  = note: futures do nothing unless you `.await` or poll them
  = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default

Le programme compile, et affiche :

avant
après

téléchargement lancé n’apparaît pas. telecharge() a fabriqué un future, personne ne l’a interrogé, et il a été détruit à la fin de l’instruction. Ce n’est qu’un avertissement, pas une erreur : dans une sortie de compilation chargée, il passe facilement inaperçu.

Une async fn est en réalité une fonction ordinaire qui rend un future. Ces deux écritures sont équivalentes :

async fn a() -> u32 {
    42
}

fn b() -> impl Future<Output = u32> {
    async { 42 }
}

Le corps n’est pas « dans » la fonction : il est dans la valeur rendue. Appeler la fonction ne fait que construire cette valeur.

Qui lance le calcul

Le trait Future n’a qu’une méthode :

pub trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}

pub enum Poll<T> {
    Ready(T),
    Pending,
}

poll veut dire : « avance autant que tu peux, et dis-moi où tu en es ». Ready(valeur) si c’est terminé, Pending sinon. Un programme qui appelle poll en boucle jusqu’à Ready s’appelle un exécuteur. En voici un minimal, en dix lignes de bibliothèque standard :

use std::pin::pin;
use std::task::{Context, Poll, Waker};

fn block_on<F: Future>(f: F) -> F::Output {
    let mut f = pin!(f);
    let mut cx = Context::from_waker(Waker::noop());
    loop {
        if let Poll::Ready(v) = f.as_mut().poll(&mut cx) {
            return v;
        }
    }
}

Avec lui, le future s’exécute enfin :

fn main() {
    println!("avant");
    let f = telecharge();
    println!("future créé");
    let n = block_on(f);
    println!("après : {n}");
}
avant
future créé
  téléchargement lancé
après : 42

L’ordre des lignes est la preuve : téléchargement lancé arrive après future créé. C’est le poll qui exécute le corps, pas l’appel.

 let f = telecharge();        block_on(f)
 ┌───────────────────┐        ┌────────────────────────────┐
 │ future : inerte   │ ─────▶ │ poll ─▶ le corps s'exécute │ ─▶ Ready(42)
 └───────────────────┘        └────────────────────────────┘
   aucune ligne du corps        « téléchargement lancé »

Les erreurs autour de .await

Dans du code async, on n’appelle pas poll soi-même : on écrit .await. Mais .await n’est permis que là où une pause est possible.

Hors d’un contexte async : E0728.

fn main() {
    let n = telecharge().await;
    println!("{n}");
}
error[E0728]: `await` is only allowed inside `async` functions and blocks
 --> e0728.rs:6:26
  |
5 | fn main() {
  | --------- this is not `async`
6 |     let n = telecharge().await;
  |                          ^^^^^ only allowed inside `async` functions and blocks

Rendre main async ne suffit pas : E0752.

error[E0752]: `main` function is not allowed to be `async`
 --> e0752.rs:5:1
  |
5 | async fn main() {
  | ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`

Si main rendait un future, qui le pollerait ? La bibliothèque standard ne contient pas d’exécuteur. Il faut en apporter un : le block_on ci-dessus pour comprendre, une bibliothèque comme Tokio pour un vrai programme. #[tokio::main] génère justement une main ordinaire qui appelle block_on.

Prendre le future pour son résultat : E0308.

async fn total() -> u32 {
    let n: u32 = telecharge();
    n + 1
}
error[E0308]: mismatched types
 --> e0308.rs:6:18
  |
6 |     let n: u32 = telecharge();
  |            ---   ^^^^^^^^^^^^ expected `u32`, found future
  |            |
  |            expected due to this
  |
note: calling an async function returns a future
 --> e0308.rs:6:18
  |
6 |     let n: u32 = telecharge();
  |                  ^^^^^^^^^^^^
help: consider `await`ing on the `Future`
  |
6 |     let n: u32 = telecharge().await;
  |                              ++++++

Ici le compilateur donne à la fois le modèle (« calling an async function returns a future ») et la correction.

Un poll à la fois

Pour voir ce que fait poll, il faut un future qui ne soit pas prêt tout de suite. Pause rend Pending la première fois, Ready la seconde :

struct Pause(bool);

impl Future for Pause {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
        if self.0 {
            Poll::Ready(())
        } else {
            self.0 = true;
            Poll::Pending
        }
    }
}

async fn tache() -> u32 {
    println!("  étape 1");
    Pause(false).await;
    println!("  étape 2");
    Pause(false).await;
    println!("  étape 3");
    42
}

Interrogeons tache() à la main, trois fois :

let mut f = pin!(tache());
let mut cx = Context::from_waker(Waker::noop());
for i in 1..=3 {
    println!("poll n° {i}");
    let r = f.as_mut().poll(&mut cx);
    println!("  -> {r:?}");
}
poll n° 1
  étape 1
  -> Pending
poll n° 2
  étape 2
  -> Pending
poll n° 3
  étape 3
  -> Ready(42)

Chaque poll exécute le corps jusqu’au prochain .await qui n’est pas prêt, puis rend la main. Le suivant reprend exactement là.

            poll 1            poll 2            poll 3
 départ ──────────▶ pause 1 ──────────▶ pause 2 ──────────▶ terminé
         étape 1    .await     étape 2   .await    étape 3   Ready(42)
         Pending               Pending

Un .await est le seul endroit où un async fn peut s’interrompre. Entre deux .await, le code s’exécute d’une traite, comme du code ordinaire.

L’état est rangé dans le future

Pour reprendre « exactement là », il faut se souvenir d’où on en était, et des variables encore utiles. Le compilateur transforme chaque async fn en machine à états : une valeur dont la taille dépend de ce qui doit survivre à une pause.

async fn petit() -> u8 {
    1
}

async fn tampon_dans_un_bloc() {
    {
        let t = [0u8; 1024];
        println!("  {}", t.len());
    }
    Pause(false).await;
}

async fn tampon_a_travers() {
    let t = [0u8; 1024];
    Pause(false).await;
    println!("  {}", t.len());
}
petit               : 1 octet(s)
tampon_dans_un_bloc : 2 octets
tampon_a_travers    : 1026 octets

Mesuré avec size_of_val sur les futures, sans les exécuter. Le tableau de 1024 octets qui est encore vivant pendant le .await est stocké dans le future ; celui qui a fini sa vie avant ne l’est pas. Il n’y a pas de pile cachée ni d’allocation : un future est une structure, et sa taille est connue à la compilation.

Deux conséquences de la paresse

L’ordre d’exécution est celui des .await, pas celui des appels.

async fn etape(nom: &str) -> usize {
    println!("  {nom} : début");
    Pause(false).await;
    println!("  {nom} : fin");
    nom.len()
}

async fn tout() -> usize {
    let a = etape("a");
    let b = etape("b");
    println!("deux futures créés, rien n'a démarré");
    let nb = b.await;
    let na = a.await;
    na + nb
}
deux futures créés, rien n'a démarré
  b : début
  b : fin
  a : début
  a : fin
total : 2

a est créé en premier et s’exécute en dernier. Et les deux ne s’entremêlent pas : b va jusqu’au bout avant que a ne commence. Créer deux futures ne les fait pas tourner en même temps ; pour cela il faut un outil qui les polle tous les deux, sujet d’un prochain article.

Détruire un future, c’est l’annuler.

async fn tache() {
    let _t = Temoin;
    println!("  étape 1");
    Pause(false).await;
    println!("  étape 2 (jamais affichée)");
}

On l’interroge une fois, puis on le laisse sortir de portée (Temoin affiche un message dans son Drop) :

  étape 1
Pending
on abandonne le future
  Temoin détruit
fin

étape 2 ne s’exécute jamais. Personne n’a « tué » le calcul : on a simplement cessé de le poller, puis détruit la valeur. Les variables qu’elle contenait sont libérées normalement, par la possession.

Ce que l’image cache

  • Le block_on de cet article tourne à vide. Il rappelle poll en boucle sans jamais dormir. Un vrai exécuteur utilise le Waker passé dans le Context : le future le garde, et l’appelle quand il a du nouveau. Mesuré sur un minuteur de 100 ms : 2 polls avec un exécuteur qui dort jusqu’au réveil, plus de 100 000 avec la boucle naïve.
  • Un future terminé ne se poll plus. Un quatrième poll sur tache() donne un panic : « async fn resumed after completion ». .await et les exécuteurs s’arrêtent à Ready, donc tu ne le verras que si tu appelles poll à la main.
  • Pin. La signature de poll prend Pin<&mut Self> : la promesse que le future ne sera plus déplacé en mémoire une fois interrogé, parce que son état peut contenir des références vers lui-même. pin! s’en charge ici ; le détail mérite son propre article.
  • .await enchaîne, il ne parallélise pas. a.await; b.await; exécute a en entier puis b. La concurrence vient d’ailleurs (join, select, spawn d’un exécuteur).
  • Un bloc async est paresseux lui aussi. async { ... } fabrique un future sans exécuter son contenu, exactement comme l’appel d’une async fn.
  • Ne bloque pas dans un future. Entre deux .await, le future garde la main. Un thread::sleep ou un calcul long dans un async fn immobilise l’exécuteur, et toutes les tâches qu’il devait faire avancer.
  • Le langage ne fournit que le mécanisme. Le trait Future, async et .await sont dans le langage et std. L’exécuteur, les minuteurs et les entrées-sorties asynchrones viennent d’une bibliothèque.

Pour aller plus loin

Creating is not starting

async fn telecharge() -> u32 {
    println!("  téléchargement lancé");
    42
}

fn main() {
    println!("avant");
    telecharge();
    println!("après");
}
warning: unused implementer of `Future` that must be used
 --> inerte.rs:8:5
  |
8 |     telecharge();
  |     ^^^^^^^^^^^^
  |
  = note: futures do nothing unless you `.await` or poll them
  = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default

The program compiles, and prints:

avant
après

téléchargement lancé doesn’t show up. telecharge() built a future, nobody queried it, and it was dropped at the end of the statement. It’s only a warning, not an error: in a busy build output, it easily goes unnoticed.

An async fn is really an ordinary function that returns a future. These two spellings are equivalent:

async fn a() -> u32 {
    42
}

fn b() -> impl Future<Output = u32> {
    async { 42 }
}

The body isn’t “in” the function: it’s in the returned value. Calling the function only builds that value.

Who starts the computation

The Future trait has a single method:

pub trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}

pub enum Poll<T> {
    Ready(T),
    Pending,
}

poll means: “advance as far as you can, and tell me where you are”. Ready(value) if it’s finished, Pending otherwise. A program that calls poll in a loop until Ready is called an executor. Here is a minimal one, in ten lines of standard library:

use std::pin::pin;
use std::task::{Context, Poll, Waker};

fn block_on<F: Future>(f: F) -> F::Output {
    let mut f = pin!(f);
    let mut cx = Context::from_waker(Waker::noop());
    loop {
        if let Poll::Ready(v) = f.as_mut().poll(&mut cx) {
            return v;
        }
    }
}

With it, the future finally runs:

fn main() {
    println!("avant");
    let f = telecharge();
    println!("future créé");
    let n = block_on(f);
    println!("après : {n}");
}
avant
future créé
  téléchargement lancé
après : 42

The order of the lines is the proof: téléchargement lancé comes after future créé. The poll runs the body, not the call.

 let f = telecharge();        block_on(f)
 ┌───────────────────┐        ┌────────────────────────────┐
 │ future: inert     │ ─────▶ │ poll ─▶ the body runs      │ ─▶ Ready(42)
 └───────────────────┘        └────────────────────────────┘
   no line of the body          "téléchargement lancé"

The errors around .await

In async code, you don’t call poll yourself: you write .await. But .await is only allowed where a pause is possible.

Outside an async context: E0728.

fn main() {
    let n = telecharge().await;
    println!("{n}");
}
error[E0728]: `await` is only allowed inside `async` functions and blocks
 --> e0728.rs:6:26
  |
5 | fn main() {
  | --------- this is not `async`
6 |     let n = telecharge().await;
  |                          ^^^^^ only allowed inside `async` functions and blocks

Making main async isn’t enough: E0752.

error[E0752]: `main` function is not allowed to be `async`
 --> e0752.rs:5:1
  |
5 | async fn main() {
  | ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`

If main returned a future, who would poll it? The standard library contains no executor. You have to bring one: the block_on above to understand, a library such as Tokio for a real program. #[tokio::main] precisely generates an ordinary main that calls block_on.

Taking the future for its result: E0308.

async fn total() -> u32 {
    let n: u32 = telecharge();
    n + 1
}
error[E0308]: mismatched types
 --> e0308.rs:6:18
  |
6 |     let n: u32 = telecharge();
  |            ---   ^^^^^^^^^^^^ expected `u32`, found future
  |            |
  |            expected due to this
  |
note: calling an async function returns a future
 --> e0308.rs:6:18
  |
6 |     let n: u32 = telecharge();
  |                  ^^^^^^^^^^^^
help: consider `await`ing on the `Future`
  |
6 |     let n: u32 = telecharge().await;
  |                              ++++++

Here the compiler gives both the model (“calling an async function returns a future”) and the fix.

One poll at a time

To see what poll does, you need a future that isn’t ready right away. Pause returns Pending the first time, Ready the second:

struct Pause(bool);

impl Future for Pause {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
        if self.0 {
            Poll::Ready(())
        } else {
            self.0 = true;
            Poll::Pending
        }
    }
}

async fn tache() -> u32 {
    println!("  étape 1");
    Pause(false).await;
    println!("  étape 2");
    Pause(false).await;
    println!("  étape 3");
    42
}

Let’s query tache() by hand, three times:

let mut f = pin!(tache());
let mut cx = Context::from_waker(Waker::noop());
for i in 1..=3 {
    println!("poll n° {i}");
    let r = f.as_mut().poll(&mut cx);
    println!("  -> {r:?}");
}
poll n° 1
  étape 1
  -> Pending
poll n° 2
  étape 2
  -> Pending
poll n° 3
  étape 3
  -> Ready(42)

Each poll runs the body up to the next .await that isn’t ready, then yields. The next one resumes exactly there.

            poll 1            poll 2            poll 3
 start  ──────────▶ pause 1 ──────────▶ pause 2 ──────────▶ done
         étape 1    .await     étape 2   .await    étape 3   Ready(42)
         Pending               Pending

An .await is the only place where an async fn can be interrupted. Between two .await, the code runs straight through, like ordinary code.

The state is stored in the future

To resume “exactly there”, you have to remember where you were, and the variables still needed. The compiler turns every async fn into a state machine: a value whose size depends on what must survive a pause.

async fn petit() -> u8 {
    1
}

async fn tampon_dans_un_bloc() {
    {
        let t = [0u8; 1024];
        println!("  {}", t.len());
    }
    Pause(false).await;
}

async fn tampon_a_travers() {
    let t = [0u8; 1024];
    Pause(false).await;
    println!("  {}", t.len());
}
petit               : 1 octet(s)
tampon_dans_un_bloc : 2 octets
tampon_a_travers    : 1026 octets

Measured with size_of_val on the futures, without running them. The 1024-byte array that is still alive during the .await is stored in the future; the one whose life ended before is not. There is no hidden stack and no allocation: a future is a struct, and its size is known at compile time.

Two consequences of laziness

Execution order is the order of the .await, not of the calls.

async fn etape(nom: &str) -> usize {
    println!("  {nom} : début");
    Pause(false).await;
    println!("  {nom} : fin");
    nom.len()
}

async fn tout() -> usize {
    let a = etape("a");
    let b = etape("b");
    println!("deux futures créés, rien n'a démarré");
    let nb = b.await;
    let na = a.await;
    na + nb
}
deux futures créés, rien n'a démarré
  b : début
  b : fin
  a : début
  a : fin
total : 2

a is created first and runs last. And the two don’t interleave: b goes all the way before a begins. Creating two futures doesn’t make them run at the same time; for that you need a tool that polls both, the topic of an upcoming article.

Dropping a future cancels it.

async fn tache() {
    let _t = Temoin;
    println!("  étape 1");
    Pause(false).await;
    println!("  étape 2 (jamais affichée)");
}

We query it once, then let it go out of scope (Temoin prints a message in its Drop):

  étape 1
Pending
on abandonne le future
  Temoin détruit
fin

étape 2 never runs. Nobody “killed” the computation: we simply stopped polling it, then dropped the value. The variables it contained are freed normally, through ownership.

What the picture hides

  • This article’s block_on spins. It calls poll again in a loop without ever sleeping. A real executor uses the Waker passed in the Context: the future keeps it, and calls it when it has news. Measured on a 100 ms timer: 2 polls with an executor that sleeps until woken, more than 100,000 with the naive loop.
  • A finished future is not polled again. A fourth poll on tache() gives a panic: “async fn resumed after completion”. .await and executors stop at Ready, so you’ll only see it if you call poll by hand.
  • Pin. The signature of poll takes Pin<&mut Self>: the promise that the future won’t be moved in memory once polled, because its state may contain references to itself. pin! handles it here; the detail deserves its own article.
  • .await sequences, it doesn’t parallelise. a.await; b.await; runs a entirely and then b. Concurrency comes from elsewhere (join, select, an executor’s spawn).
  • An async block is lazy too. async { ... } builds a future without running its content, exactly like calling an async fn.
  • Don’t block inside a future. Between two .await, the future keeps control. A thread::sleep or a long computation in an async fn freezes the executor, and every task it was supposed to advance.
  • The language only provides the mechanism. The Future trait, async and .await are in the language and std. The executor, timers and asynchronous I/O come from a library.

Going further

Questions fréquentesFrequently asked questions

Pourquoi ma fonction async ne fait-elle rien quand je l'appelle ?Why does my async function do nothing when I call it?

Parce qu'appeler une async fn n'exécute pas son corps : l'appel rend un future, une valeur qui décrit le calcul. Tant que personne ne l'interroge avec poll, rien ne se passe. Si tu écris telecharge(); sans .await, le future est créé puis détruit aussitôt. Le compilateur avertit : « unused implementer of Future that must be used », avec la note « futures do nothing unless you .await or poll them ». Ajoute .await dans du code async, ou confie le future à un exécuteur.Because calling an async fn doesn't run its body: the call returns a future, a value that describes the computation. Until someone queries it with poll, nothing happens. If you write telecharge(); without .await, the future is created and dropped right away. The compiler warns: "unused implementer of Future that must be used", with the note "futures do nothing unless you .await or poll them". Add .await in async code, or hand the future to an executor.

Que signifie l'erreur E0728, « await is only allowed inside async functions and blocks » ?What does error E0728, "await is only allowed inside async functions and blocks", mean?

Tu as écrit .await dans une fonction qui n'est pas async. .await a besoin de pouvoir mettre la fonction en pause et rendre la main, et seule une fonction compilée en machine à états (async fn ou bloc async) sait le faire. Deux corrections : rendre la fonction englobante async, ce qui remonte la question à son appelant ; ou, tout en haut du programme, passer le future à un exécuteur avec block_on.You wrote .await in a function that isn't async. .await needs to be able to pause the function and yield, and only a function compiled into a state machine (an async fn or an async block) can do that. Two fixes: make the enclosing function async, which pushes the question up to its caller; or, at the very top of the program, pass the future to an executor with block_on.

Quelle est la différence entre un Future Rust et une Promise JavaScript ?What is the difference between a Rust Future and a JavaScript Promise?

Une Promise JavaScript démarre dès sa création : le travail est déjà en cours, et await ne fait qu'attendre le résultat. Un Future Rust est inerte : créé, il n'a exécuté aucune ligne, et c'est le premier poll (déclenché par .await ou par un exécuteur) qui lance le corps. Conséquence directe : oublier await en JavaScript laisse quand même la requête partir ; l'oublier en Rust fait qu'elle ne part jamais. Autre conséquence : deux futures créés puis attendus l'un après l'autre s'exécutent l'un après l'autre, pas en parallèle.A JavaScript Promise starts as soon as it is created: the work is already under way, and await only waits for the result. A Rust Future is inert: once created, it hasn't run a single line, and the first poll (triggered by .await or by an executor) is what starts the body. Direct consequence: forgetting await in JavaScript still lets the request go out; forgetting it in Rust means it never goes out. Another consequence: two futures created and then awaited one after the other run one after the other, not in parallel.

Que font poll, Pending et Ready ?What do poll, Pending and Ready do?

poll est l'unique méthode du trait Future : elle fait avancer le calcul autant que possible, puis rend Poll::Ready(valeur) s'il est terminé, ou Poll::Pending s'il doit attendre. Pour un async fn, chaque poll exécute le corps jusqu'au prochain .await qui n'est pas prêt. Mesuré sur une fonction à deux .await : trois polls, qui rendent Pending, Pending puis Ready(42). Un quatrième poll provoque un panic, « async fn resumed after completion ».poll is the Future trait's only method: it advances the computation as far as possible, then returns Poll::Ready(value) if it is finished, or Poll::Pending if it has to wait. For an async fn, each poll runs the body up to the next .await that isn't ready. Measured on a function with two .await: three polls, returning Pending, Pending and then Ready(42). A fourth poll triggers a panic, "async fn resumed after completion".

Pourquoi main ne peut-elle pas être async en Rust ?Why can't main be async in Rust?

Parce que quelqu'un doit poller le future que main rendrait, et la bibliothèque standard ne fournit pas d'exécuteur. Écrire async fn main() donne E0752, « main function is not allowed to be async ». Le langage définit le trait Future et la syntaxe async/.await ; la boucle qui interroge les futures et les réveille vient d'une bibliothèque (Tokio, smol, etc.). L'attribut #[tokio::main] ne fait rien de magique : il génère une main ordinaire qui crée un exécuteur et appelle block_on sur ton code async.Because someone has to poll the future main would return, and the standard library provides no executor. Writing async fn main() gives E0752, "main function is not allowed to be async". The language defines the Future trait and the async/.await syntax; the loop that polls futures and wakes them comes from a library (Tokio, smol, and so on). The #[tokio::main] attribute does nothing magical: it generates an ordinary main that creates an executor and calls block_on on your async code.

RustAsyncFutureawaitModèle mental

← Tous les articlesAll articles