Ownership et emprunt

Rust Ownership and Moves

The rule behind Rust's memory safety: every value has exactly one owner.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
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

  1. let b = a moves a String: a can no longer be used.
  2. clone makes a real copy.
  3. Integers are Copy, so both variables stay valid.

Exemple Rust exécutable

Rust
Exécuter le code →
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}");
}
Obtenir un bouton Run pour cet exemple Résultat de l'exécution
took: hello
hello 5 5

S'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.

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