711 lines
38 KiB
HTML
711 lines
38 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>Advanced Traits</title>
|
||
</head>
|
||
<body>
|
||
<h2 id="advanced-traits"><a class="header" href="#advanced-traits">Advanced Traits</a></h2>
|
||
<p>We first covered traits in the <a href="../ch10/ch10-02-traits.html">“Defining Shared Behavior with
|
||
Traits”</a><!-- ignore --> section in Chapter 10, but we didn’t discuss
|
||
the more advanced details. Now that you know more about Rust, we can get into
|
||
the nitty-gritty.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="specifying-placeholder-types-in-trait-definitions-with-associated-types"></a>
|
||
<a id="associated-types"></a></p>
|
||
<h3 id="defining-traits-with-associated-types"><a class="header" href="#defining-traits-with-associated-types">Defining Traits with Associated Types</a></h3>
|
||
<p><em>Associated types</em> connect a type placeholder with a trait such that the trait
|
||
method definitions can use these placeholder types in their signatures. The
|
||
implementor of a trait will specify the concrete type to be used instead of the
|
||
placeholder type for the particular implementation. That way, we can define a
|
||
trait that uses some types without needing to know exactly what those types are
|
||
until the trait is implemented.</p>
|
||
<p>We’ve described most of the advanced features in this chapter as being rarely
|
||
needed. Associated types are somewhere in the middle: They’re used more rarely
|
||
than features explained in the rest of the book but more commonly than many of
|
||
the other features discussed in this chapter.</p>
|
||
<p>One example of a trait with an associated type is the <code>Iterator</code> trait that the
|
||
standard library provides. The associated type is named <code>Item</code> and stands in
|
||
for the type of the values the type implementing the <code>Iterator</code> trait is
|
||
iterating over. The definition of the <code>Iterator</code> trait is as shown in Listing
|
||
20-13.</p>
|
||
<figure class="listing" id="listing-20-13">
|
||
<pre><code class="language-rust noplayground">pub trait Iterator {
|
||
type Item;
|
||
|
||
fn next(&mut self) -> Option<Self::Item>;
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-13">Listing 20-13</a>: The definition of the <code>Iterator</code> trait that has an associated type <code>Item</code></figcaption>
|
||
</figure>
|
||
<p>The type <code>Item</code> is a placeholder, and the <code>next</code> method’s definition shows that
|
||
it will return values of type <code>Option<Self::Item></code>. Implementors of the
|
||
<code>Iterator</code> trait will specify the concrete type for <code>Item</code>, and the <code>next</code>
|
||
method will return an <code>Option</code> containing a value of that concrete type.</p>
|
||
<p>Associated types might seem like a similar concept to generics, in that the
|
||
latter allow us to define a function without specifying what types it can
|
||
handle. To examine the difference between the two concepts, we’ll look at an
|
||
implementation of the <code>Iterator</code> trait on a type named <code>Counter</code> that specifies
|
||
the <code>Item</code> type is <code>u32</code>:</p>
|
||
<figure class="listing">
|
||
<span class="file-name">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust ignore"><span class="boring">struct Counter {
|
||
</span><span class="boring"> count: u32,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Counter {
|
||
</span><span class="boring"> fn new() -> Counter {
|
||
</span><span class="boring"> Counter { count: 0 }
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>impl Iterator for Counter {
|
||
type Item = u32;
|
||
|
||
fn next(&mut self) -> Option<Self::Item> {
|
||
// --snip--
|
||
<span class="boring"> if self.count < 5 {
|
||
</span><span class="boring"> self.count += 1;
|
||
</span><span class="boring"> Some(self.count)
|
||
</span><span class="boring"> } else {
|
||
</span><span class="boring"> None
|
||
</span><span class="boring"> }
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}</span></code></pre>
|
||
</figure>
|
||
<p>This syntax seems comparable to that of generics. So, why not just define the
|
||
<code>Iterator</code> trait with generics, as shown in Listing 20-14?</p>
|
||
<figure class="listing" id="listing-20-14">
|
||
<pre><code class="language-rust noplayground">pub trait Iterator<T> {
|
||
fn next(&mut self) -> Option<T>;
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-14">Listing 20-14</a>: A hypothetical definition of the <code>Iterator</code> trait using generics</figcaption>
|
||
</figure>
|
||
<p>The difference is that when using generics, as in Listing 20-14, we must
|
||
annotate the types in each implementation; because we can also implement
|
||
<code>Iterator<String> for Counter</code> or any other type, we could have multiple
|
||
implementations of <code>Iterator</code> for <code>Counter</code>. In other words, when a trait has a
|
||
generic parameter, it can be implemented for a type multiple times, changing
|
||
the concrete types of the generic type parameters each time. When we use the
|
||
<code>next</code> method on <code>Counter</code>, we would have to provide type annotations to
|
||
indicate which implementation of <code>Iterator</code> we want to use.</p>
|
||
<p>With associated types, we don’t need to annotate types, because we can’t
|
||
implement a trait on a type multiple times. In Listing 20-13 with the
|
||
definition that uses associated types, we can choose what the type of <code>Item</code>
|
||
will be only once because there can be only one <code>impl Iterator for Counter</code>. We
|
||
don’t have to specify that we want an iterator of <code>u32</code> values everywhere we
|
||
call <code>next</code> on <code>Counter</code>.</p>
|
||
<p>Associated types also become part of the trait’s contract: Implementors of the
|
||
trait must provide a type to stand in for the associated type placeholder.
|
||
Associated types often have a name that describes how the type will be used,
|
||
and documenting the associated type in the API documentation is a good practice.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="default-generic-type-parameters-and-operator-overloading"></a></p>
|
||
<h3 id="using-default-generic-parameters-and-operator-overloading"><a class="header" href="#using-default-generic-parameters-and-operator-overloading">Using Default Generic Parameters and Operator Overloading</a></h3>
|
||
<p>When we use generic type parameters, we can specify a default concrete type for
|
||
the generic type. This eliminates the need for implementors of the trait to
|
||
specify a concrete type if the default type works. You specify a default type
|
||
when declaring a generic type with the <code><PlaceholderType=ConcreteType></code> syntax.</p>
|
||
<p>A great example of a situation where this technique is useful is with <em>operator
|
||
overloading</em>, in which you customize the behavior of an operator (such as <code>+</code>)
|
||
in particular situations.</p>
|
||
<p>Rust doesn’t allow you to create your own operators or overload arbitrary
|
||
operators. But you can overload the operations and corresponding traits listed
|
||
in <code>std::ops</code> by implementing the traits associated with the operator. For
|
||
example, in Listing 20-15, we overload the <code>+</code> operator to add two <code>Point</code>
|
||
instances together. We do this by implementing the <code>Add</code> trait on a <code>Point</code>
|
||
struct.</p>
|
||
<figure class="listing" id="listing-20-15">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">use std::ops::Add;
|
||
|
||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||
struct Point {
|
||
x: i32,
|
||
y: i32,
|
||
}
|
||
|
||
impl Add for Point {
|
||
type Output = Point;
|
||
|
||
fn add(self, other: Point) -> Point {
|
||
Point {
|
||
x: self.x + other.x,
|
||
y: self.y + other.y,
|
||
}
|
||
}
|
||
}
|
||
|
||
fn main() {
|
||
assert_eq!(
|
||
Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
|
||
Point { x: 3, y: 3 }
|
||
);
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-15">Listing 20-15</a>: Implementing the <code>Add</code> trait to overload the <code>+</code> operator for <code>Point</code> instances</figcaption>
|
||
</figure>
|
||
<p>The <code>add</code> method adds the <code>x</code> values of two <code>Point</code> instances and the <code>y</code>
|
||
values of two <code>Point</code> instances to create a new <code>Point</code>. The <code>Add</code> trait has an
|
||
associated type named <code>Output</code> that determines the type returned from the <code>add</code>
|
||
method.</p>
|
||
<p>The default generic type in this code is within the <code>Add</code> trait. Here is its
|
||
definition:</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>trait Add<Rhs=Self> {
|
||
type Output;
|
||
|
||
fn add(self, rhs: Rhs) -> Self::Output;
|
||
}
|
||
<span class="boring">}</span></code></pre>
|
||
<p>This code should look generally familiar: a trait with one method and an
|
||
associated type. The new part is <code>Rhs=Self</code>: This syntax is called <em>default
|
||
type parameters</em>. The <code>Rhs</code> generic type parameter (short for “right-hand
|
||
side”) defines the type of the <code>rhs</code> parameter in the <code>add</code> method. If we don’t
|
||
specify a concrete type for <code>Rhs</code> when we implement the <code>Add</code> trait, the type
|
||
of <code>Rhs</code> will default to <code>Self</code>, which will be the type we’re implementing
|
||
<code>Add</code> on.</p>
|
||
<p>When we implemented <code>Add</code> for <code>Point</code>, we used the default for <code>Rhs</code> because we
|
||
wanted to add two <code>Point</code> instances. Let’s look at an example of implementing
|
||
the <code>Add</code> trait where we want to customize the <code>Rhs</code> type rather than using the
|
||
default.</p>
|
||
<p>We have two structs, <code>Millimeters</code> and <code>Meters</code>, holding values in different
|
||
units. This thin wrapping of an existing type in another struct is known as the
|
||
<em>newtype pattern</em>, which we describe in more detail in the <a href="ch20-02-advanced-traits.html#implementing-external-traits-with-the-newtype-pattern">“Implementing
|
||
External Traits with the Newtype Pattern”</a><!-- ignore --> section. We
|
||
want to add values in millimeters to values in meters and have the
|
||
implementation of <code>Add</code> do the conversion correctly. We can implement <code>Add</code> for
|
||
<code>Millimeters</code> with <code>Meters</code> as the <code>Rhs</code>, as shown in Listing 20-16.</p>
|
||
<figure class="listing" id="listing-20-16">
|
||
<span class="file-name">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust noplayground">use std::ops::Add;
|
||
|
||
struct Millimeters(u32);
|
||
struct Meters(u32);
|
||
|
||
impl Add<Meters> for Millimeters {
|
||
type Output = Millimeters;
|
||
|
||
fn add(self, other: Meters) -> Millimeters {
|
||
Millimeters(self.0 + (other.0 * 1000))
|
||
}
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-16">Listing 20-16</a>: Implementing the <code>Add</code> trait on <code>Millimeters</code> to add <code>Millimeters</code> and <code>Meters</code></figcaption>
|
||
</figure>
|
||
<p>To add <code>Millimeters</code> and <code>Meters</code>, we specify <code>impl Add<Meters></code> to set the
|
||
value of the <code>Rhs</code> type parameter instead of using the default of <code>Self</code>.</p>
|
||
<p>You’ll use default type parameters in two main ways:</p>
|
||
<ol>
|
||
<li>To extend a type without breaking existing code</li>
|
||
<li>To allow customization in specific cases most users won’t need</li>
|
||
</ol>
|
||
<p>The standard library’s <code>Add</code> trait is an example of the second purpose:
|
||
Usually, you’ll add two like types, but the <code>Add</code> trait provides the ability to
|
||
customize beyond that. Using a default type parameter in the <code>Add</code> trait
|
||
definition means you don’t have to specify the extra parameter most of the
|
||
time. In other words, a bit of implementation boilerplate isn’t needed, making
|
||
it easier to use the trait.</p>
|
||
<p>The first purpose is similar to the second but in reverse: If you want to add a
|
||
type parameter to an existing trait, you can give it a default to allow
|
||
extension of the functionality of the trait without breaking the existing
|
||
implementation code.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name"></a>
|
||
<a id="disambiguating-between-methods-with-the-same-name"></a></p>
|
||
<h3 id="disambiguating-between-identically-named-methods"><a class="header" href="#disambiguating-between-identically-named-methods">Disambiguating Between Identically Named Methods</a></h3>
|
||
<p>Nothing in Rust prevents a trait from having a method with the same name as
|
||
another trait’s method, nor does Rust prevent you from implementing both traits
|
||
on one type. It’s also possible to implement a method directly on the type with
|
||
the same name as methods from traits.</p>
|
||
<p>When calling methods with the same name, you’ll need to tell Rust which one you
|
||
want to use. Consider the code in Listing 20-17 where we’ve defined two traits,
|
||
<code>Pilot</code> and <code>Wizard</code>, that both have a method called <code>fly</code>. We then implement
|
||
both traits on a type <code>Human</code> that already has a method named <code>fly</code> implemented
|
||
on it. Each <code>fly</code> method does something different.</p>
|
||
<figure class="listing" id="listing-20-17">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">trait Pilot {
|
||
fn fly(&self);
|
||
}
|
||
|
||
trait Wizard {
|
||
fn fly(&self);
|
||
}
|
||
|
||
struct Human;
|
||
|
||
impl Pilot for Human {
|
||
fn fly(&self) {
|
||
println!("This is your captain speaking.");
|
||
}
|
||
}
|
||
|
||
impl Wizard for Human {
|
||
fn fly(&self) {
|
||
println!("Up!");
|
||
}
|
||
}
|
||
|
||
impl Human {
|
||
fn fly(&self) {
|
||
println!("*waving arms furiously*");
|
||
}
|
||
}
|
||
<span class="boring">
|
||
</span><span class="boring">fn main() {}</span></code></pre>
|
||
<figcaption><a href="#listing-20-17">Listing 20-17</a>: Two traits are defined to have a <code>fly</code> method and are implemented on the <code>Human</code> type, and a <code>fly</code> method is implemented on <code>Human</code> directly.</figcaption>
|
||
</figure>
|
||
<p>When we call <code>fly</code> on an instance of <code>Human</code>, the compiler defaults to calling
|
||
the method that is directly implemented on the type, as shown in Listing 20-18.</p>
|
||
<figure class="listing" id="listing-20-18">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">trait Pilot {
|
||
</span><span class="boring"> fn fly(&self);
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">trait Wizard {
|
||
</span><span class="boring"> fn fly(&self);
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Human;
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Pilot for Human {
|
||
</span><span class="boring"> fn fly(&self) {
|
||
</span><span class="boring"> println!("This is your captain speaking.");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Wizard for Human {
|
||
</span><span class="boring"> fn fly(&self) {
|
||
</span><span class="boring"> println!("Up!");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Human {
|
||
</span><span class="boring"> fn fly(&self) {
|
||
</span><span class="boring"> println!("*waving arms furiously*");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
let person = Human;
|
||
person.fly();
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-18">Listing 20-18</a>: Calling <code>fly</code> on an instance of <code>Human</code></figcaption>
|
||
</figure>
|
||
<p>Running this code will print <code>*waving arms furiously*</code>, showing that Rust
|
||
called the <code>fly</code> method implemented on <code>Human</code> directly.</p>
|
||
<p>To call the <code>fly</code> methods from either the <code>Pilot</code> trait or the <code>Wizard</code> trait,
|
||
we need to use more explicit syntax to specify which <code>fly</code> method we mean.
|
||
Listing 20-19 demonstrates this syntax.</p>
|
||
<figure class="listing" id="listing-20-19">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">trait Pilot {
|
||
</span><span class="boring"> fn fly(&self);
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">trait Wizard {
|
||
</span><span class="boring"> fn fly(&self);
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Human;
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Pilot for Human {
|
||
</span><span class="boring"> fn fly(&self) {
|
||
</span><span class="boring"> println!("This is your captain speaking.");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Wizard for Human {
|
||
</span><span class="boring"> fn fly(&self) {
|
||
</span><span class="boring"> println!("Up!");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Human {
|
||
</span><span class="boring"> fn fly(&self) {
|
||
</span><span class="boring"> println!("*waving arms furiously*");
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
let person = Human;
|
||
Pilot::fly(&person);
|
||
Wizard::fly(&person);
|
||
person.fly();
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-19">Listing 20-19</a>: Specifying which trait’s <code>fly</code> method we want to call</figcaption>
|
||
</figure>
|
||
<p>Specifying the trait name before the method name clarifies to Rust which
|
||
implementation of <code>fly</code> we want to call. We could also write
|
||
<code>Human::fly(&person)</code>, which is equivalent to the <code>person.fly()</code> that we used
|
||
in Listing 20-19, but this is a bit longer to write if we don’t need to
|
||
disambiguate.</p>
|
||
<p>Running this code prints the following:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling traits-example v0.1.0 (file:///projects/traits-example)
|
||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.46s
|
||
Running `target/debug/traits-example`
|
||
This is your captain speaking.
|
||
Up!
|
||
*waving arms furiously*
|
||
</code></pre>
|
||
<p>Because the <code>fly</code> method takes a <code>self</code> parameter, if we had two <em>types</em> that
|
||
both implement one <em>trait</em>, Rust could figure out which implementation of a
|
||
trait to use based on the type of <code>self</code>.</p>
|
||
<p>However, associated functions that are not methods don’t have a <code>self</code>
|
||
parameter. When there are multiple types or traits that define non-method
|
||
functions with the same function name, Rust doesn’t always know which type you
|
||
mean unless you use fully qualified syntax. For example, in Listing 20-20, we
|
||
create a trait for an animal shelter that wants to name all baby dogs Spot. We
|
||
make an <code>Animal</code> trait with an associated non-method function <code>baby_name</code>. The
|
||
<code>Animal</code> trait is implemented for the struct <code>Dog</code>, on which we also provide an
|
||
associated non-method function <code>baby_name</code> directly.</p>
|
||
<figure class="listing" id="listing-20-20">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">trait Animal {
|
||
fn baby_name() -> String;
|
||
}
|
||
|
||
struct Dog;
|
||
|
||
impl Dog {
|
||
fn baby_name() -> String {
|
||
String::from("Spot")
|
||
}
|
||
}
|
||
|
||
impl Animal for Dog {
|
||
fn baby_name() -> String {
|
||
String::from("puppy")
|
||
}
|
||
}
|
||
|
||
fn main() {
|
||
println!("A baby dog is called a {}", Dog::baby_name());
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-20">Listing 20-20</a>: A trait with an associated function and a type with an associated function of the same name that also implements the trait</figcaption>
|
||
</figure>
|
||
<p>We implement the code for naming all puppies Spot in the <code>baby_name</code> associated
|
||
function that is defined on <code>Dog</code>. The <code>Dog</code> type also implements the trait
|
||
<code>Animal</code>, which describes characteristics that all animals have. Baby dogs are
|
||
called puppies, and that is expressed in the implementation of the <code>Animal</code>
|
||
trait on <code>Dog</code> in the <code>baby_name</code> function associated with the <code>Animal</code> trait.</p>
|
||
<p>In <code>main</code>, we call the <code>Dog::baby_name</code> function, which calls the associated
|
||
function defined on <code>Dog</code> directly. This code prints the following:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling traits-example v0.1.0 (file:///projects/traits-example)
|
||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.54s
|
||
Running `target/debug/traits-example`
|
||
A baby dog is called a Spot
|
||
</code></pre>
|
||
<p>This output isn’t what we wanted. We want to call the <code>baby_name</code> function that
|
||
is part of the <code>Animal</code> trait that we implemented on <code>Dog</code> so that the code
|
||
prints <code>A baby dog is called a puppy</code>. The technique of specifying the trait
|
||
name that we used in Listing 20-19 doesn’t help here; if we change <code>main</code> to
|
||
the code in Listing 20-21, we’ll get a compilation error.</p>
|
||
<figure class="listing" id="listing-20-21">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore does_not_compile"><span class="boring">trait Animal {
|
||
</span><span class="boring"> fn baby_name() -> String;
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Dog;
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Dog {
|
||
</span><span class="boring"> fn baby_name() -> String {
|
||
</span><span class="boring"> String::from("Spot")
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Animal for Dog {
|
||
</span><span class="boring"> fn baby_name() -> String {
|
||
</span><span class="boring"> String::from("puppy")
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
println!("A baby dog is called a {}", Animal::baby_name());
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-21">Listing 20-21</a>: Attempting to call the <code>baby_name</code> function from the <code>Animal</code> trait, but Rust doesn’t know which implementation to use</figcaption>
|
||
</figure>
|
||
<p>Because <code>Animal::baby_name</code> doesn’t have a <code>self</code> parameter, and there could be
|
||
other types that implement the <code>Animal</code> trait, Rust can’t figure out which
|
||
implementation of <code>Animal::baby_name</code> we want. We’ll get this compiler error:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling traits-example v0.1.0 (file:///projects/traits-example)
|
||
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
|
||
--> src/main.rs:20:43
|
||
|
|
||
2 | fn baby_name() -> String;
|
||
| ------------------------- `Animal::baby_name` defined here
|
||
...
|
||
20 | println!("A baby dog is called a {}", Animal::baby_name());
|
||
| ^^^^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
||
|
|
||
help: use the fully-qualified path to the only available implementation
|
||
|
|
||
20 | println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
|
||
| +++++++ +
|
||
|
||
For more information about this error, try `rustc --explain E0790`.
|
||
error: could not compile `traits-example` (bin "traits-example") due to 1 previous error
|
||
</code></pre>
|
||
<p>To disambiguate and tell Rust that we want to use the implementation of
|
||
<code>Animal</code> for <code>Dog</code> as opposed to the implementation of <code>Animal</code> for some other
|
||
type, we need to use fully qualified syntax. Listing 20-22 demonstrates how to
|
||
use fully qualified syntax.</p>
|
||
<figure class="listing" id="listing-20-22">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">trait Animal {
|
||
</span><span class="boring"> fn baby_name() -> String;
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Dog;
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Dog {
|
||
</span><span class="boring"> fn baby_name() -> String {
|
||
</span><span class="boring"> String::from("Spot")
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl Animal for Dog {
|
||
</span><span class="boring"> fn baby_name() -> String {
|
||
</span><span class="boring"> String::from("puppy")
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn main() {
|
||
println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-22">Listing 20-22</a>: Using fully qualified syntax to specify that we want to call the <code>baby_name</code> function from the <code>Animal</code> trait as implemented on <code>Dog</code></figcaption>
|
||
</figure>
|
||
<p>We’re providing Rust with a type annotation within the angle brackets, which
|
||
indicates we want to call the <code>baby_name</code> method from the <code>Animal</code> trait as
|
||
implemented on <code>Dog</code> by saying that we want to treat the <code>Dog</code> type as an
|
||
<code>Animal</code> for this function call. This code will now print what we want:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling traits-example v0.1.0 (file:///projects/traits-example)
|
||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
|
||
Running `target/debug/traits-example`
|
||
A baby dog is called a puppy
|
||
</code></pre>
|
||
<p>In general, fully qualified syntax is defined as follows:</p>
|
||
<pre><code class="language-rust ignore"><Type as Trait>::function(receiver_if_method, next_arg, ...);</code></pre>
|
||
<p>For associated functions that aren’t methods, there would not be a <code>receiver</code>:
|
||
There would only be the list of other arguments. You could use fully qualified
|
||
syntax everywhere that you call functions or methods. However, you’re allowed
|
||
to omit any part of this syntax that Rust can figure out from other information
|
||
in the program. You only need to use this more verbose syntax in cases where
|
||
there are multiple implementations that use the same name and Rust needs help
|
||
to identify which implementation you want to call.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="using-supertraits-to-require-one-traits-functionality-within-another-trait"></a></p>
|
||
<h3 id="using-supertraits"><a class="header" href="#using-supertraits">Using Supertraits</a></h3>
|
||
<p>Sometimes you might write a trait definition that depends on another trait: For
|
||
a type to implement the first trait, you want to require that type to also
|
||
implement the second trait. You would do this so that your trait definition can
|
||
make use of the associated items of the second trait. The trait your trait
|
||
definition is relying on is called a <em>supertrait</em> of your trait.</p>
|
||
<p>For example, let’s say we want to make an <code>OutlinePrint</code> trait with an
|
||
<code>outline_print</code> method that will print a given value formatted so that it’s
|
||
framed in asterisks. That is, given a <code>Point</code> struct that implements the
|
||
standard library trait <code>Display</code> to result in <code>(x, y)</code>, when we call
|
||
<code>outline_print</code> on a <code>Point</code> instance that has <code>1</code> for <code>x</code> and <code>3</code> for <code>y</code>, it
|
||
should print the following:</p>
|
||
<pre><code class="language-text">**********
|
||
* *
|
||
* (1, 3) *
|
||
* *
|
||
**********
|
||
</code></pre>
|
||
<p>In the implementation of the <code>outline_print</code> method, we want to use the
|
||
<code>Display</code> trait’s functionality. Therefore, we need to specify that the
|
||
<code>OutlinePrint</code> trait will work only for types that also implement <code>Display</code> and
|
||
provide the functionality that <code>OutlinePrint</code> needs. We can do that in the
|
||
trait definition by specifying <code>OutlinePrint: Display</code>. This technique is
|
||
similar to adding a trait bound to the trait. Listing 20-23 shows an
|
||
implementation of the <code>OutlinePrint</code> trait.</p>
|
||
<figure class="listing" id="listing-20-23">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">use std::fmt;
|
||
|
||
trait OutlinePrint: fmt::Display {
|
||
fn outline_print(&self) {
|
||
let output = self.to_string();
|
||
let len = output.len();
|
||
println!("{}", "*".repeat(len + 4));
|
||
println!("*{}*", " ".repeat(len + 2));
|
||
println!("* {output} *");
|
||
println!("*{}*", " ".repeat(len + 2));
|
||
println!("{}", "*".repeat(len + 4));
|
||
}
|
||
}
|
||
<span class="boring">
|
||
</span><span class="boring">fn main() {}</span></code></pre>
|
||
<figcaption><a href="#listing-20-23">Listing 20-23</a>: Implementing the <code>OutlinePrint</code> trait that requires the functionality from <code>Display</code></figcaption>
|
||
</figure>
|
||
<p>Because we’ve specified that <code>OutlinePrint</code> requires the <code>Display</code> trait, we
|
||
can use the <code>to_string</code> function that is automatically implemented for any type
|
||
that implements <code>Display</code>. If we tried to use <code>to_string</code> without adding a
|
||
colon and specifying the <code>Display</code> trait after the trait name, we’d get an
|
||
error saying that no method named <code>to_string</code> was found for the type <code>&Self</code> in
|
||
the current scope.</p>
|
||
<p>Let’s see what happens when we try to implement <code>OutlinePrint</code> on a type that
|
||
doesn’t implement <code>Display</code>, such as the <code>Point</code> struct:</p>
|
||
<figure class="listing">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::fmt;
|
||
</span><span class="boring">
|
||
</span><span class="boring">trait OutlinePrint: fmt::Display {
|
||
</span><span class="boring"> fn outline_print(&self) {
|
||
</span><span class="boring"> let output = self.to_string();
|
||
</span><span class="boring"> let len = output.len();
|
||
</span><span class="boring"> println!("{}", "*".repeat(len + 4));
|
||
</span><span class="boring"> println!("*{}*", " ".repeat(len + 2));
|
||
</span><span class="boring"> println!("* {output} *");
|
||
</span><span class="boring"> println!("*{}*", " ".repeat(len + 2));
|
||
</span><span class="boring"> println!("{}", "*".repeat(len + 4));
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>struct Point {
|
||
x: i32,
|
||
y: i32,
|
||
}
|
||
|
||
impl OutlinePrint for Point {}
|
||
<span class="boring">
|
||
</span><span class="boring">fn main() {
|
||
</span><span class="boring"> let p = Point { x: 1, y: 3 };
|
||
</span><span class="boring"> p.outline_print();
|
||
</span><span class="boring">}</span></code></pre>
|
||
</figure>
|
||
<p>We get an error saying that <code>Display</code> is required but not implemented:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling traits-example v0.1.0 (file:///projects/traits-example)
|
||
error[E0277]: `Point` doesn't implement `std::fmt::Display`
|
||
--> src/main.rs:20:23
|
||
|
|
||
20 | impl OutlinePrint for Point {}
|
||
| ^^^^^ the trait `std::fmt::Display` is not implemented for `Point`
|
||
|
|
||
note: required by a bound in `OutlinePrint`
|
||
--> src/main.rs:3:21
|
||
|
|
||
3 | trait OutlinePrint: fmt::Display {
|
||
| ^^^^^^^^^^^^ required by this bound in `OutlinePrint`
|
||
|
||
error[E0277]: `Point` doesn't implement `std::fmt::Display`
|
||
--> src/main.rs:24:7
|
||
|
|
||
24 | p.outline_print();
|
||
| ^^^^^^^^^^^^^ the trait `std::fmt::Display` is not implemented for `Point`
|
||
|
|
||
note: required by a bound in `OutlinePrint::outline_print`
|
||
--> src/main.rs:3:21
|
||
|
|
||
3 | trait OutlinePrint: fmt::Display {
|
||
| ^^^^^^^^^^^^ required by this bound in `OutlinePrint::outline_print`
|
||
4 | fn outline_print(&self) {
|
||
| ------------- required by a bound in this associated function
|
||
|
||
For more information about this error, try `rustc --explain E0277`.
|
||
error: could not compile `traits-example` (bin "traits-example") due to 2 previous errors
|
||
</code></pre>
|
||
<p>To fix this, we implement <code>Display</code> on <code>Point</code> and satisfy the constraint that
|
||
<code>OutlinePrint</code> requires, like so:</p>
|
||
<figure class="listing">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">trait OutlinePrint: fmt::Display {
|
||
</span><span class="boring"> fn outline_print(&self) {
|
||
</span><span class="boring"> let output = self.to_string();
|
||
</span><span class="boring"> let len = output.len();
|
||
</span><span class="boring"> println!("{}", "*".repeat(len + 4));
|
||
</span><span class="boring"> println!("*{}*", " ".repeat(len + 2));
|
||
</span><span class="boring"> println!("* {output} *");
|
||
</span><span class="boring"> println!("*{}*", " ".repeat(len + 2));
|
||
</span><span class="boring"> println!("{}", "*".repeat(len + 4));
|
||
</span><span class="boring"> }
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">struct Point {
|
||
</span><span class="boring"> x: i32,
|
||
</span><span class="boring"> y: i32,
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span><span class="boring">impl OutlinePrint for Point {}
|
||
</span><span class="boring">
|
||
</span>use std::fmt;
|
||
|
||
impl fmt::Display for Point {
|
||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||
write!(f, "({}, {})", self.x, self.y)
|
||
}
|
||
}
|
||
<span class="boring">
|
||
</span><span class="boring">fn main() {
|
||
</span><span class="boring"> let p = Point { x: 1, y: 3 };
|
||
</span><span class="boring"> p.outline_print();
|
||
</span><span class="boring">}</span></code></pre>
|
||
</figure>
|
||
<p>Then, implementing the <code>OutlinePrint</code> trait on <code>Point</code> will compile
|
||
successfully, and we can call <code>outline_print</code> on a <code>Point</code> instance to display
|
||
it within an outline of asterisks.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="using-the-newtype-pattern-to-implement-external-traits-on-external-types"></a>
|
||
<a id="using-the-newtype-pattern-to-implement-external-traits"></a></p>
|
||
<h3 id="implementing-external-traits-with-the-newtype-pattern"><a class="header" href="#implementing-external-traits-with-the-newtype-pattern">Implementing External Traits with the Newtype Pattern</a></h3>
|
||
<p>In the <a href="../ch10/ch10-02-traits.html#implementing-a-trait-on-a-type">“Implementing a Trait on a Type”</a><!--
|
||
ignore --> section in Chapter 10, we mentioned the orphan rule that states
|
||
we’re only allowed to implement a trait on a type if either the trait or the
|
||
type, or both, are local to our crate. It’s possible to get around this
|
||
restriction using the newtype pattern, which involves creating a new type in a
|
||
tuple struct. (We covered tuple structs in the <a href="../ch05/ch05-01-defining-structs.html#creating-different-types-with-tuple-structs">“Creating Different Types with
|
||
Tuple Structs”</a><!-- ignore --> section in Chapter 5.) The tuple
|
||
struct will have one field and be a thin wrapper around the type for which we
|
||
want to implement a trait. Then, the wrapper type is local to our crate, and we
|
||
can implement the trait on the wrapper. <em>Newtype</em> is a term that originates
|
||
from the Haskell programming language. There is no runtime performance penalty
|
||
for using this pattern, and the wrapper type is elided at compile time.</p>
|
||
<p>As an example, let’s say we want to implement <code>Display</code> on <code>Vec<T></code>, which the
|
||
orphan rule prevents us from doing directly because the <code>Display</code> trait and the
|
||
<code>Vec<T></code> type are defined outside our crate. We can make a <code>Wrapper</code> struct
|
||
that holds an instance of <code>Vec<T></code>; then, we can implement <code>Display</code> on
|
||
<code>Wrapper</code> and use the <code>Vec<T></code> value, as shown in Listing 20-24.</p>
|
||
<figure class="listing" id="listing-20-24">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre class="playground"><code class="language-rust edition2024">use std::fmt;
|
||
|
||
struct Wrapper(Vec<String>);
|
||
|
||
impl fmt::Display for Wrapper {
|
||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||
write!(f, "[{}]", self.0.join(", "))
|
||
}
|
||
}
|
||
|
||
fn main() {
|
||
let w = Wrapper(vec![String::from("hello"), String::from("world")]);
|
||
println!("w = {w}");
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-24">Listing 20-24</a>: Creating a <code>Wrapper</code> type around <code>Vec<String></code> to implement <code>Display</code></figcaption>
|
||
</figure>
|
||
<p>The implementation of <code>Display</code> uses <code>self.0</code> to access the inner <code>Vec<T></code>
|
||
because <code>Wrapper</code> is a tuple struct and <code>Vec<T></code> is the item at index 0 in the
|
||
tuple. Then, we can use the functionality of the <code>Display</code> trait on <code>Wrapper</code>.</p>
|
||
<p>The downside of using this technique is that <code>Wrapper</code> is a new type, so it
|
||
doesn’t have the methods of the value it’s holding. We would have to implement
|
||
all the methods of <code>Vec<T></code> directly on <code>Wrapper</code> such that the methods
|
||
delegate to <code>self.0</code>, which would allow us to treat <code>Wrapper</code> exactly like a
|
||
<code>Vec<T></code>. If we wanted the new type to have every method the inner type has,
|
||
implementing the <code>Deref</code> trait on the <code>Wrapper</code> to return the inner type would
|
||
be a solution (we discussed implementing the <code>Deref</code> trait in the <a href="../ch15/ch15-02-deref.html#treating-smart-pointers-like-regular-references">“Treating
|
||
Smart Pointers Like Regular References”</a><!-- ignore -->
|
||
section in Chapter 15). If we didn’t want the <code>Wrapper</code> type to have all the
|
||
methods of the inner type—for example, to restrict the <code>Wrapper</code> type’s
|
||
behavior—we would have to implement just the methods we do want manually.</p>
|
||
<p>This newtype pattern is also useful even when traits are not involved. Let’s
|
||
switch focus and look at some advanced ways to interact with Rust’s type system.</p>
|
||
</body>
|
||
</html>
|