Ownership et emprunt
Rust Ownership and Moves
The rule behind Rust's memory safety: every value has exactly one owner.
Ce que vous allez apprendre
- One owner per value
- What a move is
- clone and Copy types
let b = a;
before
- a owns "hello"
- b does not exist
after
- a is moved
- b owns "hello"
One owner at a time
Every value in Rust has exactly one owner, and the value is freed when its owner goes out of scope. Assigning a String to another variable moves it: the old variable can no longer be used.
After let b = a the text belongs to b, and using a would be a compile error. clone makes a real copy, so c stays valid when b moves into take. Simple types such as integers are Copy: assigning them copies the value, so x and y both work.
Points clés
- let b = a moves a String: a can no longer be used.
- clone makes a real copy.
- Integers are Copy, so both variables stay valid.
Exemple Rust exécutable
main.rs
fn take(text: String) {
println!("took: {text}");
} // text is dropped here
fn main() {
let a = String::from("hello");
let b = a; // ownership moves from a to b
// println!("{a}"); // error: value borrowed after move
let c = b.clone(); // a deep copy: b and c are both valid
take(b); // b moves into the function
let x = 5;
let y = x; // integers are Copy, so x is still valid
println!("{c} {x} {y}");
}
took: hello
hello 5 5S'entraîner
Ouvrez l'exemple dans le compilateur en ligne, modifiez une valeur ou ajoutez une ligne, et devinez la sortie avant de l'exécuter. Cassez ensuite le code exprès et lisez le message du compilateur.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
S'entraîner avec un défi
Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.
Tous les défis