lotsoftools

Rust Error E0072: Recursive Type with Infinite Size

Understanding Rust Error E0072

Error E0072 in Rust occurs when a recursive type has an infinite size because it lacks indirection. Recursive types require a pointer, such as a Box, &, or Rc, for them to have a well-defined size. When a recursive type is defined without a pointer, it results in a type with an unbounded size.

As shown in the official example:

#![allow(unused)]
fn main() {
struct ListNode {
    head: u8,
    tail: Option<ListNode>,
}
}

The type cannot have a well-defined size since it needs to be arbitrarily large. The Option does not include a pointer, and it results in a circular reference between ListNode and its tail.

Fixing Rust Error E0072

To fix Rust Error E0072, you must introduce a pointer, such as Box, & or Rc, within your recursive type definition. In most cases, using the Box type is the simplest approach, as it adds a level of indirection while maintaining a well-defined size for the type.

Here's an example of how to fix this error using Box:

#![allow(unused)]
fn main() {
struct ListNode {
    head: u8,
    tail: Option<Box<ListNode>>,
}
}

By changing the tail field of the ListNode struct to use an Option containing a Box, the type achieves a well-defined size, and Error E0072 is resolved.

Understanding the Size and Performance Implications

In Rust, the Box type creates a heap allocation and adds a layer of indirection, impacting performance. However, it ensures that recursive types have a well-defined size, making it a practical solution for cases like the one in Rust Error E0072. Using alternative pointers, such as Rc or &, might result in different performance patterns depending on your specific use case.

Considerations with Other Recursive Types

Besides structs, you may encounter Rust Error E0072 when dealing with recursive enums. The same concept applies: add a pointer (Box, &, or Rc) to ensure the recursive enum has a well-defined size.

For example, a recursive enum causing Rust Error E0072:

#![allow(unused)]
fn main() {
enum Tree {
    Leaf(i32),
    Node(Tree, Tree),
}
}

Fix the error by adding a Box pointer:

#![allow(unused)]
fn main() {
enum Tree {
    Leaf(i32),
    Node(Box<Tree>, Box<Tree>),
}
}

By introducing the Box pointers to the Node variant, the enum type achieves a well-defined size, and Rust Error E0072 is resolved.