Files
docs-rust/ch18/ch18-02-trait-objects.html
2026-06-22 21:27:36 +05:30

340 lines
20 KiB
HTML
Raw 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 Trait Objects to Abstract over Shared Behavior</title>
</head>
<body>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="using-trait-objects-that-allow-for-values-of-different-types"></a></p>
<h2 id="using-trait-objects-to-abstract-over-shared-behavior"><a class="header" href="#using-trait-objects-to-abstract-over-shared-behavior">Using Trait Objects to Abstract over Shared Behavior</a></h2>
<p>In Chapter 8, we mentioned that one limitation of vectors is that they can
store elements of only one type. We created a workaround in Listing 8-9 where
we defined a <code>SpreadsheetCell</code> enum that had variants to hold integers, floats,
and text. This meant we could store different types of data in each cell and
still have a vector that represented a row of cells. This is a perfectly good
solution when our interchangeable items are a fixed set of types that we know
when our code is compiled.</p>
<p>However, sometimes we want our library user to be able to extend the set of
types that are valid in a particular situation. To show how we might achieve
this, well create an example graphical user interface (GUI) tool that iterates
through a list of items, calling a <code>draw</code> method on each one to draw it to the
screen—a common technique for GUI tools. Well create a library crate called
<code>gui</code> that contains the structure of a GUI library. This crate might include
some types for people to use, such as <code>Button</code> or <code>TextField</code>. In addition,
<code>gui</code> users will want to create their own types that can be drawn: For
instance, one programmer might add an <code>Image</code>, and another might add a
<code>SelectBox</code>.</p>
<p>At the time of writing the library, we cant know and define all the types
other programmers might want to create. But we do know that <code>gui</code> needs to keep
track of many values of different types, and it needs to call a <code>draw</code> method
on each of these differently typed values. It doesnt need to know exactly what
will happen when we call the <code>draw</code> method, just that the value will have that
method available for us to call.</p>
<p>To do this in a language with inheritance, we might define a class named
<code>Component</code> that has a method named <code>draw</code> on it. The other classes, such as
<code>Button</code>, <code>Image</code>, and <code>SelectBox</code>, would inherit from <code>Component</code> and thus
inherit the <code>draw</code> method. They could each override the <code>draw</code> method to define
their custom behavior, but the framework could treat all of the types as if
they were <code>Component</code> instances and call <code>draw</code> on them. But because Rust
doesnt have inheritance, we need another way to structure the <code>gui</code> library to
allow users to create new types compatible with the library.</p>
<h3 id="defining-a-trait-for-common-behavior"><a class="header" href="#defining-a-trait-for-common-behavior">Defining a Trait for Common Behavior</a></h3>
<p>To implement the behavior that we want <code>gui</code> to have, well define a trait
named <code>Draw</code> that will have one method named <code>draw</code>. Then, we can define a
vector that takes a trait object. A <em>trait object</em> points to both an instance
of a type implementing our specified trait and a table used to look up trait
methods on that type at runtime. We create a trait object by specifying some
sort of pointer, such as a reference or a <code>Box&lt;T&gt;</code> smart pointer, then the
<code>dyn</code> keyword, and then specifying the relevant trait. (Well talk about the
reason trait objects must use a pointer in <a href="../ch20/ch20-03-advanced-types.html#dynamically-sized-types-and-the-sized-trait">“Dynamically Sized Types and the
<code>Sized</code> Trait”</a><!-- ignore --> in Chapter 20.) We can use
trait objects in place of a generic or concrete type. Wherever we use a trait
object, Rusts type system will ensure at compile time that any value used in
that context will implement the trait objects trait. Consequently, we dont
need to know all the possible types at compile time.</p>
<p>Weve mentioned that, in Rust, we refrain from calling structs and enums
“objects” to distinguish them from other languages objects. In a struct or
enum, the data in the struct fields and the behavior in <code>impl</code> blocks are
separated, whereas in other languages, the data and behavior combined into one
concept is often labeled an object. Trait objects differ from objects in other
languages in that we cant add data to a trait object. Trait objects arent as
generally useful as objects in other languages: Their specific purpose is to
allow abstraction across common behavior.</p>
<p>Listing 18-3 shows how to define a trait named <code>Draw</code> with one method named
<code>draw</code>.</p>
<figure class="listing" id="listing-18-3">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust noplayground">pub trait Draw {
fn draw(&amp;self);
}</code></pre>
<figcaption><a href="#listing-18-3">Listing 18-3</a>: Definition of the <code>Draw</code> trait</figcaption>
</figure>
<p>This syntax should look familiar from our discussions on how to define traits
in Chapter 10. Next comes some new syntax: Listing 18-4 defines a struct named
<code>Screen</code> that holds a vector named <code>components</code>. This vector is of type
<code>Box&lt;dyn Draw&gt;</code>, which is a trait object; its a stand-in for any type inside a
<code>Box</code> that implements the <code>Draw</code> trait.</p>
<figure class="listing" id="listing-18-4">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Draw {
</span><span class="boring"> fn draw(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span>pub struct Screen {
pub components: Vec&lt;Box&lt;dyn Draw&gt;&gt;,
}</code></pre>
<figcaption><a href="#listing-18-4">Listing 18-4</a>: Definition of the <code>Screen</code> struct with a <code>components</code> field holding a vector of trait objects that implement the <code>Draw</code> trait</figcaption>
</figure>
<p>On the <code>Screen</code> struct, well define a method named <code>run</code> that will call the
<code>draw</code> method on each of its <code>components</code>, as shown in Listing 18-5.</p>
<figure class="listing" id="listing-18-5">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Draw {
</span><span class="boring"> fn draw(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct Screen {
</span><span class="boring"> pub components: Vec&lt;Box&lt;dyn Draw&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>impl Screen {
pub fn run(&amp;self) {
for component in self.components.iter() {
component.draw();
}
}
}</code></pre>
<figcaption><a href="#listing-18-5">Listing 18-5</a>: A <code>run</code> method on <code>Screen</code> that calls the <code>draw</code> method on each component</figcaption>
</figure>
<p>This works differently from defining a struct that uses a generic type
parameter with trait bounds. A generic type parameter can be substituted with
only one concrete type at a time, whereas trait objects allow for multiple
concrete types to fill in for the trait object at runtime. For example, we
could have defined the <code>Screen</code> struct using a generic type and a trait bound,
as in Listing 18-6.</p>
<figure class="listing" id="listing-18-6">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Draw {
</span><span class="boring"> fn draw(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span>pub struct Screen&lt;T: Draw&gt; {
pub components: Vec&lt;T&gt;,
}
impl&lt;T&gt; Screen&lt;T&gt;
where
T: Draw,
{
pub fn run(&amp;self) {
for component in self.components.iter() {
component.draw();
}
}
}</code></pre>
<figcaption><a href="#listing-18-6">Listing 18-6</a>: An alternate implementation of the <code>Screen</code> struct and its <code>run</code> method using generics and trait bounds</figcaption>
</figure>
<p>This restricts us to a <code>Screen</code> instance that has a list of components all of
type <code>Button</code> or all of type <code>TextField</code>. If youll only ever have homogeneous
collections, using generics and trait bounds is preferable because the
definitions will be monomorphized at compile time to use the concrete types.</p>
<p>On the other hand, with the method using trait objects, one <code>Screen</code> instance
can hold a <code>Vec&lt;T&gt;</code> that contains a <code>Box&lt;Button&gt;</code> as well as a
<code>Box&lt;TextField&gt;</code>. Lets look at how this works, and then well talk about the
runtime performance implications.</p>
<h3 id="implementing-the-trait"><a class="header" href="#implementing-the-trait">Implementing the Trait</a></h3>
<p>Now well add some types that implement the <code>Draw</code> trait. Well provide the
<code>Button</code> type. Again, actually implementing a GUI library is beyond the scope
of this book, so the <code>draw</code> method wont have any useful implementation in its
body. To imagine what the implementation might look like, a <code>Button</code> struct
might have fields for <code>width</code>, <code>height</code>, and <code>label</code>, as shown in Listing 18-7.</p>
<figure class="listing" id="listing-18-7">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Draw {
</span><span class="boring"> fn draw(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct Screen {
</span><span class="boring"> pub components: Vec&lt;Box&lt;dyn Draw&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Screen {
</span><span class="boring"> pub fn run(&amp;self) {
</span><span class="boring"> for component in self.components.iter() {
</span><span class="boring"> component.draw();
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>pub struct Button {
pub width: u32,
pub height: u32,
pub label: String,
}
impl Draw for Button {
fn draw(&amp;self) {
// code to actually draw a button
}
}</code></pre>
<figcaption><a href="#listing-18-7">Listing 18-7</a>: A <code>Button</code> struct that implements the <code>Draw</code> trait</figcaption>
</figure>
<p>The <code>width</code>, <code>height</code>, and <code>label</code> fields on <code>Button</code> will differ from the
fields on other components; for example, a <code>TextField</code> type might have those
same fields plus a <code>placeholder</code> field. Each of the types we want to draw on
the screen will implement the <code>Draw</code> trait but will use different code in the
<code>draw</code> method to define how to draw that particular type, as <code>Button</code> has here
(without the actual GUI code, as mentioned). The <code>Button</code> type, for instance,
might have an additional <code>impl</code> block containing methods related to what
happens when a user clicks the button. These kinds of methods wont apply to
types like <code>TextField</code>.</p>
<p>If someone using our library decides to implement a <code>SelectBox</code> struct that has
<code>width</code>, <code>height</code>, and <code>options</code> fields, they would implement the <code>Draw</code> trait
on the <code>SelectBox</code> type as well, as shown in Listing 18-8.</p>
<figure class="listing" id="listing-18-8">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore">use gui::Draw;
struct SelectBox {
width: u32,
height: u32,
options: Vec&lt;String&gt;,
}
impl Draw for SelectBox {
fn draw(&amp;self) {
// code to actually draw a select box
}
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<figcaption><a href="#listing-18-8">Listing 18-8</a>: Another crate using <code>gui</code> and implementing the <code>Draw</code> trait on a <code>SelectBox</code> struct</figcaption>
</figure>
<p>Our librarys user can now write their <code>main</code> function to create a <code>Screen</code>
instance. To the <code>Screen</code> instance, they can add a <code>SelectBox</code> and a <code>Button</code>
by putting each in a <code>Box&lt;T&gt;</code> to become a trait object. They can then call the
<code>run</code> method on the <code>Screen</code> instance, which will call <code>draw</code> on each of the
components. Listing 18-9 shows this implementation.</p>
<figure class="listing" id="listing-18-9">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore"><span class="boring">use gui::Draw;
</span><span class="boring">
</span><span class="boring">struct SelectBox {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring"> options: Vec&lt;String&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Draw for SelectBox {
</span><span class="boring"> fn draw(&amp;self) {
</span><span class="boring"> // code to actually draw a select box
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>use gui::{Button, Screen};
fn main() {
let screen = Screen {
components: vec![
Box::new(SelectBox {
width: 75,
height: 10,
options: vec![
String::from("Yes"),
String::from("Maybe"),
String::from("No"),
],
}),
Box::new(Button {
width: 50,
height: 10,
label: String::from("OK"),
}),
],
};
screen.run();
}</code></pre>
<figcaption><a href="#listing-18-9">Listing 18-9</a>: Using trait objects to store values of different types that implement the same trait</figcaption>
</figure>
<p>When we wrote the library, we didnt know that someone might add the
<code>SelectBox</code> type, but our <code>Screen</code> implementation was able to operate on the
new type and draw it because <code>SelectBox</code> implements the <code>Draw</code> trait, which
means it implements the <code>draw</code> method.</p>
<p>This concept—of being concerned only with the messages a value responds to
rather than the values concrete type—is similar to the concept of <em>duck
typing</em> in dynamically typed languages: If it walks like a duck and quacks like
a duck, then it must be a duck! In the implementation of <code>run</code> on <code>Screen</code> in
Listing 18-5, <code>run</code> doesnt need to know what the concrete type of each
component is. It doesnt check whether a component is an instance of a <code>Button</code>
or a <code>SelectBox</code>, it just calls the <code>draw</code> method on the component. By
specifying <code>Box&lt;dyn Draw&gt;</code> as the type of the values in the <code>components</code>
vector, weve defined <code>Screen</code> to need values that we can call the <code>draw</code>
method on.</p>
<p>The advantage of using trait objects and Rusts type system to write code
similar to code using duck typing is that we never have to check whether a
value implements a particular method at runtime or worry about getting errors
if a value doesnt implement a method but we call it anyway. Rust wont compile
our code if the values dont implement the traits that the trait objects need.</p>
<p>For example, Listing 18-10 shows what happens if we try to create a <code>Screen</code>
with a <code>String</code> as a component.</p>
<figure class="listing" id="listing-18-10">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore does_not_compile">use gui::Screen;
fn main() {
let screen = Screen {
components: vec![Box::new(String::from("Hi"))],
};
screen.run();
}</code></pre>
<figcaption><a href="#listing-18-10">Listing 18-10</a>: Attempting to use a type that doesnt implement the trait objects trait</figcaption>
</figure>
<p>Well get this error because <code>String</code> doesnt implement the <code>Draw</code> trait:</p>
<pre><code class="language-console">$ cargo run
Compiling gui v0.1.0 (file:///projects/gui)
error[E0277]: the trait bound `String: Draw` is not satisfied
--&gt; src/main.rs:5:26
|
5 | components: vec![Box::new(String::from("Hi"))],
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String`
|
= help: the trait `Draw` is implemented for `Button`
= note: required for the cast from `Box&lt;String&gt;` to `Box&lt;dyn Draw&gt;`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `gui` (bin "gui") due to 1 previous error
</code></pre>
<p>This error lets us know that either were passing something to <code>Screen</code> that we
didnt mean to pass and so should pass a different type, or we should implement
<code>Draw</code> on <code>String</code> so that <code>Screen</code> is able to call <code>draw</code> on it.</p>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="trait-objects-perform-dynamic-dispatch"></a></p>
<h3 id="performing-dynamic-dispatch"><a class="header" href="#performing-dynamic-dispatch">Performing Dynamic Dispatch</a></h3>
<p>Recall in <a href="../ch10/ch10-01-syntax.html#performance-of-code-using-generics">“Performance of Code Using
Generics”</a><!-- ignore --> in Chapter 10 our
discussion on the monomorphization process performed on generics by the
compiler: The compiler generates nongeneric implementations of functions and
methods for each concrete type that we use in place of a generic type
parameter. The code that results from monomorphization is doing <em>static
dispatch</em>, which is when the compiler knows what method youre calling at
compile time. This is opposed to <em>dynamic dispatch</em>, which is when the compiler
cant tell at compile time which method youre calling. In dynamic dispatch
cases, the compiler emits code that at runtime will know which method to call.</p>
<p>When we use trait objects, Rust must use dynamic dispatch. The compiler doesnt
know all the types that might be used with the code thats using trait objects,
so it doesnt know which method implemented on which type to call. Instead, at
runtime, Rust uses the pointers inside the trait object to know which method to
call. This lookup incurs a runtime cost that doesnt occur with static dispatch.
Dynamic dispatch also prevents the compiler from choosing to inline a methods
code, which in turn prevents some optimizations, and Rust has some rules about
where you can and cannot use dynamic dispatch, called <em>dyn compatibility</em>. Those
rules are beyond the scope of this discussion, but you can read more about them
<a href="https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility">in the reference</a><!-- ignore -->. However, we did get extra
flexibility in the code that we wrote in Listing 18-5 and were able to support
in Listing 18-9, so its a trade-off to consider.</p>
</body>
</html>