« the ? operator can only be used in a function that returns Result » (E0277) : Result et ? en Rust, le modèle mental "the ? operator can only be used in a function that returns Result" (E0277): Result and ? in Rust, the mental model

Une exception saute par-dessus le code ; un Result le traverse à découvert. Chaque ? est une sortie écrite dans la fonction, et l'appelant doit pouvoir la recevoir (E0277), dans le bon type d'erreur (From). Animation et sorties réelles de rustc.An exception jumps over the code; a Result crosses it in plain sight. Each ? is an exit written into the function, and the caller must be able to receive it (E0277), in the right error type (From). Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
ErreursErrors
PubliéPublished

En bref. En Rust, une fonction qui peut échouer le dit dans son type de retour, Result<T, E>. L’opérateur ? déballe le Ok et, sur un Err, quitte la fonction en renvoyant l’erreur à l’appelant. Deux conditions : l’appelant doit pouvoir recevoir une erreur (sinon E0277, the ? operator can only be used in a function that returns Result), et l’erreur doit se convertir dans son type (sinon E0277, ? couldn’t convert the error).

Le modèle en une phrase

Une exception saute par-dessus le code. Un Result le traverse à découvert : chaque ? est une sortie de secours écrite à l’endroit exact où l’échec peut arriver.

L’article sur Option rendait l’absence obligatoire à traiter. Result fait la même chose pour l’échec, avec une différence : la boîte vide porte une raison.

In short. In Rust, a function that can fail says so in its return type, Result<T, E>. The ? operator unwraps the Ok and, on an Err, leaves the function and returns the error to the caller. Two conditions: the caller must be able to receive an error (otherwise E0277, the ? operator can only be used in a function that returns Result), and the error must convert into its type (otherwise E0277, ? couldn’t convert the error).

The model in one sentence

An exception jumps over the code. A Result crosses it in plain sight: each ? is an emergency exit written at the exact spot where failure can happen.

The article on Option made absence mandatory to handle. Result does the same for failure, with one difference: the empty box carries a reason.

fn lire_port(texte: &str) -> Result<u16, ParseIntError> {
let port = texte.trim().parse::<u16>()?;
Ok(port)
}
Deux rails : Ok et ErrTwo rails: Ok and Err? sort au premier Err? exits at the first Errfn lire_port(texte) -> Result<u16, ParseIntError>ErrErrOktexte.trim().parse::<u16>()?Ok(port)jamais exécuténever runsappelantcallerlire_port("8080")lire_port("8080")Ok(8080)Ok(8080)le chemin Ok : chaque ? laisse passerthe Ok path: every ? lets it throughvérifié avec rustc 1.100checked with rustc 1.100
  1. Avec "8080", parse renvoie Ok. Le ? déballe la valeur, la fonction descend jusqu'à Ok(port).With "8080", parse returns Ok. The ? unwraps the value, the function runs down to Ok(port).
  2. Avec "80a", parse renvoie Err. Le ? sort de la fonction sur-le-champ : Ok(port) ne s'exécute jamais, l'erreur arrive chez l'appelant.With "80a", parse returns Err. The ? leaves the function on the spot: Ok(port) never runs, the error reaches the caller.
  3. L'appelant est main, qui renvoie (). Il n'a pas de porte pour une erreur : E0277, the `?` operator can only be used in a function that returns `Result` or `Option`.The caller is main, which returns (). It has no door for an error: E0277, the `?` operator can only be used in a function that returns `Result` or `Option`.
  4. Le correctif que propose rustc : main renvoie Result<(), Box<dyn Error>>. L'erreur remonte, Rust l'affiche, Error: ParseIntError { kind: InvalidDigit }, code de sortie 1.The fix rustc suggests: main returns Result<(), Box<dyn Error>>. The error goes up, Rust prints it, Error: ParseIntError { kind: InvalidDigit }, exit code 1.
Result en Rust : la fonction descend sur le chemin Ok ; à chaque ?, une Err sort tout de suite vers l'appelant. Si l'appelant renvoie (), E0277 : the `?` operator can only be used in a function that returns `Result` or `Option`.Result in Rust: the function runs down the Ok path; at each ?, an Err leaves right away for the caller. If the caller returns (), E0277: the `?` operator can only be used in a function that returns `Result` or `Option`.

Deux rails et des portes

parse peut échouer, et son type le dit : Result<u16, ParseIntError>. On l’appelle dans une fonction qui le dit aussi :

use std::num::ParseIntError;

fn lire_port(texte: &str) -> Result<u16, ParseIntError> {
    let port = texte.trim().parse::<u16>()?;
    Ok(port)
}

Lisez la fonction comme un rail qui descend. Avec "8080", parse renvoie Ok(8080), le ? en sort 8080, on arrive à Ok(port). Avec "80a", parse renvoie Err, et le ? ouvre une porte sur le côté : la fonction s’arrête là et renvoie Err(ParseIntError). La ligne Ok(port) ne s’exécute jamais.

 texte.trim()
      │
 .parse::<u16>()? ──── Err ───▶  appelant
      │ Ok
 Ok(port) ──────────── Ok ────▶  appelant

Avec une exception, la même porte existerait, mais sans dessin : rien dans la signature, rien sur la ligne. Ici, elle se voit deux fois : dans le type de retour et dans le ?.

L’appelant doit avoir une porte : E0277

Appelons lire_port depuis main, comme on le ferait d’abord :

fn main() {
    let port = lire_port("80a")?;
    println!("port {port}");
}
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
  --> src/main.rs:9:32
   |
 8 | fn main() {
   | --------- this function should return `Result` or `Option` to accept `?`
 9 |     let port = lire_port("80a")?;
   |                                ^ cannot use the `?` operator in a function that returns `()`
   |
help: consider adding return type
   |
 8 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
 9 |     let port = lire_port("80a")?;
10 |     println!("port {port}");
11 +     Ok(())
   |

Le ? veut renvoyer l’erreur à l’appelant de main, mais main renvoie () : il n’y a pas de place pour un Err. La porte donne sur un mur. rustc propose la correction, et elle marche :

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let port = lire_port("80a")?;
    println!("port {port}");
    Ok(())
}
Error: ParseIntError { kind: InvalidDigit }

Le programme s’arrête avec le code de sortie 1, pas de panic. Rust affiche l’erreur avec son format Debug, d’où les accolades.

La porte convertit : couldn't convert the error

Lisons maintenant le port dans un fichier. Deux opérations peuvent échouer, avec deux erreurs différentes :

use std::fs;
use std::num::ParseIntError;

fn lire_port(chemin: &str) -> Result<u16, ParseIntError> {
    let texte = fs::read_to_string(chemin)?;
    let port = texte.trim().parse::<u16>()?;
    Ok(port)
}
error[E0277]: `?` couldn't convert the error to `ParseIntError`
 --> src/main.rs:5:43
  |
4 | fn lire_port(chemin: &str) -> Result<u16, ParseIntError> {
  |                               -------------------------- expected `ParseIntError` because of this
5 |     let texte = fs::read_to_string(chemin)?;
  |                 --------------------------^ the trait `From<std::io::Error>` is not implemented for `ParseIntError`
  |                 |
  |                 this can't be annotated with `?` because it has type `Result<_, std::io::Error>`
  |
  = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait

La note dit tout : à la sortie, ? passe l’erreur dans From::from. À peu près, ? s’écrit :

let texte = match fs::read_to_string(chemin) {
    Ok(t) => t,
    Err(e) => return Err(From::from(e)),
};

Il faudrait From<io::Error> for ParseIntError, qui n’existe pas, et n’a pas à exister : une erreur de lecture n’est pas une erreur de format. C’est le type d’erreur de la fonction qu’il faut élargir.

Première sortie, Box<dyn Error>. Toute erreur standard s’y convertit :

fn lire_port(chemin: &str) -> Result<u16, Box<dyn Error>> {
    let texte = fs::read_to_string(chemin)?;
    let port = texte.trim().parse::<u16>()?;
    Ok(port)
}

Sur un fichier absent, l’appelant reçoit une erreur qui s’affiche No such file or directory (os error 2). C’est parfait pour un main ou un script. Le prix : l’appelant ne sait plus, par le type, quelle erreur c’était.

Seconde sortie, un enum et un From par source :

#[derive(Debug)]
enum ErreurConfig {
    Lecture(io::Error),
    Format(ParseIntError),
}

impl From<io::Error> for ErreurConfig {
    fn from(e: io::Error) -> Self { ErreurConfig::Lecture(e) }
}
impl From<ParseIntError> for ErreurConfig {
    fn from(e: ParseIntError) -> Self { ErreurConfig::Format(e) }
}

fn lire_port(chemin: &str) -> Result<u16, ErreurConfig> {
    let texte = fs::read_to_string(chemin)?;
    let port = texte.trim().parse::<u16>()?;
    Ok(port)
}

Le corps de lire_port ne change pas : les deux ? trouvent leur From. L’appelant, lui, peut décider selon la variante :

match lire_port(c) {
    Ok(p) => println!("{c} : port {p}"),
    Err(ErreurConfig::Lecture(e)) => println!("{c} : illisible ({e})"),
    Err(e @ ErreurConfig::Format(_)) => println!("{c} : {e}"),
}
absent.txt : illisible (No such file or directory (os error 2))
mauvais.txt : format : invalid digit found in string
bon.txt : port 8080

(Pour la dernière ligne, ErreurConfig implémente aussi Display.) C’est l’enum de l’article sur match, appliqué aux erreurs : un bras oublié serait E0004.

Un Result qu’on ignore ne passe pas en silence

fs::write("/nonexistent-dir/x.txt", "x");
println!("fini");
warning: unused `Result` that must be used
 --> src/main.rs:3:5
  |
3 |     fs::write("/nonexistent-dir/x.txt", "x");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this `Result` may be an `Err` variant, which should be handled
  = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default

Ce n’est qu’un avertissement, et le programme affiche fini alors que l’écriture a échoué. Mais l’échec a été signalé à la compilation : Result est marqué #[must_use]. Pour l’ignorer exprès, on l’écrit : let _ = fs::write(…);.

Ce que l’image cache

  • unwrap partout, c’est l’exception non gérée. lire_port("80a").unwrap() compile et s’arrête avec called Result::unwrap() on an Err value: ParseIntError { kind: InvalidDigit }, code 101. Une entrée invalide est une erreur attendue : elle se propage. unwrap est pour un bug, un invariant violé ; c’est le sujet des deux prochains numéros.
  • ? marche aussi sur Option, mais on ne mélange pas. lignes.first()? dans une fonction qui renvoie Result donne E0277 the ? operator can only be used on Results, not Options, et rustc propose .ok_or(...)? : on donne une raison à l’absence.
  • main -> Result affiche le Debug, pas un message soigné. Pour un outil en ligne de commande, on fait souvent un match final dans main pour imprimer l’erreur avec Display et choisir le code de sortie.
  • Les bibliothèques connues ne font qu’écrire ce code pour vous. thiserror génère l’enum, Display et les From ; anyhow est un Box<dyn Error> avec du contexte. Le modèle reste le même : une valeur de retour, et des portes.

Pour aller plus loin

Two tracks and some doors

parse can fail, and its type says so: Result<u16, ParseIntError>. We call it from a function that says so too:

use std::num::ParseIntError;

fn lire_port(texte: &str) -> Result<u16, ParseIntError> {
    let port = texte.trim().parse::<u16>()?;
    Ok(port)
}

Read the function (lire_port, “read port”) as a track running downward. With "8080", parse returns Ok(8080), the ? takes out 8080, we reach Ok(port). With "80a", parse returns Err, and the ? opens a side door: the function stops there and returns Err(ParseIntError). The Ok(port) line never runs.

 texte.trim()
      │
 .parse::<u16>()? ──── Err ───▶  caller
      │ Ok
 Ok(port) ──────────── Ok ────▶  caller

With an exception, the same door would exist, but undrawn: nothing in the signature, nothing on the line. Here it shows twice: in the return type and in the ?.

The caller needs a door: E0277

Let’s call lire_port from main, as you would at first:

fn main() {
    let port = lire_port("80a")?;
    println!("port {port}");
}
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
  --> src/main.rs:9:32
   |
 8 | fn main() {
   | --------- this function should return `Result` or `Option` to accept `?`
 9 |     let port = lire_port("80a")?;
   |                                ^ cannot use the `?` operator in a function that returns `()`
   |
help: consider adding return type
   |
 8 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
 9 |     let port = lire_port("80a")?;
10 |     println!("port {port}");
11 +     Ok(())
   |

The ? wants to return the error to main’s caller, but main returns (): there is no room for an Err. The door opens onto a wall. rustc suggests the fix, and it works:

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let port = lire_port("80a")?;
    println!("port {port}");
    Ok(())
}
Error: ParseIntError { kind: InvalidDigit }

The program stops with exit code 1, no panic. Rust prints the error with its Debug format, hence the braces.

The door converts: couldn't convert the error

Now read the port from a file. Two operations can fail, with two different errors:

use std::fs;
use std::num::ParseIntError;

fn lire_port(chemin: &str) -> Result<u16, ParseIntError> {
    let texte = fs::read_to_string(chemin)?;
    let port = texte.trim().parse::<u16>()?;
    Ok(port)
}
error[E0277]: `?` couldn't convert the error to `ParseIntError`
 --> src/main.rs:5:43
  |
4 | fn lire_port(chemin: &str) -> Result<u16, ParseIntError> {
  |                               -------------------------- expected `ParseIntError` because of this
5 |     let texte = fs::read_to_string(chemin)?;
  |                 --------------------------^ the trait `From<std::io::Error>` is not implemented for `ParseIntError`
  |                 |
  |                 this can't be annotated with `?` because it has type `Result<_, std::io::Error>`
  |
  = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait

The note says it all: on the way out, ? runs the error through From::from. Roughly, ? reads:

let texte = match fs::read_to_string(chemin) {
    Ok(t) => t,
    Err(e) => return Err(From::from(e)),
};

That would need From<io::Error> for ParseIntError, which doesn’t exist and shouldn’t: a read error is not a format error. It’s the function’s error type that must grow.

First way out, Box<dyn Error>. Any standard error converts into it:

fn lire_port(chemin: &str) -> Result<u16, Box<dyn Error>> {
    let texte = fs::read_to_string(chemin)?;
    let port = texte.trim().parse::<u16>()?;
    Ok(port)
}

On a missing file, the caller gets an error that prints as No such file or directory (os error 2). Perfect for a main or a script. The price: from the type alone, the caller no longer knows which error it was.

Second way out, an enum and one From per source (ErreurConfig, “config error”, with variants Lecture, “read”, and Format):

#[derive(Debug)]
enum ErreurConfig {
    Lecture(io::Error),
    Format(ParseIntError),
}

impl From<io::Error> for ErreurConfig {
    fn from(e: io::Error) -> Self { ErreurConfig::Lecture(e) }
}
impl From<ParseIntError> for ErreurConfig {
    fn from(e: ParseIntError) -> Self { ErreurConfig::Format(e) }
}

fn lire_port(chemin: &str) -> Result<u16, ErreurConfig> {
    let texte = fs::read_to_string(chemin)?;
    let port = texte.trim().parse::<u16>()?;
    Ok(port)
}

The body of lire_port doesn’t change: both ? find their From. The caller, for its part, can decide by variant:

match lire_port(c) {
    Ok(p) => println!("{c} : port {p}"),
    Err(ErreurConfig::Lecture(e)) => println!("{c} : illisible ({e})"),
    Err(e @ ErreurConfig::Format(_)) => println!("{c} : {e}"),
}
absent.txt : illisible (No such file or directory (os error 2))
mauvais.txt : format : invalid digit found in string
bon.txt : port 8080

(For the last arm, ErreurConfig also implements Display.) That’s the enum from the match article, applied to errors: a forgotten arm would be E0004.

An ignored Result doesn’t go unnoticed

fs::write("/nonexistent-dir/x.txt", "x");
println!("fini");
warning: unused `Result` that must be used
 --> src/main.rs:3:5
  |
3 |     fs::write("/nonexistent-dir/x.txt", "x");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this `Result` may be an `Err` variant, which should be handled
  = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default

It’s only a warning, and the program prints fini (“done”) even though the write failed. But the failure was flagged at compile time: Result is marked #[must_use]. To ignore it on purpose, you write it out: let _ = fs::write(…);.

What the picture hides

  • unwrap everywhere is the unhandled exception. lire_port("80a").unwrap() compiles and stops with called Result::unwrap() on an Err value: ParseIntError { kind: InvalidDigit }, exit code 101. Invalid input is an expected error: it propagates. unwrap is for a bug, a broken invariant; that’s the topic of the next two issues.
  • ? also works on Option, but you don’t mix them. lignes.first()? in a function returning Result gives E0277 the ? operator can only be used on Results, not Options, and rustc suggests .ok_or(...)?: you give the absence a reason.
  • main -> Result prints the Debug form, not a polished message. For a command-line tool, you often end main with a match that prints the error with Display and picks the exit code.
  • Well-known libraries just write this code for you. thiserror generates the enum, Display and the Froms; anyhow is a Box<dyn Error> with context. The model stays the same: a return value, and doors.

Going further

Questions fréquentesFrequently asked questions

Que signifie « the `?` operator can only be used in a function that returns `Result` or `Option` » ?What does "the `?` operator can only be used in a function that returns `Result` or `Option`" mean?

Vous avez écrit ? dans une fonction qui renvoie (), le plus souvent main. Sur une erreur, ? doit renvoyer cette erreur à l'appelant, et () ne peut pas la contenir. rustc propose la correction : fn main() -> Result<(), Box<dyn std::error::Error>>, avec Ok(()) à la fin.You wrote ? in a function that returns (), most often main. On an error, ? must return that error to the caller, and () can't hold it. rustc suggests the fix: fn main() -> Result<(), Box<dyn std::error::Error>>, with Ok(()) at the end.

Que fait exactement l'opérateur ? en Rust ?What exactly does the ? operator do in Rust?

Sur Ok(v), il donne v et la fonction continue. Sur Err(e), il quitte la fonction tout de suite en renvoyant l'erreur, après l'avoir convertie avec From vers le type d'erreur de la fonction. C'est un return anticipé écrit à l'endroit exact où l'échec peut arriver.On Ok(v), it yields v and the function carries on. On Err(e), it leaves the function right away and returns the error, after converting it with From into the function's error type. It is an early return written at the exact spot where failure can happen.

Comment corriger « `?` couldn't convert the error to `ParseIntError` » ?How do I fix "`?` couldn't convert the error to `ParseIntError`"?

Deux erreurs différentes remontent par la même fonction, ici io::Error et ParseIntError, et la première ne se convertit pas dans la seconde. Soit on renvoie Box<dyn Error>, où toute erreur standard entre ; soit on définit un enum d'erreurs avec un impl From par source, pour que l'appelant puisse faire un match.Two different errors flow out of the same function, here io::Error and ParseIntError, and the first doesn't convert into the second. Either return Box<dyn Error>, which any standard error fits into, or define an error enum with one impl From per source, so the caller can match on it.

Quelle différence entre Result et une exception ?What is the difference between Result and an exception?

Une exception emprunte un canal invisible : rien dans la signature ne dit qu'une fonction peut lever, et elle saute par-dessus les appelants jusqu'à un try. Un Result est une valeur de retour : le type annonce l'échec possible, et chaque ? marque à l'écran l'endroit où l'erreur repart vers l'appelant.An exception travels an invisible channel: nothing in the signature says a function can throw, and it jumps over callers up to a try. A Result is a return value: the type announces possible failure, and each ? marks on screen the spot where the error heads back to the caller.

Pourquoi ne pas mettre unwrap partout ?Why not just use unwrap everywhere?

Parce que c'est réinventer l'exception non gérée. Sur « 80a », lire_port("80a").unwrap() s'arrête avec « called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit } », code de sortie 101. unwrap a sa place pour un bug, un invariant violé ; une entrée invalide est une erreur attendue, elle se propage.Because it reinvents the unhandled exception. On "80a", lire_port("80a").unwrap() stops with "called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }", exit code 101. unwrap belongs to bugs, broken invariants; invalid input is an expected error, and it propagates.

RustResultOpérateur ?E0277Gestion d'erreursModèle mental

← Tous les articlesAll articles