« recursive type has infinite size » : Box<T> en Rust, le modèle mental (E0072) "recursive type has infinite size": Box<T> in Rust, the mental model (E0072)

Une Box<T> est un pointeur de taille fixe, 8 octets, qui possède seul une valeur rangée sur le tas. C'est ce qui rend mesurable un type récursif (E0072), et ce qui fait qu'un move ne copie que le pointeur. Tailles mesurées, Deref (E0308), Drop, et le piège du grand tableau qui passe par la pile. Animation et sorties réelles de rustc.A Box<T> is a fixed-size pointer, 8 bytes, that solely owns a value stored on the heap. That is what makes a recursive type measurable (E0072), and why a move copies only the pointer. Measured sizes, Deref (E0308), Drop, and the trap of the big array going through the stack. Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
PointeursPointers
PubliéPublished

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,
}
Liste, rangée par valeurListe, stored by valuetaille infinieinfinite sizeListei32 · 4 oListei32 · 4 oListei32 · 4 oListei32 · 4 o…taille(Liste) = 4 + taille(Liste) = 4 + 4 + taille(Liste) = …size(Liste) = 4 + size(Liste) = 4 + 4 + size(Liste) = …E0072 · recursive type `Liste` has infinite sizeE0072 · recursive type `Liste` has infinite size
  1. Une Liste qui contient une Liste par valeur contient une Liste, 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.A Liste containing a Liste by value contains a Liste, which contains another, endlessly. rustc must know every type's size, and this one has none. E0072, recursive type `Liste` has infinite size.
  2. Box<Liste> est un pointeur : 8 octets, quoi qu'il désigne. Un maillon contient donc un i32 et 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 an i32 and a pointer, 16 bytes with alignment. The type is measurable, and the rest of the list lives elsewhere, on the heap.
  3. Chaque Box::new alloue 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.Each Box::new allocates a link on the heap and keeps its address. Walking the list means following the pointers one by one down to Nil: somme(&l) returns 6.
  4. La règle est générale : une Box<T> fait la taille d'un pointeur, que T pèse 16 ou 1000 octets. Et Option<Box<T>> ne coûte rien de plus : une boîte n'est jamais nulle, donc None prend la place du pointeur nul.The rule is general: a Box<T> is the size of a pointer, whether T weighs 16 or 1000 bytes. And Option<Box<T>> costs nothing more: a box is never null, so None takes the null pointer's place.
La taille avec Box<T> en Rust : un type récursif par valeur a une taille infinie (E0072). Box<Liste> est un pointeur de 8 octets, donc un maillon fait 16 octets et la suite de la liste vit sur le tas.Size with Box<T> in Rust: a type recursive by value has infinite size (E0072). Box<Liste> is an 8-byte pointer, so a link is 16 bytes and the rest of the list lives on the heap.

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 octets

Une 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 o

Chaque 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> : 8

La 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 à 0x101655ce0

Deux 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 move

C’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 : 7

b 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 25

Libé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 main

consommer(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::new construit 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 bien 16000000.
  • Boxer ce qui est déjà sur le tas ne sert à rien. String et Vec font 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, &Image suffit, et &b s’y convertit tout seul.
  • Un seul propriétaire, c’est la limite. Quand deux parties du programme doivent posséder la même valeur, Box ne suffit plus : c’est le sujet de Rc et Arc, au prochain numéro.

Pour aller plus loin

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 octets

A 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 B

Each 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> : 8

The 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 à 0x101655ce0

Two 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 move

It’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 : 7

b 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 25

Freed 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 main

consommer(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::new builds 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 print 16000000.
  • Boxing what’s already on the heap is pointless. String and Vec are 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, &Image is enough, and &b converts to it on its own.
  • A single owner is the limit. When two parts of the program must own the same value, Box is no longer enough: that’s the subject of Rc and Arc, in the next issue.

Going further

Questions fréquentesFrequently asked questions

Que signifie « recursive type has infinite size » (E0072) ?What does "recursive type has infinite size" (E0072) mean?

Ton type se contient lui-même par valeur : enum Liste { Cons(i32, Liste), Nil }. Pour ranger une Liste, rustc doit connaître sa taille, or elle vaut 4 octets plus la taille d'une Liste, sans fin. Correctif, celui que rustc propose : mettre la partie récursive derrière un pointeur, Cons(i32, Box<Liste>). Une Box fait 8 octets quoi qu'elle désigne, et le type devient mesurable : 16 octets.Your type contains itself by value: enum Liste { Cons(i32, Liste), Nil }. To store a Liste, rustc must know its size, but that size is 4 bytes plus the size of a Liste, endlessly. Fix, the one rustc suggests: put the recursive part behind a pointer, Cons(i32, Box<Liste>). A Box is 8 bytes whatever it points to, and the type becomes measurable: 16 bytes.

Où vit une Box<T>, sur la pile ou sur le tas ?Where does a Box<T> live, on the stack or on the heap?

Les deux. La boîte elle-même est un pointeur : 8 octets sur une machine 64 bits, rangés là où tu ranges la variable, en général sur la pile. La valeur qu'elle désigne vit sur le tas. Mesuré avec size_of : Box<[u8; 1000]> fait 8 octets, [u8; 1000] en fait 1000. Et Option<Box<T>> fait 8 octets aussi, car une boîte n'est jamais nulle : None prend la place du pointeur nul.Both. The box itself is a pointer: 8 bytes on a 64-bit machine, stored wherever you store the variable, usually on the stack. The value it points to lives on the heap. Measured with size_of: Box<[u8; 1000]> is 8 bytes, [u8; 1000] is 1000. And Option<Box<T>> is 8 bytes too, because a box is never null: None takes the null pointer's place.

Quand utiliser Box<T>, et quand s'en passer ?When should you use Box<T>, and when not?

Trois cas la justifient : un type récursif (liste, arbre), un objet trait possédé (Box<dyn Trait>), et une grosse valeur qu'on déplace souvent, puisque le move ne copie alors que 8 octets. En dehors de ça, la pile suffit. Box<String> ou Box<Vec<T>> n'apportent presque jamais rien : String et Vec rangent déjà leur contenu sur le tas, et la boîte ajoute une allocation et une indirection.Three cases justify it: a recursive type (list, tree), an owned trait object (Box<dyn Trait>), and a large value you move often, since the move then copies only 8 bytes. Outside of those, the stack is enough. Box<String> or Box<Vec<T>> almost never bring anything: String and Vec already keep their content on the heap, and the box adds an allocation and an indirection.

Pourquoi `b == 5` donne-t-il E0308 quand b est une Box<i32> ?Why does `b == 5` give E0308 when b is a Box<i32>?

Parce qu'une Box<i32> n'est pas un i32. L'appel de méthode et l'accès aux champs suivent le pointeur tout seuls (Deref), mais un opérateur comme == compare deux valeurs du même type, sans rien déréférencer. Il faut nommer la valeur : *b == 5. De même, *b + 1 pour calculer avec le contenu, alors que b.pow(2) passe sans étoile.Because a Box<i32> is not an i32. Method calls and field access follow the pointer on their own (Deref), but an operator like == compares two values of the same type, dereferencing nothing. You have to name the value: *b == 5. Likewise *b + 1 to compute with the content, whereas b.pow(2) works without the star.

Pourquoi Box::new([0u8; 16_000_000]) fait-il déborder la pile ?Why does Box::new([0u8; 16_000_000]) overflow the stack?

Box::new est une fonction ordinaire : son argument est d'abord construit, sur la pile, puis déplacé vers le tas. Un tableau de 16 Mo ne tient pas dans une pile de 8 Mo, et le programme s'arrête sur « thread 'main' has overflowed its stack ». En release, l'optimiseur évite souvent ce passage, sans le garantir. Pour un grand tampon, alloue directement sur le tas : vec![0u8; 16_000_000].into_boxed_slice().Box::new is an ordinary function: its argument is first built, on the stack, then moved to the heap. A 16 MB array doesn't fit in an 8 MB stack, and the program stops with "thread 'main' has overflowed its stack". In release, the optimizer often avoids that detour, without guaranteeing it. For a large buffer, allocate directly on the heap: vec![0u8; 16_000_000].into_boxed_slice().

RustBoxSmart pointersTasE0072Modèle mental

← Tous les articlesAll articles