Rust errors / Types and traits
Rust compiler error · checked with rustc 1.99.0
Rust error E0072: recursive type has infinite size
What it meansA struct or enum contains itself directly, so its size would be infinite. Put the recursive part behind a pointer such as Box.
What rustc prints
error[E0072]: recursive type `ListNode` has infinite size --> main.rs:1:1 | 1 | struct ListNode { | ^^^^^^^^^^^^^^^ 2 | head: u8, 3 | tail: Option<ListNode>, // error: no indirection here so impossible to | -------- recursive without indirection | help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle | 3 | tail: Option<Box<ListNode>>, // error: no indirection here so impossible to | ++++ +
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
Why it happens
- A linked list or tree node that holds the next node by value.
How to fix it
1. Box the recursive field
enum List {
Cons(i32, Box<List>),
Nil,
}
struct Node { value: i32, children: Vec<Node> } // Vec already adds indirectionOther wordings of this error
recursive type has infinite size, insert some indirection
The compiler team's explanation
A recursive type has infinite size because it doesn't have an indirection.
Erroneous code example:
struct ListNode {
head: u8,
tail: Option<ListNode>, // error: no indirection here so impossible to
// compute the type's size
}
When defining a recursive struct or enum, any use of the type being defined from inside the definition must occur behind a pointer (like Box, & or Rc). This is because structs and enums must have a well-defined size, and without the pointer, the size of the type would need to be unbounded.
In the example, the type cannot have a well-defined size, because it needs to be arbitrarily large (since we would be able to nest ListNodes to any depth). Specifically,
size of `ListNode` = 1 byte for `head`
+ 1 byte for the discriminant of the `Option`
+ size of `ListNode`
One way to fix this is by wrapping ListNode in a Box, like so:
struct ListNode {
head: u8,
tail: Option<Box<ListNode>>,
}
This works because Box is a pointer, so its size is well-known.
From rustc --explain E0072 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0308mismatched types
- E0277the trait bound is not satisfied
- E0599no method named X found in the current scope
- E0433failed to resolve
- E0069`return;` in a function whose return type is not `()`
- E0071expected struct, variant or union type, found `u32`
- E0076SIMD vector's only field must be an array
- E0077SIMD vector element type should be a primitive scalar (integer/float/pointer) type
Up next
Often hit nextE0308: mismatched typesA related error from the same family.Read it next →Did this answer your question?