Understanding Rust Error E0073

Introduction to Rust Error E0073

Rust Error E0073 occurs when a struct or an enum is defined in such a way that it requires an instance of itself to create a new instance. This causes a problem because there would be no way to make the first instance necessary to create subsequent instances. Although the Rust compiler no longer emits this error, understanding the issue can be beneficial when working with recursive data structures.

Example of Rust Error E0073

Consider the following code, which demonstrates a struct that triggers the E0073 error:

fn main() {
  struct Foo { x: Box<Foo> } // error

In this example, the Foo struct contains a field x that is a Box<Foo>, requiring an instance of Foo to be initialized. This circular dependency makes it impossible to create the initial instance of Foo.

Resolving Rust Error E0073

To resolve this issue, you can wrap the field within an Option type. This provides a way to create an initial Foo instance without requiring another Foo instance. Here's an example of how you can modify the struct to fix the error:

fn main() {
  struct Foo { x: Option<Box<Foo>> }

Now, it is possible to create an initial Foo instance with the value Foo { x: None }. This allows for the creation of further instances without causing a circular dependency.

Use Case: Modeling Recursive Data Structures

The concept explained in error E0073 is essential when dealing with recursive data structures, such as trees. For instance, consider the following definition of a binary tree:

enum BinaryTree<T> {
  Node { 
    value: T, 
    left: Box<BinaryTree<T>>, 
    right: Box<BinaryTree<T>> 

In this example, the BinaryTree enum has two variants: Empty and Node. The Node variant contains a value of type T, and references to left and right subtrees. The recursive structure is made possible by utilizing the Option type as demonstrated earlier.