Files
book/traits.html
T

518 lines
24 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></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="primitive-rust.html"><strong>3.</strong> Primitive Rust</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" class="active"><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"><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>Traits</h1>
<p>A trait is a language feature that tells the Rust compiler about
functionality a type must provide.</p>
<p>Recall the <code>impl</code> keyword, used to call a function with <a href="method-syntax.html">method
syntax</a>:</p>
<pre><code class="language-rust">struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl Circle {
fn area(&amp;self) -&gt; f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
</code></pre>
<p>Traits are similar, except that we first define a trait with a method
signature, then implement the trait for a type. In this example, we implement the trait <code>HasArea</code> for <code>Circle</code>:</p>
<pre><code class="language-rust">struct Circle {
x: f64,
y: f64,
radius: f64,
}
trait HasArea {
fn area(&amp;self) -&gt; f64;
}
impl HasArea for Circle {
fn area(&amp;self) -&gt; f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
</code></pre>
<p>As you can see, the <code>trait</code> block looks very similar to the <code>impl</code> block,
but we don’t define a body, just a type signature. When we <code>impl</code> a trait,
we use <code>impl Trait for Item</code>, rather than just <code>impl Item</code>.</p>
<h2>Trait bounds on generic functions</h2>
<p>Traits are useful because they allow a type to make certain promises about its
behavior. Generic functions can exploit this to constrain, or <a href="glossary.html#bounds">bound</a>, the types they
accept. Consider this function, which does not compile:</p>
<pre><code class="language-rust,ignore">fn print_area&lt;T&gt;(shape: T) {
println!(&quot;This shape has an area of {}&quot;, shape.area());
}
</code></pre>
<p>Rust complains:</p>
<pre><code class="language-text">error: no method named `area` found for type `T` in the current scope
</code></pre>
<p>Because <code>T</code> can be any type, we can’t be sure that it implements the <code>area</code>
method. But we can add a trait bound to our generic <code>T</code>, ensuring
that it does:</p>
<pre><code class="language-rust"># trait HasArea {
# fn area(&amp;self) -&gt; f64;
# }
fn print_area&lt;T: HasArea&gt;(shape: T) {
println!(&quot;This shape has an area of {}&quot;, shape.area());
}
</code></pre>
<p>The syntax <code>&lt;T: HasArea&gt;</code> means “any type that implements the <code>HasArea</code> trait.”
Because traits define function type signatures, we can be sure that any type
which implements <code>HasArea</code> will have an <code>.area()</code> method.</p>
<p>Here’s an extended example of how this works:</p>
<pre><code class="language-rust">trait HasArea {
fn area(&amp;self) -&gt; f64;
}
struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl HasArea for Circle {
fn area(&amp;self) -&gt; f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
struct Square {
x: f64,
y: f64,
side: f64,
}
impl HasArea for Square {
fn area(&amp;self) -&gt; f64 {
self.side * self.side
}
}
fn print_area&lt;T: HasArea&gt;(shape: T) {
println!(&quot;This shape has an area of {}&quot;, shape.area());
}
fn main() {
let c = Circle {
x: 0.0f64,
y: 0.0f64,
radius: 1.0f64,
};
let s = Square {
x: 0.0f64,
y: 0.0f64,
side: 1.0f64,
};
print_area(c);
print_area(s);
}
</code></pre>
<p>This program outputs:</p>
<pre><code class="language-text">This shape has an area of 3.141593
This shape has an area of 1
</code></pre>
<p>As you can see, <code>print_area</code> is now generic, but also ensures that we have
passed in the correct types. If we pass in an incorrect type:</p>
<pre><code class="language-rust,ignore">print_area(5);
</code></pre>
<p>We get a compile-time error:</p>
<pre><code class="language-text">error: the trait `HasArea` is not implemented for the type `_` [E0277]
</code></pre>
<h2>Trait bounds on generic structs</h2>
<p>Your generic structs can also benefit from trait bounds. All you need to
do is append the bound when you declare type parameters. Here is a new
type <code>Rectangle&lt;T&gt;</code> and its operation <code>is_square()</code>:</p>
<pre><code class="language-rust">struct Rectangle&lt;T&gt; {
x: T,
y: T,
width: T,
height: T,
}
impl&lt;T: PartialEq&gt; Rectangle&lt;T&gt; {
fn is_square(&amp;self) -&gt; bool {
self.width == self.height
}
}
fn main() {
let mut r = Rectangle {
x: 0,
y: 0,
width: 47,
height: 47,
};
assert!(r.is_square());
r.height = 42;
assert!(!r.is_square());
}
</code></pre>
<p><code>is_square()</code> needs to check that the sides are equal, so the sides must be of
a type that implements the [<code>core::cmp::PartialEq</code>]<a href="../core/cmp/trait.PartialEq.html">PartialEq</a> trait:</p>
<pre><code class="language-ignore">impl&lt;T: PartialEq&gt; Rectangle&lt;T&gt; { ... }
</code></pre>
<p>Now, a rectangle can be defined in terms of any type that can be compared for
equality.</p>
<p>Here we defined a new struct <code>Rectangle</code> that accepts numbers of any
precision—really, objects of pretty much any type—as long as they can be
compared for equality. Could we do the same for our <code>HasArea</code> structs, <code>Square</code>
and <code>Circle</code>? Yes, but they need multiplication, and to work with that we need
to know more about <a href="operators-and-overloading.html">operator traits</a>.</p>
<h1>Rules for implementing traits</h1>
<p>So far, we’ve only added trait implementations to structs, but you can
implement a trait for any type. So technically, we <em>could</em> implement <code>HasArea</code>
for <code>i32</code>:</p>
<pre><code class="language-rust">trait HasArea {
fn area(&amp;self) -&gt; f64;
}
impl HasArea for i32 {
fn area(&amp;self) -&gt; f64 {
println!(&quot;this is silly&quot;);
*self as f64
}
}
5.area();
</code></pre>
<p>It is considered poor style to implement methods on such primitive types, even
though it is possible.</p>
<p>This may seem like the Wild West, but there are two restrictions around
implementing traits that prevent this from getting out of hand. The first is
that if the trait isn’t defined in your scope, it doesn’t apply. Here’s an
example: the standard library provides a [<code>Write</code>]<a href="../std/io/trait.Write.html">write</a> trait which adds
extra functionality to <code>File</code>s, for doing file I/O. By default, a <code>File</code>
won’t have its methods:</p>
<pre><code class="language-rust,ignore">let mut f = std::fs::File::open(&quot;foo.txt&quot;).expect(&quot;Couldn’t open foo.txt&quot;);
let buf = b&quot;whatever&quot;; // byte string literal. buf: &amp;[u8; 8]
let result = f.write(buf);
# result.unwrap(); // ignore the error
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">error: type `std::fs::File` does not implement any method in scope named `write`
let result = f.write(buf);
^~~~~~~~~~
</code></pre>
<p>We need to <code>use</code> the <code>Write</code> trait first:</p>
<pre><code class="language-rust,ignore">use std::io::Write;
let mut f = std::fs::File::open(&quot;foo.txt&quot;).expect(&quot;Couldn’t open foo.txt&quot;);
let buf = b&quot;whatever&quot;;
let result = f.write(buf);
# result.unwrap(); // ignore the error
</code></pre>
<p>This will compile without error.</p>
<p>This means that even if someone does something bad like add methods to <code>i32</code>,
it won’t affect you, unless you <code>use</code> that trait.</p>
<p>There’s one more restriction on implementing traits: either the trait, or the
type you’re writing the <code>impl</code> for, must be defined by you. So, we could
implement the <code>HasArea</code> type for <code>i32</code>, because <code>HasArea</code> is in our code. But
if we tried to implement <code>ToString</code>, a trait provided by Rust, for <code>i32</code>, we could
not, because neither the trait nor the type are in our code.</p>
<p>One last thing about traits: generic functions with a trait bound use
‘monomorphization’ (mono: one, morph: form), so they are statically dispatched.
What’s that mean? Check out the chapter on <a href="trait-objects.html">trait objects</a> for more details.</p>
<h1>Multiple trait bounds</h1>
<p>You’ve seen that you can bound a generic type parameter with a trait:</p>
<pre><code class="language-rust">fn foo&lt;T: Clone&gt;(x: T) {
x.clone();
}
</code></pre>
<p>If you need more than one bound, you can use <code>+</code>:</p>
<pre><code class="language-rust">use std::fmt::Debug;
fn foo&lt;T: Clone + Debug&gt;(x: T) {
x.clone();
println!(&quot;{:?}&quot;, x);
}
</code></pre>
<p><code>T</code> now needs to be both <code>Clone</code> as well as <code>Debug</code>.</p>
<h1>Where clause</h1>
<p>Writing functions with only a few generic types and a small number of trait
bounds isn’t too bad, but as the number increases, the syntax gets increasingly
awkward:</p>
<pre><code class="language-rust">use std::fmt::Debug;
fn foo&lt;T: Clone, K: Clone + Debug&gt;(x: T, y: K) {
x.clone();
y.clone();
println!(&quot;{:?}&quot;, y);
}
</code></pre>
<p>The name of the function is on the far left, and the parameter list is on the
far right. The bounds are getting in the way.</p>
<p>Rust has a solution, and it’s called a ‘<code>where</code> clause’:</p>
<pre><code class="language-rust">use std::fmt::Debug;
fn foo&lt;T: Clone, K: Clone + Debug&gt;(x: T, y: K) {
x.clone();
y.clone();
println!(&quot;{:?}&quot;, y);
}
fn bar&lt;T, K&gt;(x: T, y: K) where T: Clone, K: Clone + Debug {
x.clone();
y.clone();
println!(&quot;{:?}&quot;, y);
}
fn main() {
foo(&quot;Hello&quot;, &quot;world&quot;);
bar(&quot;Hello&quot;, &quot;world&quot;);
}
</code></pre>
<p><code>foo()</code> uses the syntax we showed earlier, and <code>bar()</code> uses a <code>where</code> clause.
All you need to do is leave off the bounds when defining your type parameters,
and then add <code>where</code> after the parameter list. For longer lists, whitespace can
be added:</p>
<pre><code class="language-rust">use std::fmt::Debug;
fn bar&lt;T, K&gt;(x: T, y: K)
where T: Clone,
K: Clone + Debug {
x.clone();
y.clone();
println!(&quot;{:?}&quot;, y);
}
</code></pre>
<p>This flexibility can add clarity in complex situations.</p>
<p><code>where</code> is also more powerful than the simpler syntax. For example:</p>
<pre><code class="language-rust">trait ConvertTo&lt;Output&gt; {
fn convert(&amp;self) -&gt; Output;
}
impl ConvertTo&lt;i64&gt; for i32 {
fn convert(&amp;self) -&gt; i64 { *self as i64 }
}
// can be called with T == i32
fn normal&lt;T: ConvertTo&lt;i64&gt;&gt;(x: &amp;T) -&gt; i64 {
x.convert()
}
// can be called with T == i64
fn inverse&lt;T&gt;() -&gt; T
// this is using ConvertTo as if it were &quot;ConvertTo&lt;i64&gt;&quot;
where i32: ConvertTo&lt;T&gt; {
42.convert()
}
</code></pre>
<p>This shows off the additional feature of <code>where</code> clauses: they allow bounds
on the left-hand side not only of type parameters <code>T</code>, but also of types (<code>i32</code> in this case). In this example, <code>i32</code> must implement
<code>ConvertTo&lt;T&gt;</code>. Rather than defining what <code>i32</code> is (since that's obvious), the
<code>where</code> clause here constrains <code>T</code>.</p>
<h1>Default methods</h1>
<p>A default method can be added to a trait definition if it is already known how a typical implementor will define a method. For example, <code>is_invalid()</code> is defined as the opposite of <code>is_valid()</code>:</p>
<pre><code class="language-rust">trait Foo {
fn is_valid(&amp;self) -&gt; bool;
fn is_invalid(&amp;self) -&gt; bool { !self.is_valid() }
}
</code></pre>
<p>Implementors of the <code>Foo</code> trait need to implement <code>is_valid()</code> but not <code>is_invalid()</code> due to the added default behavior. This default behavior can still be overridden as in:</p>
<pre><code class="language-rust"># trait Foo {
# fn is_valid(&amp;self) -&gt; bool;
#
# fn is_invalid(&amp;self) -&gt; bool { !self.is_valid() }
# }
struct UseDefault;
impl Foo for UseDefault {
fn is_valid(&amp;self) -&gt; bool {
println!(&quot;Called UseDefault.is_valid.&quot;);
true
}
}
struct OverrideDefault;
impl Foo for OverrideDefault {
fn is_valid(&amp;self) -&gt; bool {
println!(&quot;Called OverrideDefault.is_valid.&quot;);
true
}
fn is_invalid(&amp;self) -&gt; bool {
println!(&quot;Called OverrideDefault.is_invalid!&quot;);
true // overrides the expected value of is_invalid()
}
}
let default = UseDefault;
assert!(!default.is_invalid()); // prints &quot;Called UseDefault.is_valid.&quot;
let over = OverrideDefault;
assert!(over.is_invalid()); // prints &quot;Called OverrideDefault.is_invalid!&quot;
</code></pre>
<h1>Inheritance</h1>
<p>Sometimes, implementing a trait requires implementing another trait:</p>
<pre><code class="language-rust">trait Foo {
fn foo(&amp;self);
}
trait FooBar : Foo {
fn foobar(&amp;self);
}
</code></pre>
<p>Implementors of <code>FooBar</code> must also implement <code>Foo</code>, like this:</p>
<pre><code class="language-rust"># trait Foo {
# fn foo(&amp;self);
# }
# trait FooBar : Foo {
# fn foobar(&amp;self);
# }
struct Baz;
impl Foo for Baz {
fn foo(&amp;self) { println!(&quot;foo&quot;); }
}
impl FooBar for Baz {
fn foobar(&amp;self) { println!(&quot;foobar&quot;); }
}
</code></pre>
<p>If we forget to implement <code>Foo</code>, Rust will tell us:</p>
<pre><code class="language-text">error: the trait `main::Foo` is not implemented for the type `main::Baz` [E0277]
</code></pre>
<h1>Deriving</h1>
<p>Implementing traits like <code>Debug</code> and <code>Default</code> repeatedly can become
quite tedious. For that reason, Rust provides an <a href="attributes.html">attribute</a> that
allows you to let Rust automatically implement traits for you:</p>
<pre><code class="language-rust">#[derive(Debug)]
struct Foo;
fn main() {
println!(&quot;{:?}&quot;, Foo);
}
</code></pre>
<p>However, deriving is limited to a certain set of traits:</p>
<ul>
<li>[<code>Clone</code>](../core/clone/trait.Clone.html)</li>
<li>[<code>Copy</code>](../core/marker/trait.Copy.html)</li>
<li>[<code>Debug</code>](../core/fmt/trait.Debug.html)</li>
<li>[<code>Default</code>](../core/default/trait.Default.html)</li>
<li>[<code>Eq</code>](../core/cmp/trait.Eq.html)</li>
<li>[<code>Hash</code>](../core/hash/trait.Hash.html)</li>
<li>[<code>Ord</code>](../core/cmp/trait.Ord.html)</li>
<li>[<code>PartialEq</code>](../core/cmp/trait.PartialEq.html)</li>
<li>[<code>PartialOrd</code>](../core/cmp/trait.PartialOrd.html)</li>
</ul>
</div>
<!-- Mobile navigation buttons -->
<a href="hashmap.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="closures.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="hashmap.html" class="nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="closures.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>