En bref. Une struct qui emprunte une variable locale ne peut pas sortir de la fonction qui l’a créée. Annoter ne change rien : sans durée, E0106 ; avec 'a, E0515 ; avec 'static, E0597 borrowed for 'static. L’erreur change de nom, pas de cause. La correction est de posséder la donnée : String au lieu de &str.
Le modèle en une phrase
'staticne fait vivre personne plus longtemps. Quand chaque annotation déplace l’erreur, ce n’est plus un problème de durées, c’est un problème de possession.
Les deux articles précédents ont montré ce que relie 'a et quand le compilateur l’écrit seul. Celui-ci traite le moment où annoter ne sert plus à rien.
In short. A struct borrowing a local variable cannot leave the function that created it. Annotating changes nothing: with no lifetime, E0106; with 'a, E0515; with 'static, E0597 borrowed for 'static. The error changes name, not cause. The fix is to own the data: String instead of &str.
The model in one sentence
'staticmakes nothing live longer. When each annotation moves the error, it is no longer a lifetime problem, it is an ownership problem.
The two previous articles showed what 'a links and when the compiler writes it for you. This one is about the moment when annotating stops helping.
struct Config<'a> { nom: &'a str }fn charge() -> Config {let saisie = String::from("prod");Config { nom: &saisie }}
Configemprunte : son champnompointe verssaisie, une variable locale decharge. Rust demande d'où vient l'emprunt : E0106.Configborrows: itsnomfield points tosaisie, a local variable ofcharge. Rust asks where the borrow comes from: E0106.- On ajoute
'a. L'erreur change : à la fin decharge,saisieest libérée etnompointerait dans le vide. E0515.Add'a. The error changes: at the end ofcharge,saisieis freed andnomwould point into nothing. E0515. - On écrit
&'static str. L'erreur change encore :'staticveut dire « jusqu'à la fin du programme », etsaisiemeurt aveccharge. E0597.Write&'static str. The error changes again:'staticmeans "until the end of the program", andsaisiedies withcharge. E0597. - Trois erreurs, une seule cause :
Configemprunte une donnée qui meurt avant elle. Aucune annotation ne la fera vivre plus longtemps.Three errors, one cause:Configborrows data that dies before it does. No annotation will make it live longer.
La spirale, erreur par erreur
Une configuration lue à l’exécution, rangée dans une struct qui emprunte :
struct Config<'a> {
nom: &'a str,
}
fn charge() -> Config {
let saisie = String::from("prod");
Config { nom: &saisie }
}error[E0106]: missing lifetime specifier
--> src/main.rs:5:16
|
5 | fn charge() -> Config {
| ^^^^^^ 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`, or if you will only have owned values
|
5 | fn charge() -> Config<'static> {
| +++++++++Le help est déjà le diagnostic : there is no value for it to be borrowed from. charge n’a aucun paramètre ; ce qu’elle renvoie ne peut emprunter qu’à elle-même. Mais on lit la suggestion, on ajoute une durée :
fn charge<'a>() -> Config<'a> {
let saisie = String::from("prod");
Config { nom: &saisie }
}error[E0515]: cannot return value referencing local variable `saisie`
--> src/main.rs:7:5
|
7 | Config { nom: &saisie }
| ^^^^^^^^^^^^^^-------^^
| | |
| | `saisie` is borrowed here
| returns a value referencing data owned by the current functionL’erreur a changé, la cause non : saisie meurt à la fin de charge. Dernier recours du débutant, 'static dans la struct :
struct Config {
nom: &'static str,
}
fn charge() -> Config {
let saisie = String::from("prod");
Config { nom: &saisie }
}error[E0597]: `saisie` does not live long enough
--> src/main.rs:7:19
|
6 | let saisie = String::from("prod");
| ------ binding `saisie` declared here
7 | Config { nom: &saisie }
| ^^^^^^^
| |
| borrowed value does not live long enough
| this usage requires that `saisie` is borrowed for `'static`
8 | }
| - `saisie` dropped here while still borrowedTroisième erreur, même cause. 'static est une exigence, pas une permission : « cet emprunt doit rester valide jusqu’à la fin du programme ». Une variable locale ne peut pas la satisfaire. C’est l’animation, premier mode.
La sortie : posséder
struct Config {
nom: String,
}
fn charge() -> Config {
let saisie = String::from("prod");
Config { nom: saisie }
}
fn main() {
println!("{}", charge().nom);
}Ça compile et affiche prod, sans une seule lifetime écrite. Config { nom: saisie } déplace la String : les trois mots (pointeur, longueur, capacité) passent dans Config, le tampon sur le tas ne bouge pas. À la fin de charge, saisie a été déplacée, il n’y a rien à libérer. C’est le move du premier article, employé à dessein.
Le coût : String occupe 24 octets contre 16 pour &str (mesuré avec size_of, cible 64 bits), plus l’allocation qui existait déjà. En échange, Config se stocke, se renvoie et se déplace sans contrainte.
T: 'static ne veut pas dire la même chose
'static a un second sens, sur un type générique : « ce type ne contient aucun emprunt à durée courte ».
fn garde<T: 'static>(t: T) -> T {
t
}
fn main() {
let s = String::from("prod");
let r = garde(&s);
println!("{r}");
}error[E0597]: `s` does not live long enough
--> src/main.rs:7:19
|
6 | let s = String::from("prod");
| - binding `s` declared here
7 | let r = garde(&s);
| ------^^-
| | |
| | borrowed value does not live long enough
| argument requires that `s` is borrowed for `'static`
8 | println!("{r}");
9 | }
| - `s` dropped here while still borrowed
|
note: requirement that the value outlives `'static` introduced here
--> src/main.rs:1:13
|
1 | fn garde<T: 'static>(t: T) -> T {
| ^^^^^^^Refusé, alors que s vit jusqu’à la fin de main : « la fin de main » n’est pas « la fin du programme ». En revanche, garde(s) (la String elle-même) et garde("littéral") compilent tous les deux : une valeur possédée ne contient aucun emprunt, elle satisfait T: 'static même créée à l’exécution. C’est la borne qu’impose std::thread::spawn, que la série retrouvera au volume 7.
Ce que l’image cache
- La contagion. Une struct qui emprunte transmet sa durée :
struct App { config: Config }donne E0106 et la suggestionstruct App<'a>. Chaque niveau ajoute un'a. C’est le signal qu’il faut posséder plus bas. - Emprunter reste légitime pour une vue éphémère. Un parseur ou un itérateur qui lit une chaîne et meurt dans la même portée doit emprunter : il n’est jamais stocké ni renvoyé.
&'static strest honnête pour ce qui vit vraiment toujours.Config { nom: "prod" }compile : un littéral est inscrit dans le binaire.Box::leakfabrique un&'static.Box::leak(saisie.into_boxed_str())compile, mais la mémoire n’est jamais rendue. Acceptable une fois au démarrage, pas dans une boucle.- Les structures à références croisées (arbres avec parent, graphes) ne se règlent avec aucune annotation. Le volume 2, numéro 03 montre l’arène : posséder à plat, lier par indices.
Pour aller plus loin
- Le volume 2, numéro 03 de The Rust Loop, ‘static & le combat contre le borrow checker, déroule la spirale, la contagion et l’arène (lien en bas de page).
- Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision.
- Rust by Example : Static
- Index des erreurs : E0515 et E0597
The spiral, error by error
Configuration read at runtime, stored in a struct that borrows:
struct Config<'a> {
nom: &'a str,
}
fn charge() -> Config {
let saisie = String::from("prod");
Config { nom: &saisie }
}error[E0106]: missing lifetime specifier
--> src/main.rs:5:16
|
5 | fn charge() -> Config {
| ^^^^^^ 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`, or if you will only have owned values
|
5 | fn charge() -> Config<'static> {
| +++++++++(charge means “load”, saisie means “input”, nom means “name”.) The help is already the diagnosis: there is no value for it to be borrowed from. charge has no parameters; whatever it returns can only borrow from itself. But you read the suggestion and add a lifetime:
fn charge<'a>() -> Config<'a> {
let saisie = String::from("prod");
Config { nom: &saisie }
}error[E0515]: cannot return value referencing local variable `saisie`
--> src/main.rs:7:5
|
7 | Config { nom: &saisie }
| ^^^^^^^^^^^^^^-------^^
| | |
| | `saisie` is borrowed here
| returns a value referencing data owned by the current functionThe error changed, the cause didn’t: saisie dies at the end of charge. The beginner’s last resort, 'static in the struct:
struct Config {
nom: &'static str,
}
fn charge() -> Config {
let saisie = String::from("prod");
Config { nom: &saisie }
}error[E0597]: `saisie` does not live long enough
--> src/main.rs:7:19
|
6 | let saisie = String::from("prod");
| ------ binding `saisie` declared here
7 | Config { nom: &saisie }
| ^^^^^^^
| |
| borrowed value does not live long enough
| this usage requires that `saisie` is borrowed for `'static`
8 | }
| - `saisie` dropped here while still borrowedThird error, same cause. 'static is a requirement, not a permission: “this borrow must stay valid until the end of the program”. A local variable cannot satisfy it. That is the animation’s first mode.
The way out: own it
struct Config {
nom: String,
}
fn charge() -> Config {
let saisie = String::from("prod");
Config { nom: saisie }
}
fn main() {
println!("{}", charge().nom);
}It compiles and prints prod, without a single lifetime written. Config { nom: saisie } moves the String: its three words (pointer, length, capacity) go into Config, the heap buffer stays put. At the end of charge, saisie has been moved, so there is nothing to free. That is the move from the first article, used on purpose.
The cost: String takes 24 bytes versus 16 for &str (measured with size_of, 64-bit target), plus the allocation that already existed. In exchange, Config can be stored, returned and moved freely.
T: 'static does not mean the same thing
'static has a second meaning, on a generic type: “this type holds no short-lived borrow”.
fn garde<T: 'static>(t: T) -> T {
t
}
fn main() {
let s = String::from("prod");
let r = garde(&s);
println!("{r}");
}error[E0597]: `s` does not live long enough
--> src/main.rs:7:19
|
6 | let s = String::from("prod");
| - binding `s` declared here
7 | let r = garde(&s);
| ------^^-
| | |
| | borrowed value does not live long enough
| argument requires that `s` is borrowed for `'static`
8 | println!("{r}");
9 | }
| - `s` dropped here while still borrowed
|
note: requirement that the value outlives `'static` introduced here
--> src/main.rs:1:13
|
1 | fn garde<T: 'static>(t: T) -> T {
| ^^^^^^^(garde means “keep”.) Refused, even though s lives until the end of main: “the end of main” is not “the end of the program”. On the other hand, garde(s) (the String itself) and garde("littéral") both compile: an owned value holds no borrow, so it satisfies T: 'static even when created at runtime. That is the bound std::thread::spawn imposes, which the series will meet again in volume 7.
What the picture hides
- Contagion. A borrowing struct passes its lifetime on:
struct App { config: Config }gives E0106 and the suggestionstruct App<'a>. Each level adds an'a. That is the signal to own further down. - Borrowing is still right for an ephemeral view. A parser or iterator that reads a string and dies in the same scope should borrow: it is never stored or returned.
&'static stris honest for what truly lives forever.Config { nom: "prod" }compiles: a literal is baked into the binary.Box::leakmanufactures a&'static.Box::leak(saisie.into_boxed_str())compiles, but the memory is never given back. Fine once at startup, not in a loop.- Cross-referencing structures (trees with parent links, graphs) are not solved by any annotation. Volume 2, issue 03 shows the arena: own flat, link by indices.
Going further
- Volume 2, issue 03 of The Rust Loop, ‘static & the fight against the borrow checker, walks through the spiral, the contagion and the arena (link at the bottom of the page).
- Previous articles: the move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision.
- Rust by Example: Static
- Error index: E0515 and E0597