Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 564935689ab5527f955e5449ded02799 > files > 299

rust-doc-1.19.0-1.mga6.armv7hl.rpm

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Trait Objects for Using Values of Different Types - The Rust Programming Language</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <base href="">

        <link rel="stylesheet" href="book.css">
        <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

        <link rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <style>
            .page-wrapper.has-warning > .nav-chapters {
              /* add height for warning content & margin */
              top: 120px;
            }

            p.warning {
                background-color: rgb(242, 222, 222);
                border-bottom-color: rgb(238, 211, 215);
                border-bottom-left-radius: 4px;
                border-bottom-right-radius: 4px;
                border-bottom-style: solid;
                border-bottom-width: 0.666667px;
                border-image-outset: 0 0 0 0;
                border-image-repeat: stretch stretch;
                border-image-slice: 100% 100% 100% 100%;
                border-image-source: none;
                border-image-width: 1 1 1 1;
                border-left-color: rgb(238, 211, 215);
                border-left-style: solid;
                border-left-width: 0.666667px;
                border-right-color: rgb(238, 211, 215);
                border-right-style: solid;
                border-right-width: 0.666667px;
                border-top-color: rgb(238, 211, 215);
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                border-top-style: solid;
                border-top-width: 0.666667px;
                color: rgb(185, 74, 72);
                margin-bottom: 0px;
                margin-left: 0px;
                margin-right: 0px;
                margin-top: 30px;
                padding-bottom: 8px;
                padding-left: 14px;
                padding-right: 35px;
                padding-top: 8px;
            }
            p.warning strong {
                color: rgb(185, 74, 72)
            }
            p.warning a {
                color: rgb(0, 136, 204)
            }
        </style>

        <!-- MathJax -->
        <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

        <!-- Fetch JQuery from CDN but have a local fallback -->
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
            if (typeof jQuery == 'undefined') {
                document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
            }
        </script>
    </head>
    <body class="light">
        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme = localStorage.getItem('theme');
            if (theme == null) { theme = 'light'; }
            $('body').removeClass().addClass(theme);
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var sidebar = localStorage.getItem('sidebar');
            if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
            else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
        </script>

        <div id="sidebar" class="sidebar">
            <ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Using Structs to Structure Related Data</a></li><li><ul class="section"><li><a href="ch05-01-defining-structs.html"><strong>5.1.</strong> Defining and Instantiating Structs</a></li><li><a href="ch05-02-example-structs.html"><strong>5.2.</strong> An Example Program Using Structs</a></li><li><a href="ch05-03-method-syntax.html"><strong>5.3.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums and Pattern Matching</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> Defining an Enum</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> The <code>match</code> Control Flow Operator</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> Concise Control Flow with <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-common-collections.html"><strong>8.</strong> Common Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generic Types, Traits, and Lifetimes</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Generic Data Types</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits: Defining Shared Behavior</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Validating References with Lifetimes</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Improving Error Handling and Modularity</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Testing the Library's Functionality</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing to <code>stderr</code> instead of <code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features in Rust</a></li><li><ul class="section"><li><a href="ch13-01-closures.html"><strong>13.1.</strong> Closures</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> Iterators</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> Improving our I/O Project</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> Performance</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> Release Profiles</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> Publishing a Crate to Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo Workspaces</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> Installing Binaries from Crates.io with <code>cargo install</code></a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Extending Cargo with Custom Commands</a></li></ul></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="ch15-01-box.html"><strong>15.1.</strong> <code>Box&lt;T&gt;</code> Points to Data on the Heap and Has a Known Size</a></li><li><a href="ch15-02-deref.html"><strong>15.2.</strong> The <code>Deref</code> Trait Allows Access to the Data Through a Reference</a></li><li><a href="ch15-03-drop.html"><strong>15.3.</strong> The <code>Drop</code> Trait Runs Code on Cleanup</a></li><li><a href="ch15-04-rc.html"><strong>15.4.</strong> <code>Rc&lt;T&gt;</code>, the Reference Counted Smart Pointer</a></li><li><a href="ch15-05-interior-mutability.html"><strong>15.5.</strong> <code>RefCell&lt;T&gt;</code> and the Interior Mutability Pattern</a></li><li><a href="ch15-06-reference-cycles.html"><strong>15.6.</strong> Creating Reference Cycles and Leaking Memory is Safe</a></li></ul></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Fearless Concurrency</a></li><li><ul class="section"><li><a href="ch16-01-threads.html"><strong>16.1.</strong> Threads</a></li><li><a href="ch16-02-message-passing.html"><strong>16.2.</strong> Message Passing</a></li><li><a href="ch16-03-shared-state.html"><strong>16.3.</strong> Shared State</a></li><li><a href="ch16-04-extensible-concurrency-sync-and-send.html"><strong>16.4.</strong> Extensible Concurrency: <code>Sync</code> and <code>Send</code></a></li></ul></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust an Object-Oriented Programming Language?</a></li><li><ul class="section"><li><a href="ch17-01-what-is-oo.html"><strong>17.1.</strong> What Does Object-Oriented Mean?</a></li><li><a href="ch17-02-trait-objects.html" class="active"><strong>17.2.</strong> Trait Objects for Using Values of Different Types</a></li><li><a href="ch17-03-oo-design-patterns.html"><strong>17.3.</strong> Object-Oriented Design Pattern Implementations</a></li></ul></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns Match the Structure of Values</a></li><li><ul class="section"><li><a href="ch18-01-all-the-places-for-patterns.html"><strong>18.1.</strong> All the Places Patterns May be Used</a></li><li><a href="ch18-02-refutability.html"><strong>18.2.</strong> Refutability: Whether a Pattern Might Fail to Match</a></li><li><a href="ch18-03-pattern-syntax.html"><strong>18.3.</strong> All the Pattern Syntax</a></li></ul></li><li><a href="ch19-00-advanced-features.html"><strong>19.</strong> Advanced Features</a></li><li><ul class="section"><li><a href="ch19-01-unsafe-rust.html"><strong>19.1.</strong> Unsafe Rust</a></li><li><a href="ch19-02-advanced-lifetimes.html"><strong>19.2.</strong> Advanced Lifetimes</a></li><li><a href="ch19-03-advanced-traits.html"><strong>19.3.</strong> Advanced Traits</a></li><li><a href="ch19-04-advanced-types.html"><strong>19.4.</strong> Advanced Types</a></li><li><a href="ch19-05-advanced-functions-and-closures.html"><strong>19.5.</strong> Advanced Functions &amp; Closures</a></li></ul></li><li><a href="ch20-00-final-project-a-web-server.html"><strong>20.</strong> Final Project: Building a Multithreaded Web Server</a></li><li><ul class="section"><li><a href="ch20-01-single-threaded.html"><strong>20.1.</strong> A Single Threaded Web Server</a></li><li><a href="ch20-02-slow-requests.html"><strong>20.2.</strong> How Slow Requests Affect Throughput</a></li><li><a href="ch20-03-designing-the-interface.html"><strong>20.3.</strong> Designing the Thread Pool Interface</a></li><li><a href="ch20-04-storing-threads.html"><strong>20.4.</strong> Creating the Thread Pool and Storing Threads</a></li><li><a href="ch20-05-sending-requests-via-channels.html"><strong>20.5.</strong> Sending Requests to Threads Via Channels</a></li><li><a href="ch20-06-graceful-shutdown-and-cleanup.html"><strong>20.6.</strong> Graceful Shutdown and Cleanup</a></li></ul></li><li><a href="appendix-00.html"><strong>21.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>21.1.</strong> A - Keywords</a></li><li><a href="appendix-02-operators.html"><strong>21.2.</strong> B - Operators</a></li><li><strong>21.3.</strong> C - Derivable Traits</li><li><strong>21.4.</strong> D - Nightly Rust</li><li><strong>21.5.</strong> E - Macros</li><li><strong>21.6.</strong> F - Translations</li><li><a href="appendix-07-newest-features.html"><strong>21.7.</strong> G - Newest Features</a></li></ul></li></ul>
        </div>

        <div id="page-wrapper" class="page-wrapper has-warning">

            <div class="page">
                <header><p class="warning">You are reading a <strong>draft</strong> of the next edition of TRPL. For more, go <a href="../index.html">here</a>.</p></header>
                <div id="menu-bar" class="menu-bar">
                    <div class="left-buttons">
                        <i id="sidebar-toggle" class="fa fa-bars"></i>
                        <i id="theme-toggle" class="fa fa-paint-brush"></i>
                    </div>

                    <h1 class="menu-title">The Rust Programming Language</h1>

                    <div class="right-buttons">
                        <i id="print-button" class="fa fa-print" title="Print this book"></i>
                    </div>
                </div>


                <div id="content" class="content">
                    <a class="header" href="ch17-02-trait-objects.html#trait-objects-for-using-values-of-different-types" id="trait-objects-for-using-values-of-different-types"><h2>Trait Objects for Using Values of Different Types</h2></a>
<p>In Chapter 8, we said that a limitation of vectors is that vectors can only
store elements of one type. We had an example in Listing 8-1 where we defined a
<code>SpreadsheetCell</code> enum that had variants to hold integers, floats, and text so
that we could store different types of data in each cell and still have a
vector represent a row of cells. This works for cases in which the kinds of
things we want to be able to treat interchangeably are a fixed set of types that
we know when our code gets compiled.</p>
<!-- The code example I want to reference did not have a listing number; it's
the one with SpreadsheetCell. I will go back and add Listing 8-1 next time I
get Chapter 8 for editing. /Carol -->
<p>Sometimes we want the set of types that we use to be extensible by the
programmers who use our library. For example, many Graphical User Interface
tools have a concept of a list of items that get drawn on the screen by
iterating through the list and calling a <code>draw</code> method on each of the items.
We're going to create a library crate containing the structure of a GUI library
called <code>rust_gui</code>. Our GUI library could include some types for people to use,
such as <code>Button</code> or <code>TextField</code>. Programmers that use <code>rust_gui</code> will want to
create more types that can be drawn on the screen: one programmer might add an
<code>Image</code>, while another might add a <code>SelectBox</code>. We're not going to implement a
fully-fledged GUI library in this chapter, but we will show how the pieces
would fit together.</p>
<p>When we're writing the <code>rust_gui</code> library, we don't know all the types that
other programmers will want to create, so we can't define an <code>enum</code> containing
all the types. What we do know is that <code>rust_gui</code> needs to be able to keep
track of a bunch of values of all these different types, and it needs to be
able to call a <code>draw</code> method on each of these values. Our GUI library doesn't
need to know what will happen exactly when we call the <code>draw</code> method, just that
the value will have that method available for us to call.</p>
<p>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 like <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.</p>
<a class="header" href="ch17-02-trait-objects.html#defining-a-trait-for-the-common-behavior" id="defining-a-trait-for-the-common-behavior"><h3>Defining a Trait for the Common Behavior</h3></a>
<p>In Rust, though, we can define a trait that we'll name <code>Draw</code> and that will
have one method named <code>draw</code>. Then we can define a vector that takes a <em>trait
object</em>, which is a trait behind some sort of pointer, such as a <code>&amp;</code> reference
or a <code>Box&lt;T&gt;</code> smart pointer. We'll talk about the reason trait objects have to
be behind a pointer in Chapter 19.</p>
<p>We mentioned that we don't call structs and enums &quot;objects&quot; to distinguish
structs and enums from other languages' objects. The data in the struct or enum
fields and the behavior in <code>impl</code> blocks is separated, as opposed to other
languages that have data and behavior combined into one concept called an
object. Trait objects <em>are</em> more like objects in other languages, in the sense
that they combine the data made up of the pointer to a concrete object with the
behavior of the methods defined in the trait. However, trait objects are
different from objects in other languages because we can't add data to a trait
object. Trait objects aren't as generally useful as objects in other languages:
their purpose is to allow abstraction across common behavior.</p>
<p>A trait defines behavior that we need in a given situation. We can then use a
trait as a trait object in places where we would use a concrete type or a
generic type. Rust's type system will ensure that any value we substitute in
for the trait object will implement the methods of the trait. Then we don't
need to know all the possible types at compile time, and we can treat all the
instances the same way. Listing 17-3 shows how to define a trait named <code>Draw</code>
with one method named <code>draw</code>:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
pub trait Draw {
    fn draw(&amp;self);
}

#}</code></pre></pre>
<p><span class="caption">Listing 17-3: Definition of the <code>Draw</code> trait</span></p>
<!-- NEXT PARAGRAPH WRAPPED WEIRD INTENTIONALLY SEE #199 -->
<p>This should look familiar since we talked about how to define traits in
Chapter 10. Next comes something new: Listing 17-4 has the definition of a
struct named <code>Screen</code> that holds a vector named <code>components</code> that are of type
<code>Box&lt;Draw&gt;</code>. That <code>Box&lt;Draw&gt;</code> is a trait object: it's a stand-in for any type
inside a <code>Box</code> that implements the <code>Draw</code> trait.</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# pub trait Draw {
#     fn draw(&amp;self);
# }
#
pub struct Screen {
    pub components: Vec&lt;Box&lt;Draw&gt;&gt;,
}

#}</code></pre></pre>
<p><span class="caption">Listing 17-4: Definition of the <code>Screen</code> struct with a
<code>components</code> field that holds a vector of trait objects that implement the
<code>Draw</code> trait</span></p>
<p>On the <code>Screen</code> struct, we'll define a method named <code>run</code>, which will call the
<code>draw</code> method on each of its <code>components</code> as shown in Listing 17-5:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# pub trait Draw {
#     fn draw(&amp;self);
# }
#
# pub struct Screen {
#     pub components: Vec&lt;Box&lt;Draw&gt;&gt;,
# }
#
impl Screen {
    pub fn run(&amp;self) {
        for component in self.components.iter() {
            component.draw();
        }
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 17-5: Implementing a <code>run</code> method on <code>Screen</code>
that calls the <code>draw</code> method on each component</span></p>
<p>This is different than defining a struct that uses a generic type parameter
with trait bounds. A generic type parameter can only be substituted with one
concrete type at a time, while 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 17-6:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# pub trait Draw {
#     fn draw(&amp;self);
# }
#
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></pre>
<p><span class="caption">Listing 17-6: An alternate implementation of the <code>Screen</code>
struct and its <code>run</code> method using generics and trait bounds</span></p>
<p>This only lets us have a <code>Screen</code> instance that has a list of components that
are all of type <code>Button</code> or all of type <code>TextField</code>. If you'll only ever have
homogeneous collections, using generics and trait bounds is preferable since
the definitions will be monomorphized at compile time to use the concrete types.</p>
<p>With the definition of <code>Screen</code> that holds a component list of trait objects in
<code>Vec&lt;Box&lt;Draw&gt;&gt;</code> instead, one <code>Screen</code> instance can hold a <code>Vec</code> that contains
a <code>Box&lt;Button&gt;</code> as well as a <code>Box&lt;TextField&gt;</code>. Let's see how that works, and
then talk about the runtime performance implications.</p>
<a class="header" href="ch17-02-trait-objects.html#implementations-of-the-trait-from-us-or-library-users" id="implementations-of-the-trait-from-us-or-library-users"><h3>Implementations of the Trait from Us or Library Users</h3></a>
<p>Now to add some types that implement the <code>Draw</code> trait. We're going to provide
the <code>Button</code> type, and again, actually implementing a GUI library is out of
scope of this book, so the <code>draw</code> method won't 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 17-7:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# pub trait Draw {
#     fn draw(&amp;self);
# }
#
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></pre>
<p><span class="caption">Listing 17-7: A <code>Button</code> struct that implements the
<code>Draw</code> trait</span></p>
<p>The <code>width</code>, <code>height</code>, and <code>label</code> fields on <code>Button</code> will differ from other
components, such as a <code>TextField</code> type that might have <code>width</code>, <code>height</code>,
<code>label</code>, and <code>placeholder</code> fields instead. Each of the types that we want to be
able to draw on the screen will implement the <code>Draw</code> trait with different code
in the <code>draw</code> method that defines how to draw that type like <code>Button</code> has here
(without any actual GUI code that's out of scope of this chapter). In addition
to implementing the <code>Draw</code> trait, <code>Button</code> might also have another <code>impl</code> block
containing methods having to do with what happens if the button is clicked.
These kinds of methods won't apply to types like <code>TextField</code>.</p>
<p>Someone using our library has decided to implement a <code>SelectBox</code> struct that
has <code>width</code>, <code>height</code>, and <code>options</code> fields. They implement the <code>Draw</code> trait on
the <code>SelectBox</code> type as well, as shown in Listing 17-8:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern crate rust_gui;
use rust_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
    }
}
</code></pre>
<p><span class="caption">Listing 17-8: Another crate using <code>rust_gui</code> and
implementing the <code>Draw</code> trait on a <code>SelectBox</code> struct</span></p>
<p>The user of our library can now write their <code>main</code> function to create a
<code>Screen</code> instance and add a <code>SelectBox</code> and a <code>Button</code> to the screen 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 17-9 shows this implementation:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">use rust_gui::{Screen, Button};

fn main() {
    let screen = Screen {
        components: vec![
            Box::new(SelectBox {
                width: 75,
                height: 10,
                options: vec![
                    String::from(&quot;Yes&quot;),
                    String::from(&quot;Maybe&quot;),
                    String::from(&quot;No&quot;)
                ],
            }),
            Box::new(Button {
                width: 50,
                height: 10,
                label: String::from(&quot;OK&quot;),
            }),
        ],
    };

    screen.run();
}
</code></pre>
<p><span class="caption">Listing 17-9: Using trait objects to store values of
different types that implement the same trait</span></p>
<p>Even though we didn't know that someone would add the <code>SelectBox</code> type someday,
our <code>Screen</code> implementation was able to operate on the <code>SelectBox</code> and draw it
because <code>SelectBox</code> implements the <code>Draw</code> type, which means it implements the
<code>draw</code> method.</p>
<p>Only being concerned with the messages a value responds to, rather than the
value's concrete type, is similar to a concept called <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
17-5, <code>run</code> doesn't need to know what the concrete type of each component is.
It doesn't check to see if 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;Draw&gt;</code> as the type of the values in the <code>components</code> vector, we've defined
that <code>Screen</code> needs values that we can call the <code>draw</code> method on.</p>
<p>The advantage with using trait objects and Rust's type system to do duck typing
is that we never have to check that a value implements a particular method at
runtime or worry about getting errors if a value doesn't implement a method but
we call it. Rust won't compile our code if the values don't implement the
traits that the trait objects need.</p>
<p>For example, Listing 17-10 shows what happens if we try to create a <code>Screen</code>
with a <code>String</code> as a component:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern crate rust_gui;
use rust_gui::Draw;

fn main() {
    let screen = Screen {
        components: vec![
            Box::new(String::from(&quot;Hi&quot;)),
        ],
    };

    screen.run();
}
</code></pre>
<p><span class="caption">Listing 17-10: Attempting to use a type that doesn't
implement the trait object's trait</span></p>
<p>We'll get this error because <code>String</code> doesn't implement the <code>Draw</code> trait:</p>
<pre><code class="language-text">error[E0277]: the trait bound `std::string::String: Draw` is not satisfied
  --&gt;
   |
 4 |             Box::new(String::from(&quot;Hi&quot;)),
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not
   implemented for `std::string::String`
   |
   = note: required for the cast to the object type `Draw`
</code></pre>
<p>This lets us know that either we're passing something we didn't mean to pass to
<code>Screen</code> and we 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>
<a class="header" href="ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch" id="trait-objects-perform-dynamic-dispatch"><h3>Trait Objects Perform Dynamic Dispatch</h3></a>
<p>Recall in Chapter 10 when we discussed the process of monomorphization that the
compiler performs when we use trait bounds on generics: the compiler generates
non-generic 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>: when the method is called, the
code that goes with that method call has been determined at compile time, and
looking up that code is very fast.</p>
<p>When we use trait objects, the compiler can't perform monomorphization because
we don't know all the types that might be used with the code. Instead, Rust
keeps track of the code that might be used when a method is called and figures
out at runtime which code needs to be used for a particular method call. This
is known as <em>dynamic dispatch</em>, and there's a runtime cost when this lookup
happens. Dynamic dispatch also prevents the compiler from choosing to inline a
method's code, which prevents some optimizations. We did get extra flexibility
in the code that we wrote and were able to support, though, so it's a tradeoff
to consider.</p>
<a class="header" href="ch17-02-trait-objects.html#object-safety-is-required-for-trait-objects" id="object-safety-is-required-for-trait-objects"><h3>Object Safety is Required for Trait Objects</h3></a>
<!-- Liz: we're conflicted on including this section. Not being able to use a
trait as a trait object because of object safety is something that
beginner/intermediate Rust developers run into sometimes, but explaining it
fully is long and complicated. Should we just cut this whole section? Leave it
(and finish the explanation of how to fix the error at the end)? Shorten it to
a quick caveat, that just says something like "Some traits can't be trait
objects. Clone is an example of one. You'll get errors that will let you know
if a trait can't be a trait object, look up object safety if you're interested
in the details"? Thanks! /Carol -->
<p>Not all traits can be made into trait objects; only <em>object safe</em> traits can. A
trait is object safe as long as both of the following are true:</p>
<ul>
<li>The trait does not require <code>Self</code> to be <code>Sized</code></li>
<li>All of the trait's methods are object safe.</li>
</ul>
<p><code>Self</code> is a keyword that is an alias for the type that we're implementing
traits or methods on. <code>Sized</code> is a marker trait like the <code>Send</code> and <code>Sync</code>
traits that we talked about in Chapter 16. <code>Sized</code> is automatically implemented
on types that have a known size at compile time, such as <code>i32</code> and references.
Types that do not have a known size include slices (<code>[T]</code>) and trait objects.</p>
<p><code>Sized</code> is an implicit trait bound on all generic type parameters by default.
Most useful operations in Rust require a type to be <code>Sized</code>, so making <code>Sized</code>
a default requirement on trait bounds means we don't have to write <code>T: Sized</code>
with most every use of generics. If we want to be able to use a trait on
slices, however, we need to opt out of the <code>Sized</code> trait bound, and we can do
that by specifying <code>T: ?Sized</code> as a trait bound.</p>
<p>Traits have a default bound of <code>Self: ?Sized</code>, which means that they can be
implemented on types that may or may not be <code>Sized</code>. If we create a trait <code>Foo</code>
that opts out of the <code>Self: ?Sized</code> bound, that would look like the following:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
trait Foo: Sized {
    fn some_method(&amp;self);
}

#}</code></pre></pre>
<p>The trait <code>Sized</code> is now a <em>supertrait</em> of trait <code>Foo</code>, which means trait <code>Foo</code>
requires types that implement <code>Foo</code> (that is, <code>Self</code>) to be <code>Sized</code>. We're
going to talk about supertraits in more detail in Chapter 19.</p>
<p>The reason a trait like <code>Foo</code> that requires <code>Self</code> to be <code>Sized</code> is not allowed
to be a trait object is that it would be impossible to implement the trait
<code>Foo</code> for the trait object <code>Foo</code>: trait objects aren't sized, but <code>Foo</code>
requires <code>Self</code> to be <code>Sized</code>. A type can't be both sized and unsized at the
same time!</p>
<p>For the second object safety requirement that says all of a trait's methods
must be object safe, a method is object safe if either:</p>
<ul>
<li>It requires <code>Self</code> to be <code>Sized</code> or</li>
<li>It meets all three of the following:
<ul>
<li>It must not have any generic type parameters</li>
<li>Its first argument must be of type <code>Self</code> or a type that dereferences to
the Self type (that is, it must be a method rather than an associated
function and have <code>self</code>, <code>&amp;self</code>, or <code>&amp;mut self</code> as the first argument)</li>
<li>It must not use <code>Self</code> anywhere else in the signature except for the
first argument</li>
</ul>
</li>
</ul>
<p>Those rules are a bit formal, but think of it this way: if your method requires
the concrete <code>Self</code> type somewhere in its signature, but an object forgets the
exact type that it is, there's no way that the method can use the original
concrete type that it's forgotten. Same with generic type parameters that are
filled in with concrete type parameters when the trait is used: the concrete
types become part of the type that implements the trait. When the type is
erased by the use of a trait object, there's no way to know what types to fill
in the generic type parameters with.</p>
<p>An example of a trait whose methods are not object safe is the standard
library's <code>Clone</code> trait. The signature for the <code>clone</code> method in the <code>Clone</code>
trait looks like this:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
pub trait Clone {
    fn clone(&amp;self) -&gt; Self;
}

#}</code></pre></pre>
<p><code>String</code> implements the <code>Clone</code> trait, and when we call the <code>clone</code> method on
an instance of <code>String</code> we get back an instance of <code>String</code>. Similarly, if we
call <code>clone</code> on an instance of <code>Vec</code>, we get back an instance of <code>Vec</code>. The
signature of <code>clone</code> needs to know what type will stand in for <code>Self</code>, since
that's the return type.</p>
<p>If we try to implement <code>Clone</code> on a trait like the <code>Draw</code> trait from Listing
17-3, we wouldn't know whether <code>Self</code> would end up being a <code>Button</code>, a
<code>SelectBox</code>, or some other type that will implement the <code>Draw</code> trait in the
future.</p>
<p>The compiler will tell you if you're trying to do something that violates the
rules of object safety in regards to trait objects. For example, if we had
tried to implement the <code>Screen</code> struct in Listing 17-4 to hold types that
implement the <code>Clone</code> trait instead of the <code>Draw</code> trait, like this:</p>
<pre><code class="language-rust ignore">pub struct Screen {
    pub components: Vec&lt;Box&lt;Clone&gt;&gt;,
}
</code></pre>
<p>We'll get this error:</p>
<pre><code class="language-text">error[E0038]: the trait `std::clone::Clone` cannot be made into an object
 --&gt;
  |
2 |     pub components: Vec&lt;Box&lt;Clone&gt;&gt;,
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` cannot be
  made into an object
  |
  = note: the trait cannot require that `Self : Sized`
</code></pre>
<!-- If we are including this section, we would explain how to fix this
problem. It involves adding another trait and implementing Clone manually for
that trait. Because this section is getting long, I stopped because it feels
like we're off in the weeds with an esoteric detail that not everyone will need
to know about. /Carol -->

                </div>

                <!-- Mobile navigation buttons -->
                
                    <a href="ch17-01-what-is-oo.html" class="mobile-nav-chapters previous">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="ch17-03-oo-design-patterns.html" class="mobile-nav-chapters next">
                        <i class="fa fa-angle-right"></i>
                    </a>
                

            </div>

            
                <a href="ch17-01-what-is-oo.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-left"></i>
                </a>
            

            
                <a href="ch17-03-oo-design-patterns.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-right"></i>
                </a>
            

        </div>


        <!-- Local fallback for Font Awesome -->
        <script>
            if ($(".fa").css("font-family") !== "FontAwesome") {
                $('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
            }
        </script>

        <!-- Livereload script (if served using the cli tool) -->
        

        <script src="highlight.js"></script>
        <script src="book.js"></script>
    </body>
</html>