0Pricing
Learn Rust Coding · Leçon

Comprendre le modèle de propriété de Rust

Assimilez les règles fondamentales de la propriété et la sémantique du déplacement, ainsi que la manière dont elles empêchent les erreurs courantes de mémoire, comme la double libération.

Comprendre le modèle de propriété de Rust est une leçon Learn Rust Coding gratuite sur CoddyKit. Ceci est la leçon 1 sur 3. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Learn Rust Coding, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Learn Rust Coding comprend 3 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

What is Rust Ownership?

Rust's ownership system is a set of rules that manage how your program uses memory. It's a core concept that helps Rust achieve memory safety without a garbage collector.

  • No dangling pointers.
  • No double-free errors.
  • No data races in concurrent code.

It checks these rules at compile time!

Stack vs. Heap Memory

Programs use two main memory areas: the stack and the heap.

  • Stack: Faster, fixed-size data (like integers, booleans, known-size types). Data is pushed and popped in order.
  • Heap: Slower, variable-size data (like String, Vec). Data is requested and returned by the allocator.

Ownership primarily manages data on the heap, ensuring its safe use and cleanup.

Rule 1: Every Value Has an Owner

The first rule of ownership is simple: each value in Rust has a variable that's called its owner.

Think of it like a label on a box. The variable s below is the owner of the text "hello".

fn main() {
  let s = String::from("hello"); // s owns "hello"
  println!("{}", s);
}

Rule 2: Only One Owner at a Time

The second rule states: at any given time, there can only be one owner for a value. This is crucial for preventing memory issues.

When you assign a complex value (like a String, which lives on the heap) from one variable to another, ownership is moved, not copied.

Ownership Transfer in Action

See what happens when s1's value is assigned to s2. Try running the code.

fn main() {
  let s1 = String::from("Hello, CoddyKit!");
  let s2 = s1; // Ownership of the String data moves from s1 to s2

  // println!("{}", s1); // This line would cause a compile-time error!
  println!("{}", s2);
}

Understanding "Move" Semantics

After let s2 = s1;, s1 is no longer considered valid. Rust prevents you from using s1 again.

  • This is called a move. The pointer, length, and capacity on the stack are copied, but the heap data itself is not.
  • If s1 were still valid, both s1 and s2 would try to free the same memory when they go out of scope (a double-free error).

Rust's ownership system prevents this at compile time!

Ownership and Function Calls

Passing a value to a function works similarly to assigning it to another variable: ownership is moved into the function.

When the function finishes, the value's owner (the function parameter) goes out of scope, and the value is dropped.

Function Ownership Demo

Observe how the String value is moved into takes_ownership and then gives_ownership returns a new String.

fn takes_ownership(some_string: String) {
  println!("Inside takes_ownership: {}", some_string);
} // some_string goes out of scope and `drop` is called.

fn gives_ownership() -> String {
  let some_string = String::from("returned string");
  some_string // Ownership is moved out of the function
}

fn main() {
  let s1 = String::from("hello");
  takes_ownership(s1); // s1's value moves into takes_ownership
  // println!("{}", s1); // Error: s1 is no longer valid here!

  let s2 = gives_ownership(); // s2 gets ownership of the returned String
  println!("After gives_ownership: {}", s2);
}

Rule 3: Scope & Dropping

The final rule: when the owner goes out of scope, the value will be dropped.

  • A scope is the range within a program for which an item is valid, usually defined by {} curly brackets.
  • When a variable goes out of scope, Rust automatically calls a special function called drop.

This ensures memory is cleaned up automatically, safely, and without a garbage collector.

Preventing Memory Errors

The ownership rules work together to guarantee memory safety:

  • One owner: Prevents multiple parts of your code from trying to free the same memory.
  • Drop on scope end: Ensures memory is freed exactly once, and at the correct time.

This eliminates common bugs like double-free errors and use-after-free errors at compile time, giving you peace of mind!

Ownership Check

Consider the following Rust code. What will happen when you try to compile and run it?

fn main() {
  let message = String::from("Rust is fun!");
  let greeting = message;
  println!("{}", message);
}

Recap: Ownership Basics

Great job! You've learned the fundamental rules of Rust's ownership system:

  • Every value has an owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value is dropped.

This system prevents common memory errors without a garbage collector. Next, we'll explore borrowing to share data without transferring ownership.

Questions Fréquemment Posées

La leçon « Comprendre le modèle de propriété de Rust » est-elle gratuite ?

Oui — le texte complet de « Comprendre le modèle de propriété de Rust » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Learn Rust Coding, passe à CoddyKit PRO. Le cours Learn Rust Coding comprend 3 leçons au total.

Qu'est-ce que j'apprendrai dans « Comprendre le modèle de propriété de Rust » ?

Assimilez les règles fondamentales de la propriété et la sémantique du déplacement, ainsi que la manière dont elles empêchent les erreurs courantes de mémoire, comme la double libération. Tu pratiques Learn Rust Coding avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Learn Rust Coding ?

Aucune expérience préalable n'est requise. Learn Rust Coding sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 3.

Combien de temps prend la leçon « Comprendre le modèle de propriété de Rust » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Learn Rust Coding ?

Oui. Chaque leçon Learn Rust Coding inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Comprendre le modèle de propriété de Rust
  2. Références et emprunt expliqués
  3. Durées de vie pour des références sûres
← Retour à Learn Rust Coding