« borrowed for 'static » : pourquoi 'static ne répare pas une erreur de lifetime en Rust "borrowed for 'static": why 'static doesn't fix a lifetime error in Rust

Une struct qui emprunte une variable locale : E0106, puis E0515 avec 'a, puis E0597 avec 'static. Trois erreurs, une seule cause, la possession. Animation de la spirale, sorties réelles de rustc, et ce que veut vraiment dire T: 'static.A struct borrowing a local variable: E0106, then E0515 with 'a, then E0597 with 'static. Three errors, one cause: ownership. Animation of the spiral, real rustc output, and what T: 'static really means.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
LifetimesLifetimes
PubliéPublished

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

'static ne 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

'static makes 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 }
}
Qui possède la donnéeWho owns the dataune référence vers une localea reference to a localPileStackTasHeapmainc.nom&strchargefin : saisie libéréeend: saisie freedsaisieStringprod'staticjusqu'à la fin du programmeuntil the end of the programsaisiefin de chargeend of chargeE0106 · missing lifetime specifiervérifié avec rustc 1.100checked with rustc 1.100
  1. Config emprunte : son champ nom pointe vers saisie, une variable locale de charge. Rust demande d'où vient l'emprunt : E0106.Config borrows: its nom field points to saisie, a local variable of charge. Rust asks where the borrow comes from: E0106.
  2. On ajoute 'a. L'erreur change : à la fin de charge, saisie est libérée et nom pointerait dans le vide. E0515.Add 'a. The error changes: at the end of charge, saisie is freed and nom would point into nothing. E0515.
  3. On écrit &'static str. L'erreur change encore : 'static veut dire « jusqu'à la fin du programme », et saisie meurt avec charge. E0597.Write &'static str. The error changes again: 'static means "until the end of the program", and saisie dies with charge. E0597.
  4. Trois erreurs, une seule cause : Config emprunte une donnée qui meurt avant elle. Aucune annotation ne la fera vivre plus longtemps.Three errors, one cause: Config borrows data that dies before it does. No annotation will make it live longer.
'static en Rust : une struct qui emprunte une variable locale ne peut pas sortir de la fonction. Ajouter 'a puis 'static change l'erreur (E0106, E0515, E0597) sans changer la cause.'static in Rust: a struct borrowing a local variable cannot leave the function. Adding 'a then 'static changes the error (E0106, E0515, E0597) without changing the cause.

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 function

L’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 borrowed

Troisiè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 suggestion struct 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 str est honnête pour ce qui vit vraiment toujours. Config { nom: "prod" } compile : un littéral est inscrit dans le binaire.
  • Box::leak fabrique 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

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 function

The 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 borrowed

Third 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 suggestion struct 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 str is honest for what truly lives forever. Config { nom: "prod" } compiles: a literal is baked into the binary.
  • Box::leak manufactures 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

Questions fréquentesFrequently asked questions

Que signifie « argument requires that `x` is borrowed for `'static` » ?What does "argument requires that `x` is borrowed for `'static`" mean?

Une contrainte 'static exige que l'emprunt reste valide jusqu'à la fin du programme. Une variable locale meurt à la fin de sa portée, donc un emprunt vers elle ne peut jamais satisfaire 'static, même si elle vit jusqu'à la fin de main. Rust répond E0597.A 'static constraint requires the borrow to stay valid until the end of the program. A local variable dies at the end of its scope, so a borrow of it can never satisfy 'static, even if it lives until the end of main. Rust answers E0597.

Faut-il mettre 'static pour corriger une erreur de lifetime ?Should I add 'static to fix a lifetime error?

Presque jamais. 'static ne fait vivre aucune donnée plus longtemps ; il exige qu'elle vive déjà jusqu'à la fin du programme. Sur une variable locale, il transforme E0515 en E0597. La correction habituelle est de posséder la donnée (String au lieu de &str).Almost never. 'static makes no data live longer; it requires that the data already lives until the end of the program. On a local variable, it turns E0515 into E0597. The usual fix is to own the data (String instead of &str).

Quelle différence entre &'static str et T: 'static ?What is the difference between &'static str and T: 'static?

&'static str est une référence valide jusqu'à la fin du programme, comme un littéral. T: 'static est une borne sur un type : il ne contient aucun emprunt à durée courte. Une String satisfait T: 'static même si elle est créée à l'exécution ; &s vers une variable locale ne la satisfait pas.&'static str is a reference valid until the end of the program, like a literal. T: 'static is a bound on a type: it holds no short-lived borrow. A String satisfies T: 'static even when created at runtime; &s to a local variable does not.

Pourquoi une struct avec un champ &str pose-t-elle autant de problèmes ?Why does a struct with a &str field cause so many problems?

Dès qu'un champ est emprunté, la struct porte une durée, et cette durée se propage à tout ce qui la contient : une struct App qui contient Config doit à son tour écrire App<'a> (sinon E0106). Si la struct doit être stockée ou renvoyée, possédez le champ.As soon as a field is borrowed, the struct carries a lifetime, and that lifetime spreads to everything containing it: a struct App holding Config must in turn write App<'a> (otherwise E0106). If the struct must be stored or returned, own the field.

Box::leak est-il une bonne façon d'obtenir un &'static str ?Is Box::leak a good way to get a &'static str?

Il compile : Box::leak(s.into_boxed_str()) renvoie un &'static str. Mais la mémoire n'est jamais libérée. C'est acceptable pour une configuration lue une fois au démarrage, pas dans une fonction appelée en boucle.It compiles: Box::leak(s.into_boxed_str()) returns a &'static str. But the memory is never freed. That is acceptable for configuration read once at startup, not in a function called in a loop.

RustLifetimes'staticE0597E0515Modèle mental

← Tous les articlesAll articles