Mutabilité intérieure : RefCell, Cell
Découvrez `RefCell` et `Cell` pour la mutabilité intérieure, qui permettent d’accéder aux données de manière mutable à travers une référence immuable, en toute sécurité.
Mutabilité intérieure : RefCell, Cell est une leçon Learn Rust Coding gratuite sur CoddyKit. Ceci est la leçon 2 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 Interior Mutability?
In Rust, the borrowing rules usually prevent you from having a mutable reference to data if you already have an immutable reference to it. This ensures data safety.
Interior mutability is a design pattern that allows you to mutate data even when you only have an immutable reference to it. It's like a controlled exception to Rust's usual rules, used in specific situations.
`Cell<T>`: For Copy Types
The Cell<T> type provides interior mutability for types that implement the Copy trait (like integers, booleans, characters). It works by replacing the value inside.
get(): Returns a copy of the value inside theCell.set(value): Replaces the value inside theCellwith a new one.
It's simple and efficient for small, copyable data.
Using `Cell` to Update Values
Here's a basic example of Cell. Notice how we can change the value inside the Cell even though the Cell itself is declared as immutable.
use std::cell::Cell;
fn main() {
let my_num = Cell::new(10);
println!("Initial value: {}", my_num.get());
my_num.set(20);
println!("Updated value: {}", my_num.get());
let x = &my_num;
x.set(30); // Still works via immutable reference!
println!("Via immutable ref: {}", my_num.get());
}`RefCell<T>`: For Non-Copy Types
When you need interior mutability for types that do not implement Copy (like String, Vec, or custom structs), you use RefCell<T>.
RefCell allows you to get mutable references to the inner data, but it enforces Rust's borrowing rules at runtime, not compile time.
`RefCell`'s Runtime Borrowing
RefCell provides methods that return smart pointers:
borrow(): Returns aRef(an immutable smart pointer). You can have multiple immutable borrows at once.borrow_mut(): Returns aRefMut(a mutable smart pointer). You can have only one mutable borrow at a time.
If you violate these rules at runtime, your program will panic!.
Using `RefCell` (Immutable Borrow)
Here, we use borrow() to get an immutable reference to the String inside the RefCell. We can print its content.
use std::cell::RefCell;
fn main() {
let my_string_cell = RefCell::new(String::from("Hello"));
let s1 = my_string_cell.borrow();
println!("Value: {}", *s1); // Dereference Ref to get String
let s2 = my_string_cell.borrow(); // Multiple immutable borrows are fine
println!("Another value: {}", *s2);
}Using `RefCell` (Mutable Borrow)
Now, let's get a mutable reference using borrow_mut(). This allows us to modify the String. Note that once s_mut is in scope, no other borrows (mutable or immutable) are allowed.
use std::cell::RefCell;
fn main() {
let my_string_cell = RefCell::new(String::from("World"));
{ // Scope for the mutable borrow
let mut s_mut = my_string_cell.borrow_mut();
s_mut.push_str(", Rust!");
}
// s_mut is out of scope here, so we can borrow again
let s_final = my_string_cell.borrow();
println!("Final value: {}", *s_final);
}The `RefCell` Runtime Panic
If you try to get a mutable borrow while another mutable borrow (or any immutable borrow) is active, RefCell will cause your program to panic! at runtime. This prevents data corruption.
Run this code to see it in action! It will crash with a "borrow already in use" error.
use std::cell::RefCell;
fn main() {
let my_value = RefCell::new(vec![1, 2, 3]);
let _first_mut_borrow = my_value.borrow_mut();
println!("First mutable borrow is active.");
// This line will cause a runtime panic!
// Try commenting it out to see the program run successfully.
let _second_mut_borrow = my_value.borrow_mut();
println!("This line will not be reached.");
}`Cell` vs. `RefCell` Summary
Choosing between Cell and RefCell depends on your data type and how you need to interact with it:
Cell<T>: Use for types that implementCopy. It replaces the entire value and is generally simpler and more performant.RefCell<T>: Use for types that do not implementCopy. It provides references to the inner data and enforces borrowing rules at runtime, allowing more complex mutations.
Quick Check: Cell or RefCell?
You have a struct that needs to store a mutable counter (u32) and a mutable list of names (Vec<String>), and both need to be updated through an immutable reference to the struct. Which interior mutability types would you use for each field?
Recap: Interior Mutability
You've learned about Rust's interior mutability pattern, which allows modifying data through an immutable reference in a controlled, safe way.
Cell<T>: ForCopytypes, replaces the inner value.RefCell<T>: For non-Copytypes, provides runtime-checked mutable/immutable references.- Violating
RefCell's rules leads to a runtime panic, ensuring safety.
These types are crucial for patterns like mock objects, circular references, or when a shared immutable reference needs to track internal state.
Questions Fréquemment Posées
La leçon « Mutabilité intérieure : RefCell, Cell » est-elle gratuite ?
Oui — le texte complet de « Mutabilité intérieure : RefCell, Cell » 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 « Mutabilité intérieure : RefCell, Cell » ?
Découvrez `RefCell` et `Cell` pour la mutabilité intérieure, qui permettent d’accéder aux données de manière mutable à travers une référence immuable, en toute sécurité. 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 2 sur 3.
Combien de temps prend la leçon « Mutabilité intérieure : RefCell, Cell » ?
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
- Pointeurs intelligents Box, Rc et Arc
- Mutabilité intérieure : RefCell, Cell
- Concurrence sans crainte avec les threads