Files
docs-rust/ch15/ch15-01-box.html
2026-06-22 21:27:36 +05:30

269 lines
17 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Using Box&lt;T&gt; to Point to Data on the Heap</title>
</head>
<body>
<h2 id="using-boxt-to-point-to-data-on-the-heap"><a class="header" href="#using-boxt-to-point-to-data-on-the-heap">Using <code>Box&lt;T&gt;</code> to Point to Data on the Heap</a></h2>
<p>The most straightforward smart pointer is a box, whose type is written
<code>Box&lt;T&gt;</code>. <em>Boxes</em> allow you to store data on the heap rather than the stack.
What remains on the stack is the pointer to the heap data. Refer to Chapter 4
to review the difference between the stack and the heap.</p>
<p>Boxes dont have performance overhead, other than storing their data on the
heap instead of on the stack. But they dont have many extra capabilities
either. Youll use them most often in these situations:</p>
<ul>
<li>When you have a type whose size cant be known at compile time, and you want
to use a value of that type in a context that requires an exact size</li>
<li>When you have a large amount of data, and you want to transfer ownership but
ensure that the data wont be copied when you do so</li>
<li>When you want to own a value, and you care only that its a type that
implements a particular trait rather than being of a specific type</li>
</ul>
<p>Well demonstrate the first situation in <a href="#enabling-recursive-types-with-boxes">“Enabling Recursive Types with
Boxes”</a><!-- ignore -->. In the second
case, transferring ownership of a large amount of data can take a long time
because the data is copied around on the stack. To improve performance in this
situation, we can store the large amount of data on the heap in a box. Then,
only the small amount of pointer data is copied around on the stack, while the
data it references stays in one place on the heap. The third case is known as a
<em>trait object</em>, and <a href="../ch18/ch18-02-trait-objects.html#using-trait-objects-to-abstract-over-shared-behavior">“Using Trait Objects to Abstract over Shared
Behavior”</a><!-- ignore --> in Chapter 18 is devoted to that
topic. So, what you learn here youll apply again in that section!</p>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="using-boxt-to-store-data-on-the-heap"></a></p>
<h3 id="storing-data-on-the-heap"><a class="header" href="#storing-data-on-the-heap">Storing Data on the Heap</a></h3>
<p>Before we discuss the heap storage use case for <code>Box&lt;T&gt;</code>, well cover the
syntax and how to interact with values stored within a <code>Box&lt;T&gt;</code>.</p>
<p>Listing 15-1 shows how to use a box to store an <code>i32</code> value on the heap.</p>
<figure class="listing" id="listing-15-1">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">fn main() {
let b = Box::new(5);
println!("b = {b}");
}</code></pre>
<figcaption><a href="#listing-15-1">Listing 15-1</a>: Storing an <code>i32</code> value on the heap using a box</figcaption>
</figure>
<p>We define the variable <code>b</code> to have the value of a <code>Box</code> that points to the
value <code>5</code>, which is allocated on the heap. This program will print <code>b = 5</code>; in
this case, we can access the data in the box similarly to how we would if this
data were on the stack. Just like any owned value, when a box goes out of
scope, as <code>b</code> does at the end of <code>main</code>, it will be deallocated. The
deallocation happens both for the box (stored on the stack) and the data it
points to (stored on the heap).</p>
<p>Putting a single value on the heap isnt very useful, so you wont use boxes by
themselves in this way very often. Having values like a single <code>i32</code> on the
stack, where theyre stored by default, is more appropriate in the majority of
situations. Lets look at a case where boxes allow us to define types that we
wouldnt be allowed to define if we didnt have boxes.</p>
<h3 id="enabling-recursive-types-with-boxes"><a class="header" href="#enabling-recursive-types-with-boxes">Enabling Recursive Types with Boxes</a></h3>
<p>A value of a <em>recursive type</em> can have another value of the same type as part of
itself. Recursive types pose an issue because Rust needs to know at compile time
how much space a type takes up. However, the nesting of values of recursive
types could theoretically continue infinitely, so Rust cant know how much space
the value needs. Because boxes have a known size, we can enable recursive types
by inserting a box in the recursive type definition.</p>
<p>As an example of a recursive type, lets explore the cons list. This is a data
type commonly found in functional programming languages. The cons list type
well define is straightforward except for the recursion; therefore, the
concepts in the example well work with will be useful anytime you get into
more complex situations involving recursive types.</p>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="more-information-about-the-cons-list"></a></p>
<h4 id="understanding-the-cons-list"><a class="header" href="#understanding-the-cons-list">Understanding the Cons List</a></h4>
<p>A <em>cons list</em> is a data structure that comes from the Lisp programming language
and its dialects, is made up of nested pairs, and is the Lisp version of a
linked list. Its name comes from the <code>cons</code> function (short for <em>construct
function</em>) in Lisp that constructs a new pair from its two arguments. By
calling <code>cons</code> on a pair consisting of a value and another pair, we can
construct cons lists made up of recursive pairs.</p>
<p>For example, heres a pseudocode representation of a cons list containing the
list <code>1, 2, 3</code> with each pair in parentheses:</p>
<pre><code class="language-text">(1, (2, (3, Nil)))
</code></pre>
<p>Each item in a cons list contains two elements: the value of the current item
and of the next item. The last item in the list contains only a value called
<code>Nil</code> without a next item. A cons list is produced by recursively calling the
<code>cons</code> function. The canonical name to denote the base case of the recursion is
<code>Nil</code>. Note that this is not the same as the “null” or “nil” concept discussed
in Chapter 6, which is an invalid or absent value.</p>
<p>The cons list isnt a commonly used data structure in Rust. Most of the time
when you have a list of items in Rust, <code>Vec&lt;T&gt;</code> is a better choice to use.
Other, more complex recursive data types <em>are</em> useful in various situations,
but by starting with the cons list in this chapter, we can explore how boxes
let us define a recursive data type without much distraction.</p>
<p>Listing 15-2 contains an enum definition for a cons list. Note that this code
wont compile yet, because the <code>List</code> type doesnt have a known size, which
well demonstrate.</p>
<figure class="listing" id="listing-15-2">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore does_not_compile">enum List {
Cons(i32, List),
Nil,
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<figcaption><a href="#listing-15-2">Listing 15-2</a>: The first attempt at defining an enum to represent a cons list data structure of <code>i32</code> values</figcaption>
</figure>
<section class="note" aria-role="note">
<p>Note: Were implementing a cons list that holds only <code>i32</code> values for the
purposes of this example. We could have implemented it using generics, as we
discussed in Chapter 10, to define a cons list type that could store values of
any type.</p>
</section>
<p>Using the <code>List</code> type to store the list <code>1, 2, 3</code> would look like the code in
Listing 15-3.</p>
<figure class="listing" id="listing-15-3">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">enum List {
</span><span class="boring"> Cons(i32, List),
</span><span class="boring"> Nil,
</span><span class="boring">}
</span><span class="boring">
</span>// --snip--
use crate::List::{Cons, Nil};
fn main() {
let list = Cons(1, Cons(2, Cons(3, Nil)));
}</code></pre>
<figcaption><a href="#listing-15-3">Listing 15-3</a>: Using the <code>List</code> enum to store the list <code>1, 2, 3</code></figcaption>
</figure>
<p>The first <code>Cons</code> value holds <code>1</code> and another <code>List</code> value. This <code>List</code> value is
another <code>Cons</code> value that holds <code>2</code> and another <code>List</code> value. This <code>List</code> value
is one more <code>Cons</code> value that holds <code>3</code> and a <code>List</code> value, which is finally
<code>Nil</code>, the non-recursive variant that signals the end of the list.</p>
<p>If we try to compile the code in Listing 15-3, we get the error shown in
Listing 15-4.</p>
<figure class="listing" id="listing-15-4">
<pre><code class="language-console">$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0072]: recursive type `List` has infinite size
--&gt; src/main.rs:1:1
|
1 | enum List {
| ^^^^^^^^^
2 | Cons(i32, List),
| ---- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&amp;`) to break the cycle
|
2 | Cons(i32, Box&lt;List&gt;),
| ++++ +
error[E0391]: cycle detected when computing when `List` needs drop
--&gt; src/main.rs:1:1
|
1 | enum List {
| ^^^^^^^^^
|
= note: ...which immediately requires computing when `List` needs drop again
= note: cycle used when computing whether `List` needs drop
= note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information
Some errors have detailed explanations: E0072, E0391.
For more information about an error, try `rustc --explain E0072`.
error: could not compile `cons-list` (bin "cons-list") due to 2 previous errors
</code></pre>
<figcaption><a href="#listing-15-4">Listing 15-4</a>: The error we get when attempting to define a recursive enum</figcaption>
</figure>
<p>The error shows this type “has infinite size.” The reason is that weve defined
<code>List</code> with a variant that is recursive: It holds another value of itself
directly. As a result, Rust cant figure out how much space it needs to store a
<code>List</code> value. Lets break down why we get this error. First, well look at how
Rust decides how much space it needs to store a value of a non-recursive type.</p>
<h4 id="computing-the-size-of-a-non-recursive-type"><a class="header" href="#computing-the-size-of-a-non-recursive-type">Computing the Size of a Non-Recursive Type</a></h4>
<p>Recall the <code>Message</code> enum we defined in Listing 6-2 when we discussed enum
definitions in Chapter 6:</p>
<pre class="playground"><code class="language-rust edition2024">enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p>To determine how much space to allocate for a <code>Message</code> value, Rust goes
through each of the variants to see which variant needs the most space. Rust
sees that <code>Message::Quit</code> doesnt need any space, <code>Message::Move</code> needs enough
space to store two <code>i32</code> values, and so forth. Because only one variant will be
used, the most space a <code>Message</code> value will need is the space it would take to
store the largest of its variants.</p>
<p>Contrast this with what happens when Rust tries to determine how much space a
recursive type like the <code>List</code> enum in Listing 15-2 needs. The compiler starts
by looking at the <code>Cons</code> variant, which holds a value of type <code>i32</code> and a value
of type <code>List</code>. Therefore, <code>Cons</code> needs an amount of space equal to the size of
an <code>i32</code> plus the size of a <code>List</code>. To figure out how much memory the <code>List</code>
type needs, the compiler looks at the variants, starting with the <code>Cons</code>
variant. The <code>Cons</code> variant holds a value of type <code>i32</code> and a value of type
<code>List</code>, and this process continues infinitely, as shown in Figure 15-1.</p>
<img alt="An infinite Cons list: a rectangle labeled &#39;Cons&#39; split into two smaller rectangles. The first smaller rectangle holds the label &#39;i32&#39;, and the second smaller rectangle holds the label &#39;Cons&#39; and a smaller version of the outer &#39;Cons&#39; rectangle. The &#39;Cons&#39; rectangles continue to hold smaller and smaller versions of themselves until the smallest comfortably sized rectangle holds an infinity symbol, indicating that this repetition goes on forever." src="../img/trpl15-01.svg" class="center" style="width: 50%;" />
<p><span class="caption">Figure 15-1: An infinite <code>List</code> consisting of infinite
<code>Cons</code> variants</span></p>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="using-boxt-to-get-a-recursive-type-with-a-known-size"></a></p>
<h4 id="getting-a-recursive-type-with-a-known-size"><a class="header" href="#getting-a-recursive-type-with-a-known-size">Getting a Recursive Type with a Known Size</a></h4>
<p>Because Rust cant figure out how much space to allocate for recursively
defined types, the compiler gives an error with this helpful suggestion:</p>
<!-- manual-regeneration
after doing automatic regeneration, look at listings/ch15-smart-pointers/listing-15-03/output.txt and copy the relevant line
-->
<pre><code class="language-text">help: insert some indirection (e.g., a `Box`, `Rc`, or `&amp;`) to break the cycle
|
2 | Cons(i32, Box&lt;List&gt;),
| ++++ +
</code></pre>
<p>In this suggestion, <em>indirection</em> means that instead of storing a value
directly, we should change the data structure to store the value indirectly by
storing a pointer to the value instead.</p>
<p>Because a <code>Box&lt;T&gt;</code> is a pointer, Rust always knows how much space a <code>Box&lt;T&gt;</code>
needs: A pointers size doesnt change based on the amount of data its
pointing to. This means we can put a <code>Box&lt;T&gt;</code> inside the <code>Cons</code> variant instead
of another <code>List</code> value directly. The <code>Box&lt;T&gt;</code> will point to the next <code>List</code>
value that will be on the heap rather than inside the <code>Cons</code> variant.
Conceptually, we still have a list, created with lists holding other lists, but
this implementation is now more like placing the items next to one another
rather than inside one another.</p>
<p>We can change the definition of the <code>List</code> enum in Listing 15-2 and the usage
of the <code>List</code> in Listing 15-3 to the code in Listing 15-5, which will compile.</p>
<figure class="listing" id="listing-15-5">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">enum List {
Cons(i32, Box&lt;List&gt;),
Nil,
}
use crate::List::{Cons, Nil};
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
}</code></pre>
<figcaption><a href="#listing-15-5">Listing 15-5</a>: The definition of <code>List</code> that uses <code>Box&lt;T&gt;</code> in order to have a known size</figcaption>
</figure>
<p>The <code>Cons</code> variant needs the size of an <code>i32</code> plus the space to store the boxs
pointer data. The <code>Nil</code> variant stores no values, so it needs less space on the
stack than the <code>Cons</code> variant. We now know that any <code>List</code> value will take up
the size of an <code>i32</code> plus the size of a boxs pointer data. By using a box,
weve broken the infinite, recursive chain, so the compiler can figure out the
size it needs to store a <code>List</code> value. Figure 15-2 shows what the <code>Cons</code>
variant looks like now.</p>
<img alt="A rectangle labeled &#39;Cons&#39; split into two smaller rectangles. The first smaller rectangle holds the label &#39;i32&#39;, and the second smaller rectangle holds the label &#39;Box&#39; with one inner rectangle that contains the label &#39;usize&#39;, representing the finite size of the box&#39;s pointer." src="../img/trpl15-02.svg" class="center" />
<p><span class="caption">Figure 15-2: A <code>List</code> that is not infinitely sized,
because <code>Cons</code> holds a <code>Box</code></span></p>
<p>Boxes provide only the indirection and heap allocation; they dont have any
other special capabilities, like those well see with the other smart pointer
types. They also dont have the performance overhead that these special
capabilities incur, so they can be useful in cases like the cons list where the
indirection is the only feature we need. Well look at more use cases for boxes
in Chapter 18.</p>
<p>The <code>Box&lt;T&gt;</code> type is a smart pointer because it implements the <code>Deref</code> trait,
which allows <code>Box&lt;T&gt;</code> values to be treated like references. When a <code>Box&lt;T&gt;</code>
value goes out of scope, the heap data that the box is pointing to is cleaned
up as well because of the <code>Drop</code> trait implementation. These two traits will be
even more important to the functionality provided by the other smart pointer
types well discuss in the rest of this chapter. Lets explore these two traits
in more detail.</p>
</body>
</html>