« borrow of moved value » (E0382) : le modèle mental du move en Rust "borrow of moved value" (E0382): the mental model of a Rust move

Pourquoi let b = a; rend a inutilisable en Rust. Le modèle en une image : une valeur, un propriétaire, et le move passe la clé. Animation, sorties réelles de rustc et mesures.Why let b = a; makes a unusable in Rust. The model in one picture: one value, one owner, and a move hands over the key. Animation, real rustc output and measurements.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
OwnershipOwnership
PubliéPublished

En bref. En Rust, let b = a; ne copie pas une String : il en transfère la propriété à b, et a devient inutilisable. Relire a déclenche l’erreur E0382 borrow of moved value, à la compilation, pour qu’aucun tampon n’ait jamais deux propriétaires.

Le modèle en une phrase

Une valeur, un propriétaire. Le move passe la clé : l’ancien propriétaire garde sa poche, mais elle est vide.

Une String est en deux morceaux : une fiche de 24 octets sur la pile (où est le texte, combien il en contient, combien de place est réservée) et le texte lui-même, sur le tas. Le move recopie la fiche, jamais le texte. Ce qui change, c’est qui a le droit de s’en servir.

In short. In Rust, let b = a; does not copy a String: it transfers ownership to b, and a becomes unusable. Reading a again triggers error E0382 borrow of moved value, at compile time, so that no buffer ever has two owners.

The model in one sentence

One value, one owner. A move hands over the key: the old owner keeps its pocket, but the pocket is empty.

A String comes in two pieces: a 24-byte record on the stack (where the text is, how much it holds, how much room is reserved) and the text itself, on the heap. A move copies the record, never the text. What changes is who is allowed to use it.

fn main() {
let a = String::from("Ada");
let b = a;
println!("{a}"); // E0382
}
Qui possède le tamponWho owns the bufferlet b = a : 24 octets copiés, pas le textelet b = a: 24 bytes copied, not the textPileStackTasHeapalen 3cap 3ptrdéplacé · rien à libérermoved · nothing to freeblen 3cap 3ptr24 octets copiés24 bytes copiedAdaAdamême tamponsame buffernouvelle allocationnew allocationvérifié avec rustc 1.100checked with rustc 1.100
  1. let a = String::from("Ada"); — Sur la pile, a tient trois mots : un pointeur, une longueur, une capacité (24 octets). Le texte lui-même vit sur le tas, dans un tampon dont a est l'unique propriétaire.On the stack, a holds three words: a pointer, a length, a capacity (24 bytes). The text itself lives on the heap, in a buffer that a solely owns.
  2. let b = a; — Le move copie les 24 octets de la pile dans b, et rien d'autre : le tampon ne bouge pas, b pointe sur le même. La clé change de main, et a devient une poche vide.The move copies the 24 stack bytes into b, and nothing else: the buffer doesn't move, b points at the same one. The key changes hands, and a becomes an empty pocket.
  3. println!("{a}"); — Relire a est refusé à la compilation : erreur E0382, borrow of moved value. Rien ne plante à l'exécution, le programme n'existe tout simplement pas.Reading a again is refused at compile time: error E0382, borrow of moved value. Nothing crashes at runtime, the program simply never exists.
  4. } — En fin de portée, seul b libère le tampon. a n'a plus rien à libérer : un seul drop, jamais deux. Le double free est impossible par construction.At end of scope, only b frees the buffer. a has nothing left to free: one drop, never two. Double free is impossible by construction.
Le move en Rust : let b = a copie 24 octets de pile, le tampon du tas ne bouge pas, a devient inutilisable, et un seul drop libère la mémoire.The move in Rust: let b = a copies 24 stack bytes, the heap buffer stays put, a becomes unusable, and a single drop frees the memory.

L’erreur, telle que rustc l’écrit

fn main() {
    let a = String::from("Ada");
    let b = a;
    println!("{a}");
}
error[E0382]: borrow of moved value: `a`
 --> src/main.rs:4:16
  |
2 |     let a = String::from("Ada");
  |         - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 |     let b = a;
  |             - value moved here
4 |     println!("{a}");
  |                ^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let b = a.clone();
  |              ++++++++

Le message raconte exactement le dessin : la ligne 2 crée le propriétaire, la ligne 3 passe la clé (value moved here), la ligne 4 essaie d’ouvrir une poche vide. La mention does not implement the Copy trait dit pourquoi : une String possède un tampon, elle ne se duplique pas en douce.

La preuve, mesurée

Le dessin affirme trois choses : la fiche fait 24 octets, le move ne déplace pas le tampon, le clone en crée un autre. Le programme suivant les vérifie (rustc 1.100, édition 2024) :

fn main() {
    let a = String::from("Ada");
    let p = a.as_ptr();
    println!("taille de String sur la pile : {} octets", std::mem::size_of::<String>());
    let b = a;
    println!("même tampon après le move : {}", std::ptr::eq(p, b.as_ptr()));
    let c = b.clone();
    println!("même tampon après clone : {}", std::ptr::eq(b.as_ptr(), c.as_ptr()));
}
taille de String sur la pile : 24 octets
même tampon après le move : true
même tampon après clone : false

Et le « un seul drop » se voit avec un type qui annonce sa propre libération :

struct Nom(&'static str);
impl Drop for Nom {
    fn drop(&mut self) { println!("drop({})", self.0); }
}

fn main() {
    let a = Nom("Ada");
    let b = a;                 // move : rien n'est affiché, rien n'est libéré
    println!("fin de main");
}                              // un seul drop, pour b
fin de main
drop(Ada)

Deux variables, une seule libération. C’est tout l’enjeu : sans le move, a et b libéreraient le même tampon, un double free.

Le même move, déguisé

let b = a; est la forme visible. Deux autres passent la clé sans le dire (sorties de rustc abrégées).

Passer une valeur à une fonction. Le paramètre s: String devient le propriétaire :

fn afficher(s: String) {
    println!("{s}");
}

fn main() {
    let nom = String::from("Ada");
    afficher(nom);
    afficher(nom);
}
error[E0382]: use of moved value: `nom`
 --> src/main.rs:8:14
  |
7 |     afficher(nom);
  |              --- value moved here
8 |     afficher(nom);
  |              ^^^ value used here after move
  |
note: consider changing this parameter type in function `afficher` to borrow instead if owning the value isn't necessary

La note est la bonne piste : fn afficher(s: &str) emprunte au lieu de prendre, et nom reste à main.

Déplacer dans une boucle. Le premier tour prend la clé, le second ne trouve plus rien :

fn main() {
    let nom = String::from("Ada");
    let mut v = Vec::new();
    for _ in 0..2 {
        v.push(nom);
    }
}
error[E0382]: use of moved value: `nom`
  |
4 |     for _ in 0..2 {
  |     ------------- inside of this loop
5 |         v.push(nom);
  |                ^^^ value moved here, in previous iteration of loop

Ce que l’image cache

  • Les types Copy ne bougent pas. i32, bool, char, f64 et les tuples de ces types se dupliquent bit à bit : let y = x; laisse x utilisable. Ils ne possèdent aucun tampon, donc rien à libérer deux fois.
  • « Le tampon ne bouge pas » ne veut pas dire « gratuit pour tout ». Le move copie toujours la partie sur la pile. Pour une String, 24 octets ; pour un tableau [u8; 4096] posé sur la pile, 4 096 octets. Le compilateur élimine souvent cette copie, mais le modèle reste « on recopie la fiche ».
  • La poche vide n’existe qu’à la compilation. À l’exécution, il n’y a ni drapeau ni vérification : le compilateur a déjà prouvé que personne ne relit a.
  • Cloner n’est pas une faute. C’est un choix explicite, avec un coût visible. Le plus souvent, la vraie réponse est d’emprunter (&a) : c’est le sujet du numéro 02, Borrowing.

Pour aller plus loin

The error, as rustc writes it

fn main() {
    let a = String::from("Ada");
    let b = a;
    println!("{a}");
}
error[E0382]: borrow of moved value: `a`
 --> src/main.rs:4:16
  |
2 |     let a = String::from("Ada");
  |         - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 |     let b = a;
  |             - value moved here
4 |     println!("{a}");
  |                ^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let b = a.clone();
  |              ++++++++

The message tells exactly the story of the drawing: line 2 creates the owner, line 3 hands over the key (value moved here), line 4 tries to open an empty pocket. The phrase does not implement the Copy trait says why: a String owns a buffer, it does not get duplicated behind your back.

The proof, measured

The drawing claims three things: the record is 24 bytes, a move leaves the buffer in place, a clone creates another one. This program checks them (rustc 1.100, edition 2024):

fn main() {
    let a = String::from("Ada");
    let p = a.as_ptr();
    println!("taille de String sur la pile : {} octets", std::mem::size_of::<String>());
    let b = a;
    println!("même tampon après le move : {}", std::ptr::eq(p, b.as_ptr()));
    let c = b.clone();
    println!("même tampon après clone : {}", std::ptr::eq(b.as_ptr(), c.as_ptr()));
}
taille de String sur la pile : 24 octets
même tampon après le move : true
même tampon après clone : false

(Size of String on the stack: 24 bytes. Same buffer after the move: true. Same buffer after clone: false.)

And “a single drop” shows up with a type that announces its own release:

struct Nom(&'static str);
impl Drop for Nom {
    fn drop(&mut self) { println!("drop({})", self.0); }
}

fn main() {
    let a = Nom("Ada");
    let b = a;                 // move: nothing printed, nothing freed
    println!("fin de main");
}                              // a single drop, for b
fin de main
drop(Ada)

Two variables, one release. That is the whole point: without the move, a and b would both free the same buffer, a double free.

The same move, in disguise

let b = a; is the visible form. Two others hand over the key without saying so (rustc output abridged).

Passing a value to a function. The parameter s: String becomes the owner:

fn afficher(s: String) {
    println!("{s}");
}

fn main() {
    let nom = String::from("Ada");
    afficher(nom);
    afficher(nom);
}
error[E0382]: use of moved value: `nom`
 --> src/main.rs:8:14
  |
7 |     afficher(nom);
  |              --- value moved here
8 |     afficher(nom);
  |              ^^^ value used here after move
  |
note: consider changing this parameter type in function `afficher` to borrow instead if owning the value isn't necessary

The note is the right lead: fn afficher(s: &str) borrows instead of taking, and nom stays with main.

Moving inside a loop. The first iteration takes the key, the second finds nothing:

fn main() {
    let nom = String::from("Ada");
    let mut v = Vec::new();
    for _ in 0..2 {
        v.push(nom);
    }
}
error[E0382]: use of moved value: `nom`
  |
4 |     for _ in 0..2 {
  |     ------------- inside of this loop
5 |         v.push(nom);
  |                ^^^ value moved here, in previous iteration of loop

What the picture hides

  • Copy types don’t move. i32, bool, char, f64 and tuples of them are duplicated bit by bit: let y = x; leaves x usable. They own no buffer, so there is nothing to free twice.
  • “The buffer doesn’t move” doesn’t mean “free for everything”. A move always copies the stack part. For a String, 24 bytes; for a [u8; 4096] array on the stack, 4,096 bytes. The compiler often elides that copy, but the model stays “copy the record”.
  • The empty pocket only exists at compile time. At runtime there is no flag and no check: the compiler has already proven that nobody reads a again.
  • Cloning is not a mistake. It is an explicit choice, with a visible cost. Most of the time the real answer is to borrow (&a): that is the topic of issue 02, Borrowing.

Going further

Questions fréquentesFrequently asked questions

Que signifie l'erreur E0382 « borrow of moved value » en Rust ?What does Rust error E0382 "borrow of moved value" mean?

Le code relit une variable après lui avoir retiré sa valeur. Un move (affectation, appel de fonction, tour de boucle) a transféré la propriété ailleurs ; l'ancienne variable est vide et Rust refuse de la lire, à la compilation.The code reads a variable after its value was taken away. A move (assignment, function call, loop iteration) transferred ownership elsewhere; the old variable is empty and Rust refuses to read it, at compile time.

Un move copie-t-il les données en Rust ?Does a move copy the data in Rust?

Il copie seulement la partie posée sur la pile : 24 octets pour une String (pointeur, longueur, capacité). Le tampon sur le tas ne bouge pas : après let b = a, b pointe exactement sur la même adresse que a.It only copies the part on the stack: 24 bytes for a String (pointer, length, capacity). The heap buffer does not move: after let b = a, b points at exactly the same address as a did.

Comment corriger E0382 ?How do I fix E0382?

Trois options, de la moins chère à la plus chère : ne plus utiliser l'ancienne variable, emprunter avec &a au lieu de déplacer, ou cloner avec a.clone() si deux propriétaires indépendants sont vraiment nécessaires (au prix d'une allocation).Three options, from cheapest to most expensive: stop using the old variable, borrow with &a instead of moving, or clone with a.clone() if two independent owners are really needed (at the cost of an allocation).

Pourquoi un i32 n'est-il pas déplacé comme une String ?Why isn't an i32 moved like a String?

Parce que i32 implémente le trait Copy : il ne possède aucune ressource à libérer, donc le dupliquer bit à bit est sûr et gratuit. Un type qui possède un tampon, comme String ou Vec, ne peut pas être Copy.Because i32 implements the Copy trait: it owns no resource to free, so duplicating it bit by bit is safe and free. A type that owns a buffer, like String or Vec, cannot be Copy.

Pourquoi Rust interdit-il d'utiliser une variable déplacée ?Why does Rust forbid using a moved variable?

Pour qu'un tampon n'ait jamais deux propriétaires. Sinon les deux le libéreraient en fin de portée : un double free. En rendant l'ancienne variable inutilisable, Rust garantit un seul drop par tampon, sans ramasse-miettes.So that a buffer never has two owners. Otherwise both would free it at end of scope: a double free. By making the old variable unusable, Rust guarantees one drop per buffer, without a garbage collector.

RustOwnershipMoveE0382Modèle mental

← Tous les articlesAll articles