En bref. Une liste chaînée écrite naïvement, enum Liste { Cons(i32, Liste), Nil }, ne compile pas : E0072, recursive type Liste has infinite size. rustc doit connaître la taille de chaque type, et celui-ci se contient lui-même. La réponse tient en trois lettres, Box, et elle ouvre le premier pointeur intelligent de Rust. Il n’a rien de magique : c’est la possession que tu connais déjà, avec la valeur rangée ailleurs.
Le modèle en une phrase
Une
Box<T>est un pointeur de taille fixe, 8 octets, qui possède seul une valeur rangée sur le tas : on déplace la boîte, jamais la valeur, et la valeur est libérée quand la boîte disparaît.
Deux conséquences, une par onglet de l’animation. La taille : puisque la boîte fait 8 octets quel que soit T, un type peut se contenir lui-même à travers elle. La possession : un seul propriétaire, donc pas de compteur, pas de ramasse-miettes, et un move qui ne coûte que le pointeur.
In short. A naively written linked list, enum Liste { Cons(i32, Liste), Nil }, doesn’t compile: E0072, recursive type Liste has infinite size. rustc must know every type’s size, and this one contains itself. The answer is three letters long, Box, and it opens Rust’s first smart pointer. There’s nothing magic about it: it’s the ownership you already know, with the value stored elsewhere.
The model in one sentence
A
Box<T>is a fixed-size pointer, 8 bytes, that solely owns a value stored on the heap: you move the box, never the value, and the value is freed when the box goes away.
Two consequences, one per tab of the animation. Size: since the box is 8 bytes whatever T is, a type can contain itself through it. Ownership: a single owner, so no counter, no garbage collector, and a move that costs only the pointer.
enum Liste {Cons(i32, Liste),Nil,}
- Une
Listequi contient uneListepar valeur contient uneListe, qui en contient une autre, sans fin. rustc doit connaître la taille de chaque type, et celle-ci n'en a pas. E0072, recursive type `Liste` has infinite size.AListecontaining aListeby value contains aListe, which contains another, endlessly. rustc must know every type's size, and this one has none. E0072, recursive type `Liste` has infinite size. Box<Liste>est un pointeur : 8 octets, quoi qu'il désigne. Un maillon contient donc uni32et un pointeur, 16 octets avec l'alignement. Le type est mesurable, et la suite de la liste vit ailleurs, sur le tas.Box<Liste>is a pointer: 8 bytes, whatever it points to. A link therefore holds ani32and a pointer, 16 bytes with alignment. The type is measurable, and the rest of the list lives elsewhere, on the heap.- Chaque
Box::newalloue un maillon sur le tas et en garde l'adresse. Parcourir la liste, c'est suivre les pointeurs un à un jusqu'àNil:somme(&l)rend 6.EachBox::newallocates a link on the heap and keeps its address. Walking the list means following the pointers one by one down toNil:somme(&l)returns 6. - La règle est générale : une
Box<T>fait la taille d'un pointeur, queTpèse 16 ou 1000 octets. EtOption<Box<T>>ne coûte rien de plus : une boîte n'est jamais nulle, doncNoneprend la place du pointeur nul.The rule is general: aBox<T>is the size of a pointer, whetherTweighs 16 or 1000 bytes. AndOption<Box<T>>costs nothing more: a box is never null, soNonetakes the null pointer's place.
Le type qui se contient lui-même : E0072
enum Liste {
Cons(i32, Liste),
Nil,
}error[E0072]: recursive type `Liste` has infinite size
--> infini.rs:1:1
|
1 | enum Liste {
| ^^^^^^^^^^
2 | Cons(i32, Liste),
| ----- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
|
2 | Cons(i32, Box<Liste>),
| ++++ +Une valeur Rust est rangée à plat, champ après champ. Pour réserver la place d’une Liste, rustc additionne : un i32, 4 octets, plus une Liste, qui vaut 4 octets plus une Liste, et ainsi de suite. L’addition ne termine pas. Le message le dit avec précision : recursive without indirection. Ce n’est pas la récursion qui gêne, c’est l’absence de détour.
La boîte borne la taille
enum Liste {
Cons(i32, Box<Liste>),
Nil,
}
let l = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("somme = {}", somme(&l));somme = 6
Box<Liste> : 8 octets
Liste : 16 octetsUne Box<Liste> est une adresse : 8 octets, que la liste derrière compte un maillon ou un million. Un maillon contient donc un i32 et une adresse, 16 octets une fois aligné. L’addition termine, et la suite de la liste vit ailleurs :
la pile le tas
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌───────┐
│ 1 │ Box ●──┼─────▶│ 2 │ Box ●──┼─────▶│ 3 │ Box ●──┼─────▶│ Nil │
└─────────────┘ └─────────────┘ └─────────────┘ └───────┘
l : 16 o 16 o 16 o 16 oChaque Box::new alloue un maillon sur le tas et en garde l’adresse. somme suit les flèches une à une jusqu’à Nil.
8 octets, quel que soit T
size_of::<[u8; 1000]>() // 1000
size_of::<Box<[u8; 1000]>>() // 8
size_of::<Option<Box<[u8; 1000]>>>() // 8[u8; 1000] : 1000 / Box : 8 / Option<Box> : 8
Liste : 16 / Box : 8 / Option<Box> : 8
i32 : 4 / Box : 8 / Option<Box> : 8La règle ne concerne pas que les listes. La boîte fait la taille d’un pointeur, que T pèse 4 ou 1000 octets. Et l’Option autour ne coûte rien : une boîte n’est jamais nulle, donc rustc donne à None la place du pointeur nul. Option<Box<T>> est le pointeur « peut-être absent » des autres langages, avec l’oubli du cas nul rendu impossible.
La troisième ligne dit aussi quand la boîte ne sert à rien : pour un i32, elle double la taille et ajoute une allocation.
Un seul propriétaire : le move copie le pointeur
let a = Box::new(Image { pixels: [7; 1000] });
println!("a : boîte à {:p}, valeur à {:p}", &a, &*a);
let b = a;
println!("b : boîte à {:p}, valeur à {:p}", &b, &*b);a : boîte à 0x16f095768, valeur à 0x101655ce0
b : boîte à 0x16f095f98, valeur à 0x101655ce0Deux boîtes à deux adresses de pile, une seule valeur, à la même adresse du tas. let b = a a copié 8 octets, pas 1000. Et comme pour tout move, l’ancien nom est vidé :
let a = Box::new(5);
let b = a;
println!("{a} {b}");error[E0382]: borrow of moved value: `a`
--> apres_move.rs:4:16
|
2 | let a = Box::new(5);
| - move occurs because `a` has type `Box<i32>`, which does not implement the `Copy` trait
3 | let b = a;
| - value moved here
4 | println!("{a} {b}");
| ^ value borrowed here after moveC’est le E0382 du premier article, mot pour mot. Box n’ajoute aucune règle : elle applique la possession unique à une valeur qui vit sur le tas.
Lire à travers : Deref
println!("lecture : {}", b.pixels[0]);lecture : 7b est une Box<Image>, et pourtant b.pixels s’écrit sans cérémonie. L’accès aux champs et l’appel de méthode suivent le pointeur tout seuls : c’est le trait Deref. Les opérateurs, eux, ne déréférencent rien :
let b = Box::new(5);
if b == 5 {error[E0308]: mismatched types
--> compare.rs:3:13
|
3 | if b == 5 {
| - ^ expected `Box<{integer}>`, found integer
| |
| expected because this is `Box<{integer}>`Une Box<i32> n’est pas un i32. Quand il faut nommer la valeur, l’étoile la désigne : *b == 5, *b + 1. Avec *b == 5, *b + 1 et b.pow(2), le programme affiche :
cinq
6 25Libérée quand son propriétaire disparaît
fn consommer(b: Box<Image>) {
println!("dans consommer : valeur à {:p}", &*b);
}
consommer(b);
println!("fin de main");dans consommer : valeur à 0x101655ce0
Image libérée (1000 octets)
fin de mainconsommer(b) déplace la boîte dans la fonction : toujours la même adresse. À la sortie de la fonction, plus personne ne possède la valeur, et Drop la libère aussitôt, avant « fin de main ». Le moment de la libération se lit dans le code : c’est la fin de la portée du dernier propriétaire. Ni free à écrire, ni ramasse-miettes à attendre.
Ce que l’image cache
Box::newconstruit d’abord sur la pile.Box::new([0u8; 16_000_000])compile, puis s’arrête à l’exécution en debug : thread ‘main’ has overflowed its stack. L’argument est bâti sur la pile avant d’être déplacé. Pour un grand tampon,vec![0u8; 16_000_000].into_boxed_slice()alloue directement sur le tas et affiche bien16000000.- Boxer ce qui est déjà sur le tas ne sert à rien.
StringetVecfont 24 octets sur la pile et rangent déjà leur contenu sur le tas.Box<String>fait 8 octets, au prix d’une seconde allocation et d’une seconde indirection à chaque lecture. - La boîte a un coût. Une allocation à la création, une libération à la fin, et un saut mémoire à chaque accès. Une liste chaînée de boîtes disperse ses maillons : pour une séquence,
Vec<T>reste presque toujours meilleur. La liste sert ici à comprendre, pas à ranger. Box<dyn Trait>est la même boîte, plus large. Derrière un objet trait, la boîte fait 16 octets : l’adresse de la valeur et celle de la vtable. La possession, elle, ne change pas.- Pour lire, emprunte. Une fonction qui prend
Box<Image>consomme la boîte. Si elle ne fait que lire,&Imagesuffit, et&bs’y convertit tout seul. - Un seul propriétaire, c’est la limite. Quand deux parties du programme doivent posséder la même valeur,
Boxne suffit plus : c’est le sujet deRcetArc, au prochain numéro.
Pour aller plus loin
- Volume 6, numéro 01 de The Rust Loop, Box<T>, ou la possession unique déportée, qui détaille le coût de l’allocation,
Box<dyn>et trois refus de terrain (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). - The Rust Book : utiliser
Box<T>pour pointer vers le tas - La bibliothèque standard :
std::boxed - Index des erreurs : E0072
The type that contains itself: E0072
enum Liste {
Cons(i32, Liste),
Nil,
}error[E0072]: recursive type `Liste` has infinite size
--> infini.rs:1:1
|
1 | enum Liste {
| ^^^^^^^^^^
2 | Cons(i32, Liste),
| ----- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
|
2 | Cons(i32, Box<Liste>),
| ++++ +A Rust value is stored flat, field after field. To reserve room for a Liste, rustc adds up: an i32, 4 bytes, plus a Liste, which is 4 bytes plus a Liste, and so on. The sum never ends. The message says it precisely: recursive without indirection. Recursion isn’t the problem, the missing detour is.
The box bounds the size
enum Liste {
Cons(i32, Box<Liste>),
Nil,
}
let l = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("somme = {}", somme(&l));somme = 6
Box<Liste> : 8 octets
Liste : 16 octetsA Box<Liste> is an address: 8 bytes, whether the list behind it has one link or a million. A link therefore holds an i32 and an address, 16 bytes once aligned. The sum ends, and the rest of the list lives elsewhere:
the stack the heap
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌───────┐
│ 1 │ Box ●──┼─────▶│ 2 │ Box ●──┼─────▶│ 3 │ Box ●──┼─────▶│ Nil │
└─────────────┘ └─────────────┘ └─────────────┘ └───────┘
l: 16 B 16 B 16 B 16 BEach Box::new allocates a link on the heap and keeps its address. somme follows the arrows one by one down to Nil.
8 bytes, whatever T is
size_of::<[u8; 1000]>() // 1000
size_of::<Box<[u8; 1000]>>() // 8
size_of::<Option<Box<[u8; 1000]>>>() // 8[u8; 1000] : 1000 / Box : 8 / Option<Box> : 8
Liste : 16 / Box : 8 / Option<Box> : 8
i32 : 4 / Box : 8 / Option<Box> : 8The rule isn’t only about lists. The box is the size of a pointer, whether T weighs 4 or 1000 bytes. And the Option around it costs nothing: a box is never null, so rustc gives None the null pointer’s place. Option<Box<T>> is other languages’ “maybe absent” pointer, with forgetting the null case made impossible.
The third line also says when the box is pointless: for an i32, it doubles the size and adds an allocation.
A single owner: the move copies the pointer
let a = Box::new(Image { pixels: [7; 1000] });
println!("a : boîte à {:p}, valeur à {:p}", &a, &*a);
let b = a;
println!("b : boîte à {:p}, valeur à {:p}", &b, &*b);a : boîte à 0x16f095768, valeur à 0x101655ce0
b : boîte à 0x16f095f98, valeur à 0x101655ce0Two boxes at two stack addresses, a single value, at the same heap address. let b = a copied 8 bytes, not 1000. And as with any move, the old name is emptied:
let a = Box::new(5);
let b = a;
println!("{a} {b}");error[E0382]: borrow of moved value: `a`
--> apres_move.rs:4:16
|
2 | let a = Box::new(5);
| - move occurs because `a` has type `Box<i32>`, which does not implement the `Copy` trait
3 | let b = a;
| - value moved here
4 | println!("{a} {b}");
| ^ value borrowed here after moveIt’s the E0382 from the first article, word for word. Box adds no rule: it applies single ownership to a value living on the heap.
Reading through: Deref
println!("lecture : {}", b.pixels[0]);lecture : 7b is a Box<Image>, yet b.pixels is written without ceremony. Field access and method calls follow the pointer on their own: that’s the Deref trait. Operators, however, dereference nothing:
let b = Box::new(5);
if b == 5 {error[E0308]: mismatched types
--> compare.rs:3:13
|
3 | if b == 5 {
| - ^ expected `Box<{integer}>`, found integer
| |
| expected because this is `Box<{integer}>`A Box<i32> is not an i32. When the value has to be named, the star does it: *b == 5, *b + 1. With *b == 5, *b + 1 and b.pow(2), the program prints:
cinq
6 25Freed when its owner goes away
fn consommer(b: Box<Image>) {
println!("dans consommer : valeur à {:p}", &*b);
}
consommer(b);
println!("fin de main");dans consommer : valeur à 0x101655ce0
Image libérée (1000 octets)
fin de mainconsommer(b) moves the box into the function: still the same address. When the function returns, nobody owns the value any more, and Drop frees it right away, before “fin de main”. The moment of release can be read in the code: it’s the end of the last owner’s scope. No free to write, no garbage collector to wait for.
What the picture hides
Box::newbuilds on the stack first.Box::new([0u8; 16_000_000])compiles, then stops at runtime in debug: thread ‘main’ has overflowed its stack. The argument is built on the stack before being moved. For a large buffer,vec![0u8; 16_000_000].into_boxed_slice()allocates directly on the heap and does print16000000.- Boxing what’s already on the heap is pointless.
StringandVecare 24 bytes on the stack and already keep their content on the heap.Box<String>is 8 bytes, at the price of a second allocation and a second indirection on every read. - The box has a cost. An allocation at creation, a release at the end, and a memory jump on every access. A linked list of boxes scatters its links: for a sequence,
Vec<T>is almost always better. The list is here to understand, not to store. Box<dyn Trait>is the same box, wider. Behind a trait object, the box is 16 bytes: the value’s address and the vtable’s. Ownership doesn’t change.- To read, borrow. A function taking
Box<Image>consumes the box. If it only reads,&Imageis enough, and&bconverts to it on its own. - A single owner is the limit. When two parts of the program must own the same value,
Boxis no longer enough: that’s the subject ofRcandArc, in the next issue.
Going further
- Volume 6, issue 01 of The Rust Loop, Box<T>, or single ownership relocated, which details the cost of allocation,
Box<dyn>and three field refusals (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). - The Rust Book: using
Box<T>to point to data on the heap - The standard library:
std::boxed - Error index: E0072