mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 22:21:17 -06:00
391 lines
21 KiB
HTML
391 lines
21 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title></title>
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="{% block description %}{% endblock %}">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
||
<base href="">
|
||
|
||
<link rel="stylesheet" href="book.css">
|
||
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
||
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="http://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">
|
||
|
||
<!-- 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="http://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>
|
||
<!-- 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="introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="hello-world.html"><strong>1.2.</strong> Hello, World!</a></li><li><a href="design.html"><strong>1.3.</strong> The Design of Rust</a></li></ul></li><li><a href="tutorial.html"><strong>2.</strong> Tutorial</a></li><li><a href="basics.html"><strong>3.</strong> The Basics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> `if`</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li></ul></li><li><a href="ownership-and-borrowing.html"><strong>4.</strong> Ownership & borrowing</a></li><li><ul class="section"><li><a href="ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="lifetimes.html"><strong>4.3.</strong> Lifetimes</a></li></ul></li><li><a href="basic-data-types.html"><strong>5.</strong> Basic Data Types</a></li><li><ul class="section"><li><a href="structs.html"><strong>5.1.</strong> Structs</a></li><li><a href="enums.html"><strong>5.2.</strong> Enums</a></li></ul></li><li><a href="crates-and-modules.html"><strong>6.</strong> Crates & Modules</a></li><li><a href="error-handling.html"><strong>7.</strong> Error Handling</a></li><li><a href="basic-collections.html"><strong>8.</strong> Basic Collections</a></li><li><ul class="section"><li><a href="vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="hashmap.html"><strong>8.3.</strong> `HashMap<K, V>`</a></li></ul></li><li><a href="traits.html"><strong>9.</strong> Traits</a></li><li><a href="closures.html"><strong>10.</strong> Closures</a></li><li><a href="iterators.html"><strong>11.</strong> Iterators</a></li><li><a href="io.html"><strong>12.</strong> I/O</a></li><li><ul class="section"><li><a href="read-and-write.html"><strong>12.1.</strong> `Read` & `Write`</a></li><li><a href="fs.html"><strong>12.2.</strong> `std::fs`</a></li><li><a href="path.html"><strong>12.3.</strong> `std::path`</a></li><li><a href="env.html"><strong>12.4.</strong> `std::env`</a></li></ul></li><li><a href="testing.html"><strong>13.</strong> Testing</a></li><li><a href="smart-pointers.html"><strong>14.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="deref.html"><strong>14.1.</strong> `Deref`</a></li><li><a href="deref-coercions.html"><strong>14.2.</strong> `Deref` coercions</a></li><li><a href="box.html"><strong>14.3.</strong> `Box<T>`</a></li><li><a href="rc.html"><strong>14.4.</strong> `Rc<T>`</a></li></ul></li><li><a href="concurrency.html"><strong>15.</strong> Concurrency</a></li><li><ul class="section"><li><a href="threads.html"><strong>15.1.</strong> Threads</a></li><li><a href="send-and-sync.html"><strong>15.2.</strong> `Send` & `Sync`</a></li><li><a href="arc.html"><strong>15.3.</strong> `Arc<T>`</a></li><li><a href="mutex.html"><strong>15.4.</strong> `Mutex<T>`</a></li><li><a href="channels.html"><strong>15.5.</strong> `Channels`</a></li></ul></li><li><a href="unsafe-rust.html"><strong>16.</strong> Unsafe Rust</a></li><li><ul class="section"><li><a href="raw-pointers.html"><strong>16.1.</strong> Raw Pointers</a></li><li><a href="transmute.html"><strong>16.2.</strong> transmute</a></li></ul></li><li><a href="ffi.html"><strong>17.</strong> FFI</a></li><li><ul class="section"><li><a href="conditional-compilation.html"><strong>17.1.</strong> Conditional Compilation</a></li><li><a href="bindings-to-c.html"><strong>17.2.</strong> Bindings to C</a></li><li><a href="using-rust-from-other-languages.html"><strong>17.3.</strong> Using Rust from Other Languages</a></li><li><a href="static.html"><strong>17.4.</strong> `static`</a></li></ul></li><li><a href="cargo.html"><strong>18.</strong> Cargo</a></li><li><ul class="section"><li><a href="cratesio.html"><strong>18.1.</strong> Crates.io</a></li></ul></li><li><a href="advanced-type-system-features.html"><strong>19.</strong> Advanced Type System Features</a></li><li><ul class="section"><li><a href="associated-types.html"><strong>19.1.</strong> Associated Types</a></li><li><a href="trait-objects.html" class="active"><strong>19.2.</strong> Trait Objects</a></li><li><a href="ufcs.html"><strong>19.3.</strong> UFCS</a></li><li><a href="coherence.html"><strong>19.4.</strong> Coherence</a></li></ul></li><li><a href="interior-mutability.html"><strong>20.</strong> Interior mutability</a></li><li><ul class="section"><li><a href="cell.html"><strong>20.1.</strong> `Cell<T>`</a></li><li><a href="refcell.html"><strong>20.2.</strong> `RefCell<T>`</a></li></ul></li><li><a href="macros.html"><strong>21.</strong> Macros</a></li><li><a href="nightly-rust.html"><strong>22.</strong> Nightly Rust</a></li></ul>
|
||
</div>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<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"></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">
|
||
<h1>Trait Objects</h1>
|
||
<p>When code involves polymorphism, there needs to be a mechanism to determine
|
||
which specific version is actually run. This is called ‘dispatch’. There are
|
||
two major forms of dispatch: static dispatch and dynamic dispatch. While Rust
|
||
favors static dispatch, it also supports dynamic dispatch through a mechanism
|
||
called ‘trait objects’.</p>
|
||
<h2>Background</h2>
|
||
<p>For the rest of this chapter, we’ll need a trait and some implementations.
|
||
Let’s make a simple one, <code>Foo</code>. It has one method that is expected to return a
|
||
<code>String</code>.</p>
|
||
<pre><code class="language-rust">trait Foo {
|
||
fn method(&self) -> String;
|
||
}
|
||
</code></pre>
|
||
<p>We’ll also implement this trait for <code>u8</code> and <code>String</code>:</p>
|
||
<pre><code class="language-rust"># trait Foo { fn method(&self) -> String; }
|
||
impl Foo for u8 {
|
||
fn method(&self) -> String { format!("u8: {}", *self) }
|
||
}
|
||
|
||
impl Foo for String {
|
||
fn method(&self) -> String { format!("string: {}", *self) }
|
||
}
|
||
</code></pre>
|
||
<h2>Static dispatch</h2>
|
||
<p>We can use this trait to perform static dispatch with trait bounds:</p>
|
||
<pre><code class="language-rust"># trait Foo { fn method(&self) -> String; }
|
||
# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
|
||
# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }
|
||
fn do_something<T: Foo>(x: T) {
|
||
x.method();
|
||
}
|
||
|
||
fn main() {
|
||
let x = 5u8;
|
||
let y = "Hello".to_string();
|
||
|
||
do_something(x);
|
||
do_something(y);
|
||
}
|
||
</code></pre>
|
||
<p>Rust uses ‘monomorphization’ to perform static dispatch here. This means that
|
||
Rust will create a special version of <code>do_something()</code> for both <code>u8</code> and
|
||
<code>String</code>, and then replace the call sites with calls to these specialized
|
||
functions. In other words, Rust generates something like this:</p>
|
||
<pre><code class="language-rust"># trait Foo { fn method(&self) -> String; }
|
||
# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
|
||
# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }
|
||
fn do_something_u8(x: u8) {
|
||
x.method();
|
||
}
|
||
|
||
fn do_something_string(x: String) {
|
||
x.method();
|
||
}
|
||
|
||
fn main() {
|
||
let x = 5u8;
|
||
let y = "Hello".to_string();
|
||
|
||
do_something_u8(x);
|
||
do_something_string(y);
|
||
}
|
||
</code></pre>
|
||
<p>This has a great upside: static dispatch allows function calls to be
|
||
inlined because the callee is known at compile time, and inlining is
|
||
the key to good optimization. Static dispatch is fast, but it comes at
|
||
a tradeoff: ‘code bloat’, due to many copies of the same function
|
||
existing in the binary, one for each type.</p>
|
||
<p>Furthermore, compilers aren’t perfect and may “optimize” code to become slower.
|
||
For example, functions inlined too eagerly will bloat the instruction cache
|
||
(cache rules everything around us). This is part of the reason that <code>#[inline]</code>
|
||
and <code>#[inline(always)]</code> should be used carefully, and one reason why using a
|
||
dynamic dispatch is sometimes more efficient.</p>
|
||
<p>However, the common case is that it is more efficient to use static dispatch,
|
||
and one can always have a thin statically-dispatched wrapper function that does
|
||
a dynamic dispatch, but not vice versa, meaning static calls are more flexible.
|
||
The standard library tries to be statically dispatched where possible for this
|
||
reason.</p>
|
||
<h2>Dynamic dispatch</h2>
|
||
<p>Rust provides dynamic dispatch through a feature called ‘trait objects’. Trait
|
||
objects, like <code>&Foo</code> or <code>Box<Foo></code>, are normal values that store a value of
|
||
<em>any</em> type that implements the given trait, where the precise type can only be
|
||
known at runtime.</p>
|
||
<p>A trait object can be obtained from a pointer to a concrete type that
|
||
implements the trait by <em>casting</em> it (e.g. <code>&x as &Foo</code>) or <em>coercing</em> it
|
||
(e.g. using <code>&x</code> as an argument to a function that takes <code>&Foo</code>).</p>
|
||
<p>These trait object coercions and casts also work for pointers like <code>&mut T</code> to
|
||
<code>&mut Foo</code> and <code>Box<T></code> to <code>Box<Foo></code>, but that’s all at the moment. Coercions
|
||
and casts are identical.</p>
|
||
<p>This operation can be seen as ‘erasing’ the compiler’s knowledge about the
|
||
specific type of the pointer, and hence trait objects are sometimes referred to
|
||
as ‘type erasure’.</p>
|
||
<p>Coming back to the example above, we can use the same trait to perform dynamic
|
||
dispatch with trait objects by casting:</p>
|
||
<pre><code class="language-rust"># trait Foo { fn method(&self) -> String; }
|
||
# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
|
||
# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }
|
||
|
||
fn do_something(x: &Foo) {
|
||
x.method();
|
||
}
|
||
|
||
fn main() {
|
||
let x = 5u8;
|
||
do_something(&x as &Foo);
|
||
}
|
||
</code></pre>
|
||
<p>or by coercing:</p>
|
||
<pre><code class="language-rust"># trait Foo { fn method(&self) -> String; }
|
||
# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
|
||
# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }
|
||
|
||
fn do_something(x: &Foo) {
|
||
x.method();
|
||
}
|
||
|
||
fn main() {
|
||
let x = "Hello".to_string();
|
||
do_something(&x);
|
||
}
|
||
</code></pre>
|
||
<p>A function that takes a trait object is not specialized to each of the types
|
||
that implements <code>Foo</code>: only one copy is generated, often (but not always)
|
||
resulting in less code bloat. However, this comes at the cost of requiring
|
||
slower virtual function calls, and effectively inhibiting any chance of
|
||
inlining and related optimizations from occurring.</p>
|
||
<h3>Why pointers?</h3>
|
||
<p>Rust does not put things behind a pointer by default, unlike many managed
|
||
languages, so types can have different sizes. Knowing the size of the value at
|
||
compile time is important for things like passing it as an argument to a
|
||
function, moving it about on the stack and allocating (and deallocating) space
|
||
on the heap to store it.</p>
|
||
<p>For <code>Foo</code>, we would need to have a value that could be at least either a
|
||
<code>String</code> (24 bytes) or a <code>u8</code> (1 byte), as well as any other type for which
|
||
dependent crates may implement <code>Foo</code> (any number of bytes at all). There’s no
|
||
way to guarantee that this last point can work if the values are stored without
|
||
a pointer, because those other types can be arbitrarily large.</p>
|
||
<p>Putting the value behind a pointer means the size of the value is not relevant
|
||
when we are tossing a trait object around, only the size of the pointer itself.</p>
|
||
<h3>Representation</h3>
|
||
<p>The methods of the trait can be called on a trait object via a special record
|
||
of function pointers traditionally called a ‘vtable’ (created and managed by
|
||
the compiler).</p>
|
||
<p>Trait objects are both simple and complicated: their core representation and
|
||
layout is quite straight-forward, but there are some curly error messages and
|
||
surprising behaviors to discover.</p>
|
||
<p>Let’s start simple, with the runtime representation of a trait object. The
|
||
<code>std::raw</code> module contains structs with layouts that are the same as the
|
||
complicated built-in types, <a href="../std/raw/struct.TraitObject.html">including trait objects</a>:</p>
|
||
<pre><code class="language-rust"># mod foo {
|
||
pub struct TraitObject {
|
||
pub data: *mut (),
|
||
pub vtable: *mut (),
|
||
}
|
||
# }
|
||
</code></pre>
|
||
<p>That is, a trait object like <code>&Foo</code> consists of a ‘data’ pointer and a ‘vtable’
|
||
pointer.</p>
|
||
<p>The data pointer addresses the data (of some unknown type <code>T</code>) that the trait
|
||
object is storing, and the vtable pointer points to the vtable (‘virtual method
|
||
table’) corresponding to the implementation of <code>Foo</code> for <code>T</code>.</p>
|
||
<p>A vtable is essentially a struct of function pointers, pointing to the concrete
|
||
piece of machine code for each method in the implementation. A method call like
|
||
<code>trait_object.method()</code> will retrieve the correct pointer out of the vtable and
|
||
then do a dynamic call of it. For example:</p>
|
||
<pre><code class="language-rust,ignore">struct FooVtable {
|
||
destructor: fn(*mut ()),
|
||
size: usize,
|
||
align: usize,
|
||
method: fn(*const ()) -> String,
|
||
}
|
||
|
||
// u8:
|
||
|
||
fn call_method_on_u8(x: *const ()) -> String {
|
||
// the compiler guarantees that this function is only called
|
||
// with `x` pointing to a u8
|
||
let byte: &u8 = unsafe { &*(x as *const u8) };
|
||
|
||
byte.method()
|
||
}
|
||
|
||
static Foo_for_u8_vtable: FooVtable = FooVtable {
|
||
destructor: /* compiler magic */,
|
||
size: 1,
|
||
align: 1,
|
||
|
||
// cast to a function pointer
|
||
method: call_method_on_u8 as fn(*const ()) -> String,
|
||
};
|
||
|
||
|
||
// String:
|
||
|
||
fn call_method_on_String(x: *const ()) -> String {
|
||
// the compiler guarantees that this function is only called
|
||
// with `x` pointing to a String
|
||
let string: &String = unsafe { &*(x as *const String) };
|
||
|
||
string.method()
|
||
}
|
||
|
||
static Foo_for_String_vtable: FooVtable = FooVtable {
|
||
destructor: /* compiler magic */,
|
||
// values for a 64-bit computer, halve them for 32-bit ones
|
||
size: 24,
|
||
align: 8,
|
||
|
||
method: call_method_on_String as fn(*const ()) -> String,
|
||
};
|
||
</code></pre>
|
||
<p>The <code>destructor</code> field in each vtable points to a function that will clean up
|
||
any resources of the vtable’s type: for <code>u8</code> it is trivial, but for <code>String</code> it
|
||
will free the memory. This is necessary for owning trait objects like
|
||
<code>Box<Foo></code>, which need to clean-up both the <code>Box</code> allocation as well as the
|
||
internal type when they go out of scope. The <code>size</code> and <code>align</code> fields store
|
||
the size of the erased type, and its alignment requirements; these are
|
||
essentially unused at the moment since the information is embedded in the
|
||
destructor, but will be used in the future, as trait objects are progressively
|
||
made more flexible.</p>
|
||
<p>Suppose we’ve got some values that implement <code>Foo</code>. The explicit form of
|
||
construction and use of <code>Foo</code> trait objects might look a bit like (ignoring the
|
||
type mismatches: they’re all just pointers anyway):</p>
|
||
<pre><code class="language-rust,ignore">let a: String = "foo".to_string();
|
||
let x: u8 = 1;
|
||
|
||
// let b: &Foo = &a;
|
||
let b = TraitObject {
|
||
// store the data
|
||
data: &a,
|
||
// store the methods
|
||
vtable: &Foo_for_String_vtable
|
||
};
|
||
|
||
// let y: &Foo = x;
|
||
let y = TraitObject {
|
||
// store the data
|
||
data: &x,
|
||
// store the methods
|
||
vtable: &Foo_for_u8_vtable
|
||
};
|
||
|
||
// b.method();
|
||
(b.vtable.method)(b.data);
|
||
|
||
// y.method();
|
||
(y.vtable.method)(y.data);
|
||
</code></pre>
|
||
<h2>Object Safety</h2>
|
||
<p>Not every trait can be used to make a trait object. For example, vectors implement
|
||
<code>Clone</code>, but if we try to make a trait object:</p>
|
||
<pre><code class="language-ignore">let v = vec![1, 2, 3];
|
||
let o = &v as &Clone;
|
||
</code></pre>
|
||
<p>We get an error:</p>
|
||
<pre><code class="language-text">error: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038]
|
||
let o = &v as &Clone;
|
||
^~
|
||
note: the trait cannot require that `Self : Sized`
|
||
let o = &v as &Clone;
|
||
^~
|
||
</code></pre>
|
||
<p>The error says that <code>Clone</code> is not ‘object-safe’. Only traits that are
|
||
object-safe can be made into trait objects. A trait is object-safe if both of
|
||
these are true:</p>
|
||
<ul>
|
||
<li>the trait does not require that <code>Self: Sized</code></li>
|
||
<li>all of its methods are object-safe</li>
|
||
</ul>
|
||
<p>So what makes a method object-safe? Each method must require that <code>Self: Sized</code>
|
||
or all of the following:</p>
|
||
<ul>
|
||
<li>must not have any type parameters</li>
|
||
<li>must not use <code>Self</code></li>
|
||
</ul>
|
||
<p>Whew! As we can see, almost all of these rules talk about <code>Self</code>. A good intuition
|
||
is “except in special circumstances, if your trait’s method uses <code>Self</code>, it is not
|
||
object-safe.”</p>
|
||
|
||
</div>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
<a href="associated-types.html" class="mobile-nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="ufcs.html" class="mobile-nav-chapters next">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<a href="associated-types.html" class="nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="ufcs.html" class="nav-chapters next">
|
||
<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>
|
||
|
||
<script src="highlight.js"></script>
|
||
<script src="book.js"></script>
|
||
</body>
|
||
</html>
|