373 lines
23 KiB
HTML
373 lines
23 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>Treating Smart Pointers Like Regular References</title>
|
||
</head>
|
||
<body>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="treating-smart-pointers-like-regular-references-with-the-deref-trait"></a>
|
||
<a id="treating-smart-pointers-like-regular-references-with-deref"></a></p>
|
||
<h2 id="treating-smart-pointers-like-regular-references"><a class="header" href="#treating-smart-pointers-like-regular-references">Treating Smart Pointers Like Regular References</a></h2>
|
||
<p>Implementing the <code>Deref</code> trait allows you to customize the behavior of the
|
||
<em>dereference operator</em> <code>*</code> (not to be confused with the multiplication or glob
|
||
operator). By implementing <code>Deref</code> in such a way that a smart pointer can be
|
||
treated like a regular reference, you can write code that operates on
|
||
references and use that code with smart pointers too.</p>
|
||
<p>Let’s first look at how the dereference operator works with regular references.
|
||
Then, we’ll try to define a custom type that behaves like <code>Box<T></code> and see why
|
||
the dereference operator doesn’t work like a reference on our newly defined
|
||
type. We’ll explore how implementing the <code>Deref</code> trait makes it possible for
|
||
smart pointers to work in ways similar to references. Then, we’ll look at
|
||
Rust’s deref coercion feature and how it lets us work with either references or
|
||
smart pointers.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="following-the-pointer-to-the-value-with-the-dereference-operator"></a>
|
||
<a id="following-the-pointer-to-the-value"></a></p>
|
||
<h3 id="following-the-reference-to-the-value"><a class="header" href="#following-the-reference-to-the-value">Following the Reference to the Value</a></h3>
|
||
<p>A regular reference is a type of pointer, and one way to think of a pointer is
|
||
as an arrow to a value stored somewhere else. In Listing 15-6, we create a
|
||
reference to an <code>i32</code> value and then use the dereference operator to follow the
|
||
reference to the value.</p>
|
||
<figure class="listing" id="listing-15-6">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">fn main() {
|
||
let x = 5;
|
||
let y = &x;
|
||
|
||
assert_eq!(5, x);
|
||
assert_eq!(5, *y);
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-15-6">Listing 15-6</a>: Using the dereference operator to follow a reference to an <code>i32</code> value</figcaption>
|
||
</figure>
|
||
<p>The variable <code>x</code> holds an <code>i32</code> value <code>5</code>. We set <code>y</code> equal to a reference to
|
||
<code>x</code>. We can assert that <code>x</code> is equal to <code>5</code>. However, if we want to make an
|
||
assertion about the value in <code>y</code>, we have to use <code>*y</code> to follow the reference
|
||
to the value it’s pointing to (hence, <em>dereference</em>) so that the compiler can
|
||
compare the actual value. Once we dereference <code>y</code>, we have access to the
|
||
integer value <code>y</code> is pointing to that we can compare with <code>5</code>.</p>
|
||
<p>If we tried to write <code>assert_eq!(5, y);</code> instead, we would get this compilation
|
||
error:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling deref-example v0.1.0 (file:///projects/deref-example)
|
||
error[E0277]: can't compare `{integer}` with `&{integer}`
|
||
--> src/main.rs:6:5
|
||
|
|
||
6 | assert_eq!(5, y);
|
||
| ^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`
|
||
|
|
||
= help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`
|
||
= note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||
|
||
For more information about this error, try `rustc --explain E0277`.
|
||
error: could not compile `deref-example` (bin "deref-example") due to 1 previous error
|
||
</code></pre>
|
||
<p>Comparing a number and a reference to a number isn’t allowed because they’re
|
||
different types. We must use the dereference operator to follow the reference
|
||
to the value it’s pointing to.</p>
|
||
<h3 id="using-boxt-like-a-reference"><a class="header" href="#using-boxt-like-a-reference">Using <code>Box<T></code> Like a Reference</a></h3>
|
||
<p>We can rewrite the code in Listing 15-6 to use a <code>Box<T></code> instead of a
|
||
reference; the dereference operator used on the <code>Box<T></code> in Listing 15-7
|
||
functions in the same way as the dereference operator used on the reference in
|
||
Listing 15-6.</p>
|
||
<figure class="listing" id="listing-15-7">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">fn main() {
|
||
let x = 5;
|
||
let y = Box::new(x);
|
||
|
||
assert_eq!(5, x);
|
||
assert_eq!(5, *y);
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-15-7">Listing 15-7</a>: Using the dereference operator on a <code>Box<i32></code></figcaption>
|
||
</figure>
|
||
<p>The main difference between Listing 15-7 and Listing 15-6 is that here we set
|
||
<code>y</code> to be an instance of a box pointing to a copied value of <code>x</code> rather than a
|
||
reference pointing to the value of <code>x</code>. In the last assertion, we can use the
|
||
dereference operator to follow the box’s pointer in the same way that we did
|
||
when <code>y</code> was a reference. Next, we’ll explore what is special about <code>Box<T></code>
|
||
that enables us to use the dereference operator by defining our own box type.</p>
|
||
<h3 id="defining-our-own-smart-pointer"><a class="header" href="#defining-our-own-smart-pointer">Defining Our Own Smart Pointer</a></h3>
|
||
<p>Let’s build a wrapper type similar to the <code>Box<T></code> type provided by the
|
||
standard library to experience how smart pointer types behave differently from
|
||
references by default. Then, we’ll look at how to add the ability to use the
|
||
dereference operator.</p>
|
||
<section class="note" aria-role="note">
|
||
<p>Note: There’s one big difference between the <code>MyBox<T></code> type we’re about to
|
||
build and the real <code>Box<T></code>: Our version will not store its data on the heap.
|
||
We are focusing this example on <code>Deref</code>, so where the data is actually stored
|
||
is less important than the pointer-like behavior.</p>
|
||
</section>
|
||
<p>The <code>Box<T></code> type is ultimately defined as a tuple struct with one element, so
|
||
Listing 15-8 defines a <code>MyBox<T></code> type in the same way. We’ll also define a
|
||
<code>new</code> function to match the <code>new</code> function defined on <code>Box<T></code>.</p>
|
||
<figure class="listing" id="listing-15-8">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">struct MyBox<T>(T);
|
||
|
||
impl<T> MyBox<T> {
|
||
fn new(x: T) -> MyBox<T> {
|
||
MyBox(x)
|
||
}
|
||
}
|
||
<span class="boring">
|
||
</span><span class="boring">fn main() {}</span></code></pre>
|
||
<figcaption><a href="#listing-15-8">Listing 15-8</a>: Defining a <code>MyBox<T></code> type</figcaption>
|
||
</figure>
|
||
<p>We define a struct named <code>MyBox</code> and declare a generic parameter <code>T</code> because we
|
||
want our type to hold values of any type. The <code>MyBox</code> type is a tuple struct
|
||
with one element of type <code>T</code>. The <code>MyBox::new</code> function takes one parameter of
|
||
type <code>T</code> and returns a <code>MyBox</code> instance that holds the value passed in.</p>
|
||
<p>Let’s try adding the <code>main</code> function in Listing 15-7 to Listing 15-8 and
|
||
changing it to use the <code>MyBox<T></code> type we’ve defined instead of <code>Box<T></code>. The
|
||
code in Listing 15-9 won’t compile, because Rust doesn’t know how to
|
||
dereference <code>MyBox</code>.</p>
|
||
<figure class="listing" id="listing-15-9">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore does_not_compile"><span class="boring">struct MyBox<T>(T);
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl<T> MyBox<T> {
|
||
</span><span class="boring"> fn new(x: T) -> MyBox<T> {
|
||
</span><span class="boring"> MyBox(x)
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
let x = 5;
|
||
let y = MyBox::new(x);
|
||
|
||
assert_eq!(5, x);
|
||
assert_eq!(5, *y);
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-15-9">Listing 15-9</a>: Attempting to use <code>MyBox<T></code> in the same way we used references and <code>Box<T></code></figcaption>
|
||
</figure>
|
||
<p>Here’s the resultant compilation error:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling deref-example v0.1.0 (file:///projects/deref-example)
|
||
error[E0614]: type `MyBox<{integer}>` cannot be dereferenced
|
||
--> src/main.rs:14:19
|
||
|
|
||
14 | assert_eq!(5, *y);
|
||
| ^^ can't be dereferenced
|
||
|
||
For more information about this error, try `rustc --explain E0614`.
|
||
error: could not compile `deref-example` (bin "deref-example") due to 1 previous error
|
||
</code></pre>
|
||
<p>Our <code>MyBox<T></code> type can’t be dereferenced because we haven’t implemented that
|
||
ability on our type. To enable dereferencing with the <code>*</code> operator, we
|
||
implement the <code>Deref</code> trait.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="treating-a-type-like-a-reference-by-implementing-the-deref-trait"></a></p>
|
||
<h3 id="implementing-the-deref-trait"><a class="header" href="#implementing-the-deref-trait">Implementing the <code>Deref</code> Trait</a></h3>
|
||
<p>As discussed in <a href="../ch10/ch10-02-traits.html#implementing-a-trait-on-a-type">“Implementing a Trait on a Type”</a><!-- ignore --> in
|
||
Chapter 10, to implement a trait we need to provide implementations for the
|
||
trait’s required methods. The <code>Deref</code> trait, provided by the standard library,
|
||
requires us to implement one method named <code>deref</code> that borrows <code>self</code> and
|
||
returns a reference to the inner data. Listing 15-10 contains an implementation
|
||
of <code>Deref</code> to add to the definition of <code>MyBox<T></code>.</p>
|
||
<figure class="listing" id="listing-15-10">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">use std::ops::Deref;
|
||
|
||
impl<T> Deref for MyBox<T> {
|
||
type Target = T;
|
||
|
||
fn deref(&self) -> &Self::Target {
|
||
&self.0
|
||
}
|
||
}
|
||
<span class="boring">
|
||
</span><span class="boring">struct MyBox<T>(T);
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl<T> MyBox<T> {
|
||
</span><span class="boring"> fn new(x: T) -> MyBox<T> {
|
||
</span><span class="boring"> MyBox(x)
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">fn main() {
|
||
</span><span class="boring"> let x = 5;
|
||
</span><span class="boring"> let y = MyBox::new(x);
|
||
</span><span class="boring">
|
||
</span><span class="boring"> assert_eq!(5, x);
|
||
</span><span class="boring"> assert_eq!(5, *y);
|
||
</span><span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-15-10">Listing 15-10</a>: Implementing <code>Deref</code> on <code>MyBox<T></code></figcaption>
|
||
</figure>
|
||
<p>The <code>type Target = T;</code> syntax defines an associated type for the <code>Deref</code> trait
|
||
to use. Associated types are a slightly different way of declaring a generic
|
||
parameter, but you don’t need to worry about them for now; we’ll cover them in
|
||
more detail in Chapter 20.</p>
|
||
<p>We fill in the body of the <code>deref</code> method with <code>&self.0</code> so that <code>deref</code>
|
||
returns a reference to the value we want to access with the <code>*</code> operator;
|
||
recall from <a href="../ch05/ch05-01-defining-structs.html#creating-different-types-with-tuple-structs">“Creating Different Types with Tuple Structs”</a><!--
|
||
ignore --> in Chapter 5 that <code>.0</code> accesses the first value in a tuple struct.
|
||
The <code>main</code> function in Listing 15-9 that calls <code>*</code> on the <code>MyBox<T></code> value now
|
||
compiles, and the assertions pass!</p>
|
||
<p>Without the <code>Deref</code> trait, the compiler can only dereference <code>&</code> references.
|
||
The <code>deref</code> method gives the compiler the ability to take a value of any type
|
||
that implements <code>Deref</code> and call the <code>deref</code> method to get a reference that
|
||
it knows how to dereference.</p>
|
||
<p>When we entered <code>*y</code> in Listing 15-9, behind the scenes Rust actually ran this
|
||
code:</p>
|
||
<pre><code class="language-rust ignore">*(y.deref())</code></pre>
|
||
<p>Rust substitutes the <code>*</code> operator with a call to the <code>deref</code> method and then a
|
||
plain dereference so that we don’t have to think about whether or not we need
|
||
to call the <code>deref</code> method. This Rust feature lets us write code that functions
|
||
identically whether we have a regular reference or a type that implements
|
||
<code>Deref</code>.</p>
|
||
<p>The reason the <code>deref</code> method returns a reference to a value, and that the
|
||
plain dereference outside the parentheses in <code>*(y.deref())</code> is still necessary,
|
||
has to do with the ownership system. If the <code>deref</code> method returned the value
|
||
directly instead of a reference to the value, the value would be moved out of
|
||
<code>self</code>. We don’t want to take ownership of the inner value inside <code>MyBox<T></code> in
|
||
this case or in most cases where we use the dereference operator.</p>
|
||
<p>Note that the <code>*</code> operator is replaced with a call to the <code>deref</code> method and
|
||
then a call to the <code>*</code> operator just once, each time we use a <code>*</code> in our code.
|
||
Because the substitution of the <code>*</code> operator does not recurse infinitely, we
|
||
end up with data of type <code>i32</code>, which matches the <code>5</code> in <code>assert_eq!</code> in
|
||
Listing 15-9.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="implicit-deref-coercions-with-functions-and-methods"></a>
|
||
<a id="using-deref-coercions-in-functions-and-methods"></a></p>
|
||
<h3 id="using-deref-coercion-in-functions-and-methods"><a class="header" href="#using-deref-coercion-in-functions-and-methods">Using Deref Coercion in Functions and Methods</a></h3>
|
||
<p><em>Deref coercion</em> converts a reference to a type that implements the <code>Deref</code>
|
||
trait into a reference to another type. For example, deref coercion can convert
|
||
<code>&String</code> to <code>&str</code> because <code>String</code> implements the <code>Deref</code> trait such that it
|
||
returns <code>&str</code>. Deref coercion is a convenience Rust performs on arguments to
|
||
functions and methods, and it works only on types that implement the <code>Deref</code>
|
||
trait. It happens automatically when we pass a reference to a particular type’s
|
||
value as an argument to a function or method that doesn’t match the parameter
|
||
type in the function or method definition. A sequence of calls to the <code>deref</code>
|
||
method converts the type we provided into the type the parameter needs.</p>
|
||
<p>Deref coercion was added to Rust so that programmers writing function and
|
||
method calls don’t need to add as many explicit references and dereferences
|
||
with <code>&</code> and <code>*</code>. The deref coercion feature also lets us write more code that
|
||
can work for either references or smart pointers.</p>
|
||
<p>To see deref coercion in action, let’s use the <code>MyBox<T></code> type we defined in
|
||
Listing 15-8 as well as the implementation of <code>Deref</code> that we added in Listing
|
||
15-10. Listing 15-11 shows the definition of a function that has a string slice
|
||
parameter.</p>
|
||
<figure class="listing" id="listing-15-11">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">fn hello(name: &str) {
|
||
println!("Hello, {name}!");
|
||
}
|
||
<span class="boring">
|
||
</span><span class="boring">fn main() {}</span></code></pre>
|
||
<figcaption><a href="#listing-15-11">Listing 15-11</a>: A <code>hello</code> function that has the parameter <code>name</code> of type <code>&str</code></figcaption>
|
||
</figure>
|
||
<p>We can call the <code>hello</code> function with a string slice as an argument, such as
|
||
<code>hello("Rust");</code>, for example. Deref coercion makes it possible to call <code>hello</code>
|
||
with a reference to a value of type <code>MyBox<String></code>, as shown in Listing 15-12.</p>
|
||
<figure class="listing" id="listing-15-12">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">use std::ops::Deref;
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl<T> Deref for MyBox<T> {
|
||
</span><span class="boring"> type Target = T;
|
||
</span><span class="boring">
|
||
</span><span class="boring"> fn deref(&self) -> &T {
|
||
</span><span class="boring"> &self.0
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct MyBox<T>(T);
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl<T> MyBox<T> {
|
||
</span><span class="boring"> fn new(x: T) -> MyBox<T> {
|
||
</span><span class="boring"> MyBox(x)
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">fn hello(name: &str) {
|
||
</span><span class="boring"> println!("Hello, {name}!");
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
let m = MyBox::new(String::from("Rust"));
|
||
hello(&m);
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-15-12">Listing 15-12</a>: Calling <code>hello</code> with a reference to a <code>MyBox<String></code> value, which works because of deref coercion</figcaption>
|
||
</figure>
|
||
<p>Here we’re calling the <code>hello</code> function with the argument <code>&m</code>, which is a
|
||
reference to a <code>MyBox<String></code> value. Because we implemented the <code>Deref</code> trait
|
||
on <code>MyBox<T></code> in Listing 15-10, Rust can turn <code>&MyBox<String></code> into <code>&String</code>
|
||
by calling <code>deref</code>. The standard library provides an implementation of <code>Deref</code>
|
||
on <code>String</code> that returns a string slice, and this is in the API documentation
|
||
for <code>Deref</code>. Rust calls <code>deref</code> again to turn the <code>&String</code> into <code>&str</code>, which
|
||
matches the <code>hello</code> function’s definition.</p>
|
||
<p>If Rust didn’t implement deref coercion, we would have to write the code in
|
||
Listing 15-13 instead of the code in Listing 15-12 to call <code>hello</code> with a value
|
||
of type <code>&MyBox<String></code>.</p>
|
||
<figure class="listing" id="listing-15-13">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">use std::ops::Deref;
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl<T> Deref for MyBox<T> {
|
||
</span><span class="boring"> type Target = T;
|
||
</span><span class="boring">
|
||
</span><span class="boring"> fn deref(&self) -> &T {
|
||
</span><span class="boring"> &self.0
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct MyBox<T>(T);
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl<T> MyBox<T> {
|
||
</span><span class="boring"> fn new(x: T) -> MyBox<T> {
|
||
</span><span class="boring"> MyBox(x)
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">fn hello(name: &str) {
|
||
</span><span class="boring"> println!("Hello, {name}!");
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
let m = MyBox::new(String::from("Rust"));
|
||
hello(&(*m)[..]);
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-15-13">Listing 15-13</a>: The code we would have to write if Rust didn’t have deref coercion</figcaption>
|
||
</figure>
|
||
<p>The <code>(*m)</code> dereferences the <code>MyBox<String></code> into a <code>String</code>. Then, the <code>&</code> and
|
||
<code>[..]</code> take a string slice of the <code>String</code> that is equal to the whole string to
|
||
match the signature of <code>hello</code>. This code without deref coercions is harder to
|
||
read, write, and understand with all of these symbols involved. Deref coercion
|
||
allows Rust to handle these conversions for us automatically.</p>
|
||
<p>When the <code>Deref</code> trait is defined for the types involved, Rust will analyze the
|
||
types and use <code>Deref::deref</code> as many times as necessary to get a reference to
|
||
match the parameter’s type. The number of times that <code>Deref::deref</code> needs to be
|
||
inserted is resolved at compile time, so there is no runtime penalty for taking
|
||
advantage of deref coercion!</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="how-deref-coercion-interacts-with-mutability"></a></p>
|
||
<h3 id="handling-deref-coercion-with-mutable-references"><a class="header" href="#handling-deref-coercion-with-mutable-references">Handling Deref Coercion with Mutable References</a></h3>
|
||
<p>Similar to how you use the <code>Deref</code> trait to override the <code>*</code> operator on
|
||
immutable references, you can use the <code>DerefMut</code> trait to override the <code>*</code>
|
||
operator on mutable references.</p>
|
||
<p>Rust does deref coercion when it finds types and trait implementations in three
|
||
cases:</p>
|
||
<ol>
|
||
<li>From <code>&T</code> to <code>&U</code> when <code>T: Deref<Target=U></code></li>
|
||
<li>From <code>&mut T</code> to <code>&mut U</code> when <code>T: DerefMut<Target=U></code></li>
|
||
<li>From <code>&mut T</code> to <code>&U</code> when <code>T: Deref<Target=U></code></li>
|
||
</ol>
|
||
<p>The first two cases are the same except that the second implements mutability.
|
||
The first case states that if you have a <code>&T</code>, and <code>T</code> implements <code>Deref</code> to
|
||
some type <code>U</code>, you can get a <code>&U</code> transparently. The second case states that
|
||
the same deref coercion happens for mutable references.</p>
|
||
<p>The third case is trickier: Rust will also coerce a mutable reference to an
|
||
immutable one. But the reverse is <em>not</em> possible: Immutable references will
|
||
never coerce to mutable references. Because of the borrowing rules, if you have
|
||
a mutable reference, that mutable reference must be the only reference to that
|
||
data (otherwise, the program wouldn’t compile). Converting one mutable
|
||
reference to one immutable reference will never break the borrowing rules.
|
||
Converting an immutable reference to a mutable reference would require that the
|
||
initial immutable reference is the only immutable reference to that data, but
|
||
the borrowing rules don’t guarantee that. Therefore, Rust can’t make the
|
||
assumption that converting an immutable reference to a mutable reference is
|
||
possible.</p>
|
||
</body>
|
||
</html>
|