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}
let a = String::from("Ada");— Sur la pile,atient trois mots : un pointeur, une longueur, une capacité (24 octets). Le texte lui-même vit sur le tas, dans un tampon dontaest l'unique propriétaire.On the stack,aholds three words: a pointer, a length, a capacity (24 bytes). The text itself lives on the heap, in a buffer thatasolely owns.let b = a;— Le move copie les 24 octets de la pile dansb, et rien d'autre : le tampon ne bouge pas,bpointe sur le même. La clé change de main, etadevient une poche vide.The move copies the 24 stack bytes intob, and nothing else: the buffer doesn't move,bpoints at the same one. The key changes hands, andabecomes an empty pocket.println!("{a}");— Relireaest refusé à la compilation : erreur E0382, borrow of moved value. Rien ne plante à l'exécution, le programme n'existe tout simplement pas.Readingaagain is refused at compile time: error E0382, borrow of moved value. Nothing crashes at runtime, the program simply never exists.}— En fin de portée, seulblibère le tampon.an'a plus rien à libérer : un seuldrop, jamais deux. Le double free est impossible par construction.At end of scope, onlybfrees the buffer.ahas nothing left to free: onedrop, never two. Double free is impossible by construction.
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 : falseEt 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 bfin 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 necessaryLa 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 loopCe que l’image cache
- Les types
Copyne bougent pas.i32,bool,char,f64et les tuples de ces types se dupliquent bit à bit :let y = x;laissexutilisable. 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
- Le numéro 01 de The Rust Loop, Move semantics, déroule la mémoire pas à pas et trouve les moves cachés dans du code réel (lien en bas de page).
- The Rust Programming Language, chapitre 4.1 : What Is Ownership?
- Index des erreurs du compilateur : E0382
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 bfin 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 necessaryThe 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 loopWhat the picture hides
Copytypes don’t move.i32,bool,char,f64and tuples of them are duplicated bit by bit:let y = x;leavesxusable. 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
aagain. - 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
- Issue 01 of The Rust Loop, Move semantics, walks through memory step by step and finds the hidden moves in real code (link at the bottom of the page).
- The Rust Programming Language, chapter 4.1: What Is Ownership?
- Compiler error index: E0382