En bref. En Rust, une fonction qui reçoit deux références et en renvoie une doit dire d’où vient le résultat : sinon, erreur E0106 missing lifetime specifier. L’annotation 'a ne rallonge aucune vie. Elle relie des durées : « le résultat ne vit pas plus longtemps que le plus court des emprunts ». Utiliser le résultat au-delà déclenche E0597.
Le modèle en une phrase
Une lifetime ne fait vivre personne plus longtemps. C’est une étiquette qui relie la durée du résultat à celle des entrées, pour que le compilateur puisse vérifier chaque appel.
Les trois premiers articles de la série ont posé le propriétaire, la règle des lecteurs et la fenêtre. Il reste une question : une fenêtre renvoyée par une fonction, sur quoi s’ouvre-t-elle, et jusqu’à quand ? Le compilateur ne lit pas le corps de la fonction pour le deviner. Il lit la signature.
In short. In Rust, a function that receives two references and returns one must say where the result comes from: otherwise, error E0106 missing lifetime specifier. The 'a annotation lengthens no life. It links durations: “the result lives no longer than the shorter of the borrows”. Using the result beyond that triggers E0597.
The model in one sentence
A lifetime makes nothing live longer. It is a label that links the result’s duration to the inputs’, so the compiler can check every call.
The first three articles in the series set up the owner, the readers’ rule and the window. One question remains: a window returned by a function, what does it open onto, and until when? The compiler does not read the function body to guess. It reads the signature.
fn plus_long<'a>(x: &'a str, y: &'a str) -> &'a str { … }fn main() {1 let prenom = String::from("Ada");2 let resultat;3 {4 let nom = String::from("Lovelace");5 resultat = plus_long(&prenom, &nom);6 }7 println!("{resultat}");}
prenomvit jusqu'à la fin demain.prenomlives until the end ofmain.nomnaît dans le bloc et meurt à son accolade fermante.nomis born inside the block and dies at its closing brace.- La signature dit : le résultat vient de
xou dey, durée'apour les deux.'ane peut donc pas dépasser le plus court des deux emprunts : celui denom.The signature says: the result comes fromxory, lifetime'afor both. So'acannot extend past the shorter of the two borrows:nom's. resultatest utilisé hors de'a, après la mort denom: il pourrait pointer dans de la mémoire libérée. Rust refuse : E0597.resultatis used outside'a, afternomdied: it might point into freed memory. Rust refuses: E0597.
L’erreur, telle que rustc l’écrit
fn plus_long(x: &str, y: &str) -> &str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
println!("{}", plus_long("Ada", "Lovelace"));
}error[E0106]: missing lifetime specifier
--> src/main.rs:1:35
|
1 | fn plus_long(x: &str, y: &str) -> &str {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
|
1 | fn plus_long<'a>(x: &'a str, y: &'a str) -> &'a str {
| ++++ ++ ++ ++Le help est le modèle mot pour mot : la signature ne dit pas si le résultat est emprunté à x ou à y. Les deux traits sous &str montrent les candidats. La correction proposée met la même étiquette 'a partout : « le résultat vit au plus aussi longtemps que x et que y ».
Ce que 'a promet, et ce qu’il vérifie
L’annotation ajoutée, le code compile. Mais la contrainte voyage jusqu’à l’appel :
fn plus_long<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let prenom = String::from("Ada");
let resultat;
{
let nom = String::from("Lovelace");
resultat = plus_long(&prenom, &nom);
}
println!("{resultat}");
}error[E0597]: `nom` does not live long enough
--> src/main.rs:10:39
|
9 | let nom = String::from("Lovelace");
| --- binding `nom` declared here
10 | resultat = plus_long(&prenom, &nom);
| ^^^^ borrowed value does not live long enough
11 | }
| - `nom` dropped here while still borrowed
12 | println!("{resultat}");
| -------- borrow later used hereC’est l’animation : 'a s’arrête avec nom (ligne 11), resultat sert ligne 12. Ici, le danger est réel : « Lovelace » est la plus longue, resultat pointerait dans nom, libéré.
La preuve que le compilateur ne regarde pas les valeurs : avec prenom = "Ada Lovelace" et nom = "Byron", le résultat serait prenom, toujours vivant. Le code est quand même refusé, avec la même E0597 (vérifié, rustc 1.100). La signature dit « peut venir de y », donc l’appel doit être sûr dans les deux cas.
Deux corrections, selon ce qui est vrai :
- Utiliser le résultat tant que
nomvit : mettre leprintln!dans le bloc. Le programme afficheLovelace. - Dire la vérité dans la signature si le résultat ne vient que de
x:
fn premier<'a>(x: &'a str, _y: &str) -> &'a str {
x
}Avec cette signature, le même main (bloc, println! après) compile et affiche Ada : 'a ne relie plus le résultat à nom. L’annotation ne change rien à l’exécution ; elle change ce que le compilateur sait.
La référence qui pend
Sans paramètre, il n’y a rien à quoi rattacher le résultat :
fn pendante() -> &String {
let s = String::from("Ada");
&s
}error[E0106]: missing lifetime specifier
--> src/main.rs:1:18
|
1 | fn pendante() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
1 | fn pendante() -> &'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
1 - fn pendante() -> &String {
1 + fn pendante() -> String {
|Le compilateur propose 'static du bout des lèvres, puis la vraie réponse : rendre la String elle-même. s meurt à la fin de la fonction ; aucune annotation ne peut la faire survivre, c’est tout le sens du modèle.
Ce que l’image cache
- La plupart des signatures n’ont pas besoin de
'a. Avec un seul paramètre référence, ou&self, le compilateur applique des règles d’élision et écrit l’annotation pour vous.fn premier_mot(s: &str) -> &strde l’article sur les slices en est un exemple. C’est le sujet du volume 2, numéro 02. 'aest choisi par l’appelant, pas par la fonction. À chaque appel, le compilateur cherche la région la plus longue compatible avec les deux arguments, puis vérifie les usages du résultat.'staticn’est pas « pour toujours » au sens d’une fuite. C’est « valable jusqu’à la fin du programme », comme les littéraux. Le mettre pour faire taire E0106 déplace l’erreur : surpendante, on obtient E0515 cannot return reference to local variables.- Zéro coût à l’exécution. Les lifetimes disparaissent à la compilation : aucun compteur, aucune vérification dans le binaire.
Pour aller plus loin
- Le volume 2, numéro 01 de The Rust Loop, Lifetimes, part du use-after-free que Rust refuse et construit l’annotation à partir de là (lien en bas de page).
- Articles précédents : le move (E0382), l’emprunt (E0502), les slices.
- The Rust Programming Language, chapitre 10.3 : Validating References with Lifetimes
- Index des erreurs : E0106 et E0597
The error, as rustc writes it
fn plus_long(x: &str, y: &str) -> &str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
println!("{}", plus_long("Ada", "Lovelace"));
}error[E0106]: missing lifetime specifier
--> src/main.rs:1:35
|
1 | fn plus_long(x: &str, y: &str) -> &str {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
|
1 | fn plus_long<'a>(x: &'a str, y: &'a str) -> &'a str {
| ++++ ++ ++ ++(plus_long means “longest”.) The help is the model word for word: the signature doesn’t say whether the result is borrowed from x or y. The two underlines below &str show the candidates. The suggested fix puts the same 'a label everywhere: “the result lives at most as long as x and y”.
What 'a promises, and what it checks
With the annotation added, the code compiles. But the constraint travels to the call site:
fn plus_long<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let prenom = String::from("Ada");
let resultat;
{
let nom = String::from("Lovelace");
resultat = plus_long(&prenom, &nom);
}
println!("{resultat}");
}error[E0597]: `nom` does not live long enough
--> src/main.rs:10:39
|
9 | let nom = String::from("Lovelace");
| --- binding `nom` declared here
10 | resultat = plus_long(&prenom, &nom);
| ^^^^ borrowed value does not live long enough
11 | }
| - `nom` dropped here while still borrowed
12 | println!("{resultat}");
| -------- borrow later used hereThat is the animation: 'a stops with nom (line 11), resultat is used on line 12. Here the danger is real: “Lovelace” is the longer one, resultat would point into nom, freed.
Proof that the compiler does not look at values: with prenom = "Ada Lovelace" and nom = "Byron", the result would be prenom, still alive. The code is refused anyway, with the same E0597 (checked, rustc 1.100). The signature says “may come from y”, so the call must be safe in both cases.
Two fixes, depending on what is true:
- Use the result while
nomis alive: put theprintln!inside the block. The program printsLovelace. - Tell the truth in the signature if the result only ever comes from
x:
fn premier<'a>(x: &'a str, _y: &str) -> &'a str {
x
}With this signature, the same main (block, println! after it) compiles and prints Ada: 'a no longer ties the result to nom. The annotation changes nothing at runtime; it changes what the compiler knows.
The dangling reference
With no parameter, there is nothing to tie the result to:
fn pendante() -> &String {
let s = String::from("Ada");
&s
}error[E0106]: missing lifetime specifier
--> src/main.rs:1:18
|
1 | fn pendante() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
1 | fn pendante() -> &'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
1 - fn pendante() -> &String {
1 + fn pendante() -> String {
|The compiler half-heartedly offers 'static, then the real answer: return the String itself. s dies at the end of the function; no annotation can make it survive, which is the whole point of the model.
What the picture hides
- Most signatures don’t need
'a. With a single reference parameter, or&self, the compiler applies elision rules and writes the annotation for you.fn premier_mot(s: &str) -> &strfrom the slices article is one example. That is the topic of volume 2, issue 02. 'ais chosen by the caller, not the function. At each call, the compiler looks for the longest region compatible with both arguments, then checks the uses of the result.'staticis not “forever” in the sense of a leak. It means “valid until the end of the program”, like literals. Adding it to silence E0106 moves the error: onpendante, you get E0515 cannot return reference to local variables.- Zero runtime cost. Lifetimes vanish at compile time: no counter, no check in the binary.
Going further
- Volume 2, issue 01 of The Rust Loop, Lifetimes, starts from the use-after-free that Rust refuses and builds the annotation from there (link at the bottom of the page).
- Previous articles: the move (E0382), borrowing (E0502), slices.
- The Rust Programming Language, chapter 10.3: Validating References with Lifetimes
- Error index: E0106 and E0597