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
Resultle 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
Resultcrosses 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)}
- Avec
"8080",parserenvoieOk. Le?déballe la valeur, la fonction descend jusqu'àOk(port).With"8080",parsereturnsOk. The?unwraps the value, the function runs down toOk(port). - Avec
"80a",parserenvoieErr. Le?sort de la fonction sur-le-champ :Ok(port)ne s'exécute jamais, l'erreur arrive chez l'appelant.With"80a",parsereturnsErr. The?leaves the function on the spot:Ok(port)never runs, the error reaches the caller. - 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 ismain, which returns(). It has no door for an error: E0277, the `?` operator can only be used in a function that returns `Result` or `Option`. - Le correctif que propose rustc :
mainrenvoieResult<(), Box<dyn Error>>. L'erreur remonte, Rust l'affiche, Error: ParseIntError { kind: InvalidDigit }, code de sortie 1.The fix rustc suggests:mainreturnsResult<(), Box<dyn Error>>. The error goes up, Rust prints it, Error: ParseIntError { kind: InvalidDigit }, exit code 1.
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 ────▶ appelantAvec 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` traitLa 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 defaultCe 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
unwrappartout, c’est l’exception non gérée.lire_port("80a").unwrap()compile et s’arrête avec calledResult::unwrap()on anErrvalue: ParseIntError { kind: InvalidDigit }, code 101. Une entrée invalide est une erreur attendue : elle se propage.unwrapest pour un bug, un invariant violé ; c’est le sujet des deux prochains numéros.?marche aussi surOption, mais on ne mélange pas.lignes.first()?dans une fonction qui renvoieResultdonne E0277 the?operator can only be used onResults, notOptions, et rustc propose.ok_or(...)?: on donne une raison à l’absence.main -> Resultaffiche leDebug, pas un message soigné. Pour un outil en ligne de commande, on fait souvent unmatchfinal dansmainpour imprimer l’erreur avecDisplayet choisir le code de sortie.- Les bibliothèques connues ne font qu’écrire ce code pour vous.
thiserrorgénère l’enum,Displayet lesFrom;anyhowest unBox<dyn Error>avec du contexte. Le modèle reste le même : une valeur de retour, et des portes.
Pour aller plus loin
- Volume 4, numéro 01 de The Rust Loop, Result & l’opérateur ?, oppose l’exception au
Resultet pose la distinction entre erreur attendue et bug (lien en bas de page). - Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599). - The Rust Book, 9.2 : erreurs récupérables avec Result
- Référence : l’opérateur
? - Index des erreurs : E0277
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 ────▶ callerWith 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` traitThe 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 defaultIt’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
unwrapeverywhere is the unhandled exception.lire_port("80a").unwrap()compiles and stops with calledResult::unwrap()on anErrvalue: ParseIntError { kind: InvalidDigit }, exit code 101. Invalid input is an expected error: it propagates.unwrapis for a bug, a broken invariant; that’s the topic of the next two issues.?also works onOption, but you don’t mix them.lignes.first()?in a function returningResultgives E0277 the?operator can only be used onResults, notOptions, and rustc suggests.ok_or(...)?: you give the absence a reason.main -> Resultprints theDebugform, not a polished message. For a command-line tool, you often endmainwith amatchthat prints the error withDisplayand picks the exit code.- Well-known libraries just write this code for you.
thiserrorgenerates theenum,Displayand theFroms;anyhowis aBox<dyn Error>with context. The model stays the same: a return value, and doors.
Going further
- Volume 4, issue 01 of The Rust Loop, Result & the ? operator, contrasts the exception with
Resultand sets out the line between expected error and bug (link at the bottom of the page). - Previous articles: the move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599). - The Rust Book, 9.2: recoverable errors with Result
- Reference: the
?operator - Error index: E0277