Box and variable size

We've previously bumped into the need for Rust to know exactly how many bytes a particular data value can occupy. Most of the time, Rust can figure that out, and most of the time, it's not a problem, but there are a few cases where it's impossible to define a fixed size for a data value.

One fundamental example is a data structure, such as the following one, where an instance contains other instances of itself:

pub struct TreeNode {
pub value: i32,
pub left: TreeNode,
pub right: TreeNode,
}

That looks reasonable at first glance, but Rust quite rightly points out that the calculated size is infinite (because the size of a TreeNode is the size of two TreeNodes plus 32 bits):

Just as the compiler suggests, we can fix this with a Box:

pub struct TreeNode {
pub value: i32,
pub left: Box<TreeNode>,
pub right: Box<TreeNode>,
}

Now, the size of a TreeNode is the size of two Boxes plus 32 bits, which is entirely reasonable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.200.14