En bref. L’emprunt pose une règle : plusieurs lecteurs, ou un seul écrivain. Le compilateur la vérifie, et refuse tout ce qu’il ne sait pas prouver. Cell et RefCell permettent de modifier une valeur à travers une référence partagée &, en garantissant la règle autrement. Avec RefCell, la vérification a lieu à l’exécution, et une erreur ne s’appelle plus E0502 : elle s’appelle RefCell already borrowed, et c’est un panic.
Le modèle en une phrase
Un
RefCell<T>range, à côté de la valeur, un registre d’emprunts :borrow()y inscrit un lecteur,borrow_mut()exige qu’il soit vide, et une violation de la règle arrête le programme au lieu d’arrêter la compilation.
La règle ne change pas, seul le moment de la vérification change. Et Cell évite la question : il ne prête jamais de référence, donc il n’a rien à vérifier. Le second onglet de l’animation compare les trois réponses.
In short. Borrowing sets a rule: many readers, or a single writer. The compiler checks it, and refuses whatever it can’t prove. Cell and RefCell let you modify a value through a shared & reference, by guaranteeing the rule another way. With RefCell, the check happens at runtime, and a mistake is no longer called E0502: it’s called RefCell already borrowed, and it’s a panic.
The model in one sentence
A
RefCell<T>stores, next to the value, a borrow registry:borrow()registers a reader,borrow_mut()requires it to be empty, and breaking the rule stops the program instead of stopping the compilation.
The rule doesn’t change, only the moment of the check does. And Cell sidesteps the question: it never lends a reference, so it has nothing to check. The animation’s second tab compares the three answers.
let journal = RefCell::new(vec![String::from("démarrage")]);
RefCell::newrange la valeur avec un registre d'emprunts à côté d'elle. Personne n'a encore emprunté : le registre est vide.RefCell::newstores the value with a borrow registry next to it. Nobody has borrowed yet: the registry is empty.borrow()inscrit un lecteur et rend unRef, un garde qui se désinscrit quand il disparaît. Des lecteurs, autant qu'on veut. Mais tant qu'ils vivent,try_borrow_mut()répondErr.borrow()registers a reader and returns aRef, a guard that unregisters itself when it goes away. As many readers as you like. But while they live,try_borrow_mut()answersErr.borrow_mut()exige un registre vide. Il ne l'est pas : le programme, qui a compilé sans un avertissement, panique à cette ligne avec « RefCell already borrowed ». C'est E0502, reporté à l'exécution.borrow_mut()requires an empty registry. It isn't: the program, which compiled without a single warning, panics on this line with "RefCell already borrowed". It's E0502, postponed to runtime.- Les lecteurs rendus, le registre retombe à zéro et l'écrivain passe, seul : pendant qu'il vit, même
try_borrow()répondErr. La règle n'a pas changé, seulement le moment où elle est vérifiée.Once the readers are released, the registry falls back to zero and the writer goes through, alone: while it lives, eventry_borrow()answersErr. The rule hasn't changed, only the moment it's checked.
Le problème : écrire derrière un &
struct Compteur {
appels: u32,
}
impl Compteur {
fn enregistrer(&self) {
self.appels += 1;
}
}error[E0594]: cannot assign to `self.appels`, which is behind a `&` reference
--> self_ref.rs:7:9
|
7 | self.appels += 1;
| ^^^^^^^^^^^^^^^^ `self` is a `&` reference, so it cannot be written to
|
help: consider changing this to be a mutable reference
|
6 | fn enregistrer(&mut self) {
| +++Le conseil de rustc est le bon dans la plupart des cas. Mais &mut self a un coût : tout appelant doit détenir l’exclusivité sur le Compteur. Pour un compteur d’appels, un cache ou un journal, c’est disproportionné : vu de l’extérieur, la méthode ne fait que lire. On veut une méthode en &self dont un détail interne change. C’est la mutabilité intérieure.
Cell : copier, ne jamais prêter
struct Compteur {
appels: Cell<u32>,
}
impl Compteur {
fn enregistrer(&self) {
self.appels.set(self.appels.get() + 1);
}
}appels : 2Cell contourne la règle sans la violer. La règle de l’emprunt protège les références : personne ne doit lire une valeur pendant qu’un autre la modifie. Cell ne donne jamais de référence vers son contenu. get() en sort une copie, set() en range une nouvelle. Sans référence en circulation, rien ne peut être observé à moitié modifié.
Deux conséquences. Cell<u32> fait 4 octets, comme un u32 : aucun registre, aucun test, aucun panic possible. Et get() n’existe que pour les types Copy : sur un Cell<String>, rustc répond E0599, « the method get exists for struct Cell<String>, but its trait bounds were not satisfied », parce que String n’est pas Copy. Pour un Vec ou une String, on veut une référence vers l’intérieur. Il faut autre chose.
RefCell : la même règle, à l’exécution
let journal = RefCell::new(vec![String::from("démarrage")]);
let a = journal.borrow();
let b = journal.borrow();
println!("deux lecteurs : {} et {}", a.len(), b.len());
println!("écrire ? : {:?}", journal.try_borrow_mut().is_ok());
drop(a);
drop(b);
println!("écrire ? : {:?}", journal.try_borrow_mut().is_ok());
journal.borrow_mut().push(String::from("requête"));
{
let ecrivain = journal.borrow_mut();
println!("lire ? : {:?}", journal.try_borrow().is_ok());
drop(ecrivain);
}
println!("journal : {:?}", journal.borrow());deux lecteurs : 1 et 1
écrire ? : false
écrire ? : true
lire ? : false
journal : ["démarrage", "requête"]RefCell prête des références, donc il les compte :
journal : RefCell<Vec<String>> 32 octets
┌───────────────────┬──────────────────────────────┐
│ registre │ valeur │
│ 2 lecteurs │ Vec { ptr, len, cap } │
└───────────────────┴──────────────────────────────┘
▲ ▲
│ └── b : Ref chaque garde se désinscrit
└─────── a : Ref quand il disparaît
borrow_mut() ? registre non vide → refusborrow() rend un Ref, borrow_mut() un RefMut. Ce sont des gardes : ils se comportent comme &T et &mut T, et leur Drop met le registre à jour. La sortie dit le reste. Deux lecteurs vivants : écrire est refusé. Lecteurs rendus : écrire est accordé. Un écrivain vivant : même lire est refusé. C’est mot pour mot la règle du deuxième article.
Le panic : « RefCell already borrowed »
try_borrow_mut() rend un Result. borrow_mut(), lui, ne négocie pas :
let journal = RefCell::new(vec![String::from("démarrage")]);
let premier = journal.borrow();
journal.borrow_mut().push(String::from("requête"));
println!("{}", premier[0]);thread 'main' (509474) panicked at panic_lecteur.rs:6:13:
RefCell already borrowedLe même programme avec des références ordinaires ne compile pas :
error[E0502]: cannot borrow `journal` as mutable because it is also borrowed as immutable
--> compile.rs:4:5
|
3 | let premier = &journal;
| -------- immutable borrow occurs here
4 | journal.push(String::from("requête"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("{}", premier[0]);
| ------- immutable borrow later used hereMême faute, même ligne, même diagnostic. La différence est le moment : E0502 te l’apprend avant la mise en production, le panic pendant. Et seulement si l’exécution passe par cette ligne : un RefCell mal utilisé dans une branche rare peut dormir longtemps.
Dans l’autre sens (un borrow() pendant qu’un écrivain vit), le message devient « RefCell already mutably borrowed ».
La forme la plus fréquente du piège est un emprunt qu’on ne voit pas :
for ligne in journal.borrow().iter() {
if ligne == "démarrage" {
journal.borrow_mut().push(String::from("prêt"));
}
}thread 'main' (509705) panicked at boucle.rs:7:21:
RefCell already borrowedLe Ref créé dans l’en-tête du for vit pendant toute la boucle. Le réflexe à prendre : des emprunts courts, rendus avant d’appeler quoi que ce soit qui pourrait emprunter à son tour.
Rc<RefCell<T>> : partagé et modifiable
L’article précédent s’arrêtait là : un Rc a plusieurs propriétaires, donc son contenu est en lecture seule (E0596). RefCell fournit la moitié manquante :
let a = Rc::new(RefCell::new(vec![1, 2, 3]));
let b = Rc::clone(&a);
a.borrow_mut().push(4);
println!("{:?} {:?}", a.borrow(), b.borrow());
println!("même valeur : {}", Rc::ptr_eq(&a, &b));[1, 2, 3, 4] [1, 2, 3, 4]
même valeur : trueRc compte les propriétaires, RefCell compte les emprunts. Les deux propriétaires voient la modification, à la différence de Rc::make_mut, qui clonait.
Entre threads : Mutex
let total = Arc::new(RefCell::new(0));
let copie = Arc::clone(&total);
let h = thread::spawn(move || {
*copie.borrow_mut() += 1;
});error[E0277]: `RefCell<i32>` cannot be shared between threads safely
--> thread_refcell.rs:8:27
|
8 | let h = thread::spawn(move || {
| _____________-------------_^
| | |
| | required by a bound introduced by this call
9 | | *copie.borrow_mut() += 1;
10 | | });
| |_____^ `RefCell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
= note: required for `Arc<RefCell<i32>>` to implement `Send`Le registre est un entier ordinaire, comme le compteur de Rc : deux threads pourraient s’y inscrire en même temps. RefCell n’est pas Sync, et le compilateur le sait. L’équivalent entre threads est un verrou :
let total = Arc::new(Mutex::new(0));
// quatre threads, chacun :
for _ in 0..1000 {
*copie.lock().unwrap() += 1;
}total : 4000Mutex tient le même rôle que RefCell, avec une différence de comportement : en cas de conflit, le thread attend son tour au lieu de paniquer. Rc<RefCell<T>> dans un thread, Arc<Mutex<T>> entre plusieurs.
Ce que l’image cache
Rc<RefCell<T>>n’est pas un réflexe. Il réintroduit à l’exécution les erreurs que le compilateur éliminait. Un seul propriétaire qui passe des&muten argument, ou unVecavec des indices à la place de pointeurs, suffit souvent, et reste vérifié à la compilation.try_borrowettry_borrow_mutrendent unResult. Quand un conflit est une situation normale et non un bug, on le traite au lieu de paniquer.Cellne se limite pas aux typesCopy. Seulget()l’exige.set()etreplace()déplacent la valeur entière, pour n’importe quelT.- Le prix se mesure.
u32etCell<u32>: 4 octets.RefCell<u32>etMutex<u32>: 16 octets (rustc 1.100, macOS arm64), plus un test à chaque emprunt. - Le
mutde la déclaration ne dit plus tout. Unlet journalsansmutpeut changer s’il contient unRefCell. C’est le sens du mot « intérieure » : la mutabilité est dans le type, pas dans la liaison.
Pour aller plus loin
- Volume 6, numéro 03 de The Rust Loop, Cell / RefCell & l’interior mutability, qui détaille le borrow check à l’exécution et le réflexe
Rc<RefCell>à éviter (lien en bas de page). - Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119), panic et invariants, traits et generics (E0369), dyn et vtable (E0038), règle de l’orphelin (E0117), Box et types récursifs (E0072), Rc et Arc (E0277). - The Rust Book :
RefCell<T>et le motif de mutabilité intérieure - La bibliothèque standard : le module
std::cell - L’index des erreurs : E0594
The problem: writing behind a &
struct Compteur {
appels: u32,
}
impl Compteur {
fn enregistrer(&self) {
self.appels += 1;
}
}error[E0594]: cannot assign to `self.appels`, which is behind a `&` reference
--> self_ref.rs:7:9
|
7 | self.appels += 1;
| ^^^^^^^^^^^^^^^^ `self` is a `&` reference, so it cannot be written to
|
help: consider changing this to be a mutable reference
|
6 | fn enregistrer(&mut self) {
| +++rustc’s advice is the right one in most cases. But &mut self has a cost: every caller must hold exclusive access to the Compteur. For a call counter, a cache or a log, that’s out of proportion: seen from outside, the method only reads. You want a &self method with one internal detail that changes. That’s interior mutability.
Cell: copy, never lend
struct Compteur {
appels: Cell<u32>,
}
impl Compteur {
fn enregistrer(&self) {
self.appels.set(self.appels.get() + 1);
}
}appels : 2Cell gets around the rule without breaking it. The borrowing rule protects references: nobody may read a value while someone else modifies it. Cell never gives out a reference to its content. get() takes a copy out, set() stores a new one. With no reference in circulation, nothing can be observed half-modified.
Two consequences. Cell<u32> is 4 bytes, like a u32: no registry, no test, no possible panic. And get() only exists for Copy types: on a Cell<String>, rustc answers E0599, “the method get exists for struct Cell<String>, but its trait bounds were not satisfied”, because String isn’t Copy. For a Vec or a String, you want a reference to the inside. Something else is needed.
RefCell: the same rule, at runtime
let journal = RefCell::new(vec![String::from("démarrage")]);
let a = journal.borrow();
let b = journal.borrow();
println!("deux lecteurs : {} et {}", a.len(), b.len());
println!("écrire ? : {:?}", journal.try_borrow_mut().is_ok());
drop(a);
drop(b);
println!("écrire ? : {:?}", journal.try_borrow_mut().is_ok());
journal.borrow_mut().push(String::from("requête"));
{
let ecrivain = journal.borrow_mut();
println!("lire ? : {:?}", journal.try_borrow().is_ok());
drop(ecrivain);
}
println!("journal : {:?}", journal.borrow());deux lecteurs : 1 et 1
écrire ? : false
écrire ? : true
lire ? : false
journal : ["démarrage", "requête"]RefCell lends references, so it counts them:
journal: RefCell<Vec<String>> 32 bytes
┌───────────────────┬──────────────────────────────┐
│ registry │ value │
│ 2 readers │ Vec { ptr, len, cap } │
└───────────────────┴──────────────────────────────┘
▲ ▲
│ └── b: Ref each guard unregisters
└─────── a: Ref itself when it goes away
borrow_mut()? registry not empty → refusedborrow() returns a Ref, borrow_mut() a RefMut. They are guards: they behave like &T and &mut T, and their Drop updates the registry. The output says the rest. Two living readers: writing is refused. Readers released: writing is granted. A living writer: even reading is refused. It’s word for word the rule from the second article.
The panic: “RefCell already borrowed”
try_borrow_mut() returns a Result. borrow_mut() doesn’t negotiate:
let journal = RefCell::new(vec![String::from("démarrage")]);
let premier = journal.borrow();
journal.borrow_mut().push(String::from("requête"));
println!("{}", premier[0]);thread 'main' (509474) panicked at panic_lecteur.rs:6:13:
RefCell already borrowedThe same program with ordinary references doesn’t compile:
error[E0502]: cannot borrow `journal` as mutable because it is also borrowed as immutable
--> compile.rs:4:5
|
3 | let premier = &journal;
| -------- immutable borrow occurs here
4 | journal.push(String::from("requête"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("{}", premier[0]);
| ------- immutable borrow later used hereSame mistake, same line, same diagnosis. The difference is the moment: E0502 tells you before going to production, the panic during. And only if execution goes through that line: a misused RefCell in a rare branch can sleep for a long time.
The other way round (a borrow() while a writer lives), the message becomes “RefCell already mutably borrowed”.
The most frequent form of the trap is a borrow you don’t see:
for ligne in journal.borrow().iter() {
if ligne == "démarrage" {
journal.borrow_mut().push(String::from("prêt"));
}
}thread 'main' (509705) panicked at boucle.rs:7:21:
RefCell already borrowedThe Ref created in the for header lives for the whole loop. The reflex to build: short borrows, released before calling anything that might borrow in turn.
Rc<RefCell<T>>: shared and mutable
The previous article stopped there: an Rc has several owners, so its content is read-only (E0596). RefCell provides the missing half:
let a = Rc::new(RefCell::new(vec![1, 2, 3]));
let b = Rc::clone(&a);
a.borrow_mut().push(4);
println!("{:?} {:?}", a.borrow(), b.borrow());
println!("même valeur : {}", Rc::ptr_eq(&a, &b));[1, 2, 3, 4] [1, 2, 3, 4]
même valeur : trueRc counts owners, RefCell counts borrows. Both owners see the change, unlike Rc::make_mut, which cloned.
Across threads: Mutex
let total = Arc::new(RefCell::new(0));
let copie = Arc::clone(&total);
let h = thread::spawn(move || {
*copie.borrow_mut() += 1;
});error[E0277]: `RefCell<i32>` cannot be shared between threads safely
--> thread_refcell.rs:8:27
|
8 | let h = thread::spawn(move || {
| _____________-------------_^
| | |
| | required by a bound introduced by this call
9 | | *copie.borrow_mut() += 1;
10 | | });
| |_____^ `RefCell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
= note: required for `Arc<RefCell<i32>>` to implement `Send`The registry is a plain integer, like Rc’s counter: two threads could register at the same time. RefCell isn’t Sync, and the compiler knows it. The cross-thread equivalent is a lock:
let total = Arc::new(Mutex::new(0));
// four threads, each:
for _ in 0..1000 {
*copie.lock().unwrap() += 1;
}total : 4000Mutex plays the same role as RefCell, with one difference in behaviour: on a conflict, the thread waits its turn instead of panicking. Rc<RefCell<T>> within one thread, Arc<Mutex<T>> across several.
What the picture hides
Rc<RefCell<T>>isn’t a reflex. It brings back at runtime the mistakes the compiler used to eliminate. A single owner passing&mutas arguments, or aVecwith indices instead of pointers, is often enough, and stays checked at compile time.try_borrowandtry_borrow_mutreturn aResult. When a conflict is a normal situation and not a bug, you handle it instead of panicking.Cellisn’t limited toCopytypes. Onlyget()requires it.set()andreplace()move the whole value, for anyT.- The price can be measured.
u32andCell<u32>: 4 bytes.RefCell<u32>andMutex<u32>: 16 bytes (rustc 1.100, macOS arm64), plus a test on each borrow. - The declaration’s
mutno longer tells everything. Alet journalwithoutmutcan change if it contains aRefCell. That’s the meaning of “interior”: the mutability is in the type, not in the binding.
Going further
- Volume 6, issue 03 of The Rust Loop, Cell / RefCell & interior mutability, which details the runtime borrow check and the
Rc<RefCell>reflex to avoid (link at the bottom of the page). - Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119), panic and invariants, traits and generics (E0369), dyn and the vtable (E0038), the orphan rule (E0117), Box and recursive types (E0072), Rc and Arc (E0277). - The Rust Book:
RefCell<T>and the interior mutability pattern - The standard library: the
std::cellmodule - The error index: E0594