944 lines
60 KiB
HTML
944 lines
60 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en" class="light sidebar-visible" dir="ltr">
|
||
<head>
|
||
<!-- Book generated using mdBook -->
|
||
<meta charset="UTF-8">
|
||
<title>Advanced Traits - The Rust Programming Language</title>
|
||
|
||
|
||
<!-- Custom HTML head -->
|
||
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<meta name="theme-color" content="#ffffff">
|
||
|
||
<link rel="icon" href="favicon-de23e50b.svg">
|
||
<link rel="shortcut icon" href="favicon-8114d1fc.png">
|
||
<link rel="stylesheet" href="css/variables-8adf115d.css">
|
||
<link rel="stylesheet" href="css/general-0392ca55.css">
|
||
<link rel="stylesheet" href="css/chrome-fc474251.css">
|
||
<link rel="stylesheet" href="css/print-9e4910d8.css" media="print">
|
||
|
||
<!-- Fonts -->
|
||
<link rel="stylesheet" href="fonts/fonts-9644e21d.css">
|
||
|
||
<!-- Highlight.js Stylesheets -->
|
||
<link rel="stylesheet" id="mdbook-highlight-css" href="highlight-493f70e1.css">
|
||
<link rel="stylesheet" id="mdbook-tomorrow-night-css" href="tomorrow-night-4c0ae647.css">
|
||
<link rel="stylesheet" id="mdbook-ayu-highlight-css" href="ayu-highlight-3fdfc3ac.css">
|
||
|
||
<!-- Custom theme stylesheets -->
|
||
<link rel="stylesheet" href="ferris-d33b75bf.css">
|
||
<link rel="stylesheet" href="theme/2018-edition-4e126c62.css">
|
||
<link rel="stylesheet" href="theme/semantic-notes-9b5766c0.css">
|
||
<link rel="stylesheet" href="theme/listing-cab26221.css">
|
||
|
||
|
||
<!-- Provide site root and default themes to javascript -->
|
||
<script>
|
||
const path_to_root = "";
|
||
const default_light_theme = "light";
|
||
const default_dark_theme = "navy";
|
||
window.path_to_searchindex_js = "searchindex-6a1da8cc.js";
|
||
</script>
|
||
<!-- Start loading toc.js asap -->
|
||
<script src="toc-0e4ce700.js"></script>
|
||
</head>
|
||
<body>
|
||
<div id="mdbook-help-container">
|
||
<div id="mdbook-help-popup">
|
||
<h2 class="mdbook-help-title">Keyboard shortcuts</h2>
|
||
<div>
|
||
<p>Press <kbd>←</kbd> or <kbd>→</kbd> to navigate between chapters</p>
|
||
<p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p>
|
||
<p>Press <kbd>?</kbd> to show this help</p>
|
||
<p>Press <kbd>Esc</kbd> to hide this help</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div id="mdbook-body-container">
|
||
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
||
<script>
|
||
try {
|
||
let theme = localStorage.getItem('mdbook-theme');
|
||
let sidebar = localStorage.getItem('mdbook-sidebar');
|
||
|
||
if (theme.startsWith('"') && theme.endsWith('"')) {
|
||
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
||
}
|
||
|
||
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
||
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
||
}
|
||
} catch (e) { }
|
||
</script>
|
||
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script>
|
||
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
|
||
let theme;
|
||
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
||
if (theme === null || theme === undefined) { theme = default_theme; }
|
||
const html = document.documentElement;
|
||
html.classList.remove('light')
|
||
html.classList.add(theme);
|
||
html.classList.add("js");
|
||
</script>
|
||
|
||
<input type="checkbox" id="mdbook-sidebar-toggle-anchor" class="hidden">
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script>
|
||
let sidebar = null;
|
||
const sidebar_toggle = document.getElementById("mdbook-sidebar-toggle-anchor");
|
||
if (document.body.clientWidth >= 1080) {
|
||
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
||
sidebar = sidebar || 'visible';
|
||
} else {
|
||
sidebar = 'hidden';
|
||
sidebar_toggle.checked = false;
|
||
}
|
||
if (sidebar === 'visible') {
|
||
sidebar_toggle.checked = true;
|
||
} else {
|
||
html.classList.remove('sidebar-visible');
|
||
}
|
||
</script>
|
||
|
||
<nav id="mdbook-sidebar" class="sidebar" aria-label="Table of contents">
|
||
<!-- populated by js -->
|
||
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
|
||
<noscript>
|
||
<iframe class="sidebar-iframe-outer" src="toc.html"></iframe>
|
||
</noscript>
|
||
<div id="mdbook-sidebar-resize-handle" class="sidebar-resize-handle">
|
||
<div class="sidebar-resize-indicator"></div>
|
||
</div>
|
||
</nav>
|
||
|
||
<div id="mdbook-page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="mdbook-menu-bar-hover-placeholder"></div>
|
||
<div id="mdbook-menu-bar" class="menu-bar sticky">
|
||
<div class="left-buttons">
|
||
<label id="mdbook-sidebar-toggle" class="icon-button" for="mdbook-sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="mdbook-sidebar">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M0 96C0 78.3 14.3 64 32 64H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H416c17.7 0 32 14.3 32 32z"/></svg></span>
|
||
</label>
|
||
<button id="mdbook-theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="mdbook-theme-list">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M371.3 367.1c27.3-3.9 51.9-19.4 67.2-42.9L600.2 74.1c12.6-19.5 9.4-45.3-7.6-61.2S549.7-4.4 531.1 9.6L294.4 187.2c-24 18-38.2 46.1-38.4 76.1L371.3 367.1zm-19.6 25.4l-116-104.4C175.9 290.3 128 339.6 128 400c0 3.9 .2 7.8 .6 11.6c1.8 17.5-10.2 36.4-27.8 36.4H96c-17.7 0-32 14.3-32 32s14.3 32 32 32H240c61.9 0 112-50.1 112-112c0-2.5-.1-5-.2-7.5z"/></svg></span>
|
||
</button>
|
||
<ul id="mdbook-theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-default_theme">Auto</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-light">Light</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-rust">Rust</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-coal">Coal</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-navy">Navy</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-ayu">Ayu</button></li>
|
||
</ul>
|
||
<button id="mdbook-search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="mdbook-searchbar">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352c79.5 0 144-64.5 144-144s-64.5-144-144-144S64 128.5 64 208s64.5 144 144 144z"/></svg></span>
|
||
</button>
|
||
</div>
|
||
|
||
<h1 class="menu-title">The Rust Programming Language</h1>
|
||
|
||
<div class="right-buttons">
|
||
<a href="print.html" title="Print this book" aria-label="Print this book">
|
||
<span class=fa-svg id="print-button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zm-16-88c-13.3 0-24-10.7-24-24s10.7-24 24-24s24 10.7 24 24s-10.7 24-24 24z"/></svg></span>
|
||
</a>
|
||
<a href="https://github.com/rust-lang/book" title="Git repository" aria-label="Git repository">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span>
|
||
</a>
|
||
|
||
</div>
|
||
</div>
|
||
|
||
<div id="mdbook-search-wrapper" class="hidden">
|
||
<form id="mdbook-searchbar-outer" class="searchbar-outer">
|
||
<div class="search-wrapper">
|
||
<input type="search" id="mdbook-searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="mdbook-searchresults-outer" aria-describedby="searchresults-header">
|
||
<div class="spinner-wrapper">
|
||
<span class=fa-svg id="fa-spin"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M304 48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zm0 416c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM48 304c26.5 0 48-21.5 48-48s-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48zm464-48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM142.9 437c18.7-18.7 18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zm0-294.2c18.7-18.7 18.7-49.1 0-67.9S93.7 56.2 75 75s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zM369.1 437c18.7 18.7 49.1 18.7 67.9 0s18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9z"/></svg></span>
|
||
</div>
|
||
</div>
|
||
</form>
|
||
<div id="mdbook-searchresults-outer" class="searchresults-outer hidden">
|
||
<div id="mdbook-searchresults-header" class="searchresults-header"></div>
|
||
<ul id="mdbook-searchresults">
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
||
<script>
|
||
document.getElementById('mdbook-sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
||
document.getElementById('mdbook-sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
||
Array.from(document.querySelectorAll('#mdbook-sidebar a')).forEach(function(link) {
|
||
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
||
});
|
||
</script>
|
||
|
||
<div id="mdbook-content" class="content">
|
||
<main>
|
||
<h2 id="advanced-traits"><a class="header" href="#advanced-traits">Advanced Traits</a></h2>
|
||
<p>We first covered traits in the <a href="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-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-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-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>
|
||
|
||
</main>
|
||
|
||
<nav class="nav-wrapper" aria-label="Page navigation">
|
||
<!-- Mobile navigation buttons -->
|
||
<a rel="prev" href="ch20-01-unsafe-rust.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
|
||
</a>
|
||
|
||
<a rel="next prefetch" href="ch20-03-advanced-types.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
|
||
</a>
|
||
|
||
<div style="clear: both"></div>
|
||
</nav>
|
||
</div>
|
||
</div>
|
||
|
||
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
||
<a rel="prev" href="ch20-01-unsafe-rust.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
|
||
</a>
|
||
|
||
<a rel="next prefetch" href="ch20-03-advanced-types.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
|
||
</a>
|
||
</nav>
|
||
|
||
</div>
|
||
|
||
<template id=fa-eye><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM432 256c0 79.5-64.5 144-144 144s-144-64.5-144-144s64.5-144 144-144s144 64.5 144 144zM288 192c0 35.3-28.7 64-64 64c-11.5 0-22.3-3-31.6-8.4c-.2 2.8-.4 5.5-.4 8.4c0 53 43 96 96 96s96-43 96-96s-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6z"/></svg></span></template>
|
||
<template id=fa-eye-slash><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L525.6 386.7c39.6-40.6 66.4-86.1 79.9-118.4c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8L38.8 5.1zM223.1 149.5C248.6 126.2 282.7 112 320 112c79.5 0 144 64.5 144 144c0 24.9-6.3 48.3-17.4 68.7L408 294.5c5.2-11.8 8-24.8 8-38.5c0-53-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6c0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zm223.1 298L373 389.9c-16.4 6.5-34.3 10.1-53 10.1c-79.5 0-144-64.5-144-144c0-6.9 .5-13.6 1.4-20.2L83.1 161.5C60.3 191.2 44 220.8 34.5 243.7c-3.3 7.9-3.3 16.7 0 24.6c14.9 35.7 46.2 87.7 93 131.1C174.5 443.2 239.2 480 320 480c47.8 0 89.9-12.9 126.2-32.5z"/></svg></span></template>
|
||
<template id=fa-copy><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"/></svg></span></template>
|
||
<template id=fa-play><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z"/></svg></span></template>
|
||
<template id=fa-clock-rotate-left><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M75 75L41 41C25.9 25.9 0 36.6 0 57.9V168c0 13.3 10.7 24 24 24H134.1c21.4 0 32.1-25.9 17-41l-30.8-30.8C155 85.5 203 64 256 64c106 0 192 86 192 192s-86 192-192 192c-40.8 0-78.6-12.7-109.7-34.4c-14.5-10.1-34.4-6.6-44.6 7.9s-6.6 34.4 7.9 44.6C151.2 495 201.7 512 256 512c141.4 0 256-114.6 256-256S397.4 0 256 0C185.3 0 121.3 28.7 75 75zm181 53c-13.3 0-24 10.7-24 24V256c0 6.4 2.5 12.5 7 17l72 72c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-65-65V152c0-13.3-10.7-24-24-24z"/></svg></span></template>
|
||
|
||
|
||
|
||
<script>
|
||
window.playground_copyable = true;
|
||
</script>
|
||
|
||
|
||
<script src="elasticlunr-ef4e11c1.min.js"></script>
|
||
<script src="mark-09e88c2c.min.js"></script>
|
||
<script src="searcher-09f2665d.js"></script>
|
||
|
||
<script src="clipboard-1626706a.min.js"></script>
|
||
<script src="highlight-abc7f01d.js"></script>
|
||
<script src="book-c22b7243.js"></script>
|
||
|
||
<!-- Custom JS scripts -->
|
||
<script src="ferris-2317480c.js"></script>
|
||
|
||
|
||
|
||
</div>
|
||
</body>
|
||
</html>
|