You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
trpl-zh-cn/ch10-02-traits.html

622 lines
56 KiB

<!DOCTYPE HTML>
<html lang="zh-CN" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Trait定义共同行为 - Rust 程序设计语言 简体中文版</title>
<!-- Custom HTML head -->
<meta name="description" content="Rust 程序设计语言 简体中文版">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="ferris.css">
<link rel="stylesheet" href="theme/2018-edition.css">
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var 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>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("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 = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded affix "><a href="title-page.html">Rust 程序设计语言</a></li><li class="chapter-item expanded affix "><a href="foreword.html">前言</a></li><li class="chapter-item expanded affix "><a href="ch00-00-introduction.html">简介</a></li><li class="chapter-item expanded "><a href="ch01-00-getting-started.html"><strong aria-hidden="true">1.</strong> 入门指南</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch01-01-installation.html"><strong aria-hidden="true">1.1.</strong> 安装</a></li><li class="chapter-item expanded "><a href="ch01-02-hello-world.html"><strong aria-hidden="true">1.2.</strong> Hello, World!</a></li><li class="chapter-item expanded "><a href="ch01-03-hello-cargo.html"><strong aria-hidden="true">1.3.</strong> Hello, Cargo!</a></li></ol></li><li class="chapter-item expanded "><a href="ch02-00-guessing-game-tutorial.html"><strong aria-hidden="true">2.</strong> 写个猜数字游戏</a></li><li class="chapter-item expanded "><a href="ch03-00-common-programming-concepts.html"><strong aria-hidden="true">3.</strong> 常见编程概念</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch03-01-variables-and-mutability.html"><strong aria-hidden="true">3.1.</strong> 变量与可变性</a></li><li class="chapter-item expanded "><a href="ch03-02-data-types.html"><strong aria-hidden="true">3.2.</strong> 数据类型</a></li><li class="chapter-item expanded "><a href="ch03-03-how-functions-work.html"><strong aria-hidden="true">3.3.</strong> 函数</a></li><li class="chapter-item expanded "><a href="ch03-04-comments.html"><strong aria-hidden="true">3.4.</strong> 注释</a></li><li class="chapter-item expanded "><a href="ch03-05-control-flow.html"><strong aria-hidden="true">3.5.</strong> 控制流</a></li></ol></li><li class="chapter-item expanded "><a href="ch04-00-understanding-ownership.html"><strong aria-hidden="true">4.</strong> 认识所有权</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch04-01-what-is-ownership.html"><strong aria-hidden="true">4.1.</strong> 什么是所有权?</a></li><li class="chapter-item expanded "><a href="ch04-02-references-and-borrowing.html"><strong aria-hidden="true">4.2.</strong> 引用与借用</a></li><li class="chapter-item expanded "><a href="ch04-03-slices.html"><strong aria-hidden="true">4.3.</strong> Slice 类型</a></li></ol></li><li class="chapter-item expanded "><a href="ch05-00-structs.html"><strong aria-hidden="true">5.</strong> 使用结构体组织相关联的数据</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch05-01-defining-structs.html"><strong aria-hidden="true">5.1.</strong> 结构体的定义和实例化</a></li><li class="chapter-item expanded "><a href="ch05-02-example-structs.html"><strong aria-hidden="true">5.2.</strong> 结构体示例程序</a></li><li class="chapter-item expanded "><a href="ch05-03-method-syntax.html"><strong aria-hidden="true">5.3.</strong> 方法语法</a></li></ol></li><li class="chapter-item expanded "><a href="ch06-00-enums.html"><strong aria-hidden="true">6.</strong> 枚举和模式匹配</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch06-01-defining-an-enum.html"><strong aria-hidden="true">6.1.</strong> 枚举的定义</a></li><li class="chapter-item expanded "><a href="ch06-02-match.html"><strong aria-hidden="true">6.2.</strong> match 控制流结构</a></li><li class="chapter-item expanded "><a href="ch06-03-if-let.html"><strong aria-hidden="true">6.3.</strong> if let 简洁控制流</a></li></ol></li><li class="chapter-item expanded "><a href="ch07-00-managing-growing-projects-with-packages-crates-and-modules.html"><strong aria-hidden="true">7.</strong> 使用包、Crate 和模块管理不断增长的项目</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch07-01-packages-and-crates.html"><strong aria-hidden="true">7.1.</strong> 包和 Crate</a></li><li class="chapter-item expanded "><a h
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Rust 程序设计语言 简体中文版</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/KaiserY/trpl-zh-cn/tree/main" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/KaiserY/trpl-zh-cn/edit/main/src/ch10-02-traits.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h2 id="trait定义共同行为"><a class="header" href="#trait定义共同行为">Trait定义共同行为</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch10-02-traits.md">ch10-02-traits.md</a>
<br>
commit 92bfbfacf88ee9a814cea0a58e9c019c529ef4ae</p>
</blockquote>
<p><em>trait</em> 定义了某个特定类型拥有可能与其他类型共享的功能。可以通过 trait 以一种抽象的方式定义共同行为。可以使用 <em>trait bounds</em> 指定泛型是任何拥有特定行为的类型。</p>
<blockquote>
<p>注意:<em>trait</em> 类似于其他语言中的常被称为 <strong>接口</strong><em>interfaces</em>)的功能,虽然有一些不同。</p>
</blockquote>
<h3 id="定义-trait"><a class="header" href="#定义-trait">定义 trait</a></h3>
<p>一个类型的行为由其可供调用的方法构成。如果可以对不同类型调用相同的方法的话这些类型就可以共享相同的行为了。trait 定义是一种将方法签名组合起来的方法,目的是定义一个实现某些目的所必需的行为的集合。</p>
<p>例如,这里有多个存放了不同类型和属性文本的结构体:结构体 <code>NewsArticle</code> 用于存放发生于世界各地的新闻故事,而结构体 <code>Tweet</code> 最多只能存放 280 个字符的内容,以及像是否转推或是否是对推友的回复这样的元数据。</p>
<p>我们想要创建一个名为 <code>aggregator</code> 的多媒体聚合库用来显示可能储存在 <code>NewsArticle</code><code>Tweet</code> 实例中的数据摘要。为了实现功能,每个结构体都要能够获取摘要,这样的话就可以调用实例的 <code>summarize</code> 方法来请求摘要。示例 10-12 中展示了一个表现这个概念的公有 <code>Summary</code> trait 的定义:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub trait Summary {
fn summarize(&amp;self) -&gt; String;
}</code></pre>
<p><span class="caption">示例 10-12<code>Summary</code> trait 定义,它包含由 <code>summarize</code> 方法提供的行为</span></p>
<p>这里使用 <code>trait</code> 关键字来声明一个 trait后面是 trait 的名字,在这个例子中是 <code>Summary</code>。我们也声明 <code>trait</code><code>pub</code> 以便依赖这个 crate 的 crate 也可以使用这个 trait正如我们见过的一些示例一样。在大括号中声明描述实现这个 trait 的类型所需要的行为的方法签名,在这个例子中是 <code>fn summarize(&amp;self) -&gt; String</code></p>
<p>在方法签名后跟分号,而不是在大括号中提供其实现。接着每一个实现这个 trait 的类型都需要提供其自定义行为的方法体,编译器也会确保任何实现 <code>Summary</code> trait 的类型都拥有与这个签名的定义完全一致的 <code>summarize</code> 方法。</p>
<p>trait 体中可以有多个方法:一行一个方法签名且都以分号结尾。</p>
<h3 id="为类型实现-trait"><a class="header" href="#为类型实现-trait">为类型实现 trait</a></h3>
<p>现在我们定义了 <code>Summary</code> trait 的签名,接着就可以在多媒体聚合库中实现这个类型了。示例 10-13 中展示了 <code>NewsArticle</code> 结构体上 <code>Summary</code> trait 的一个实现,它使用标题、作者和创建的位置作为 <code>summarize</code> 的返回值。对于 <code>Tweet</code> 结构体,我们选择将 <code>summarize</code> 定义为用户名后跟推文的全部文本作为返回值,并假设推文内容已经被限制为 280 字符以内。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Summary {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span>pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&amp;self) -&gt; String {
format!(&quot;{}, by {} ({})&quot;, self.headline, self.author, self.location)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&amp;self) -&gt; String {
format!(&quot;{}: {}&quot;, self.username, self.content)
}
}</code></pre>
<p><span class="caption">示例 10-13<code>NewsArticle</code><code>Tweet</code> 类型上实现 <code>Summary</code> trait</span></p>
<p>在类型上实现 trait 类似于实现常规方法。区别在于 <code>impl</code> 关键字之后,我们提供需要实现 trait 的名称,接着是 <code>for</code> 和需要实现 trait 的类型的名称。在 <code>impl</code> 块中,使用 trait 定义中的方法签名,不过不再后跟分号,而是需要在大括号中编写函数体来为特定类型实现 trait 方法所拥有的行为。</p>
<p>现在库在 <code>NewsArticle</code><code>Tweet</code> 上实现了<code>Summary</code> traitcrate 的用户可以像调用常规方法一样调用 <code>NewsArticle</code><code>Tweet</code> 实例的 trait 方法了。唯一的区别是 trait 必须和类型一起引入作用域以便使用额外的 trait 方法。这是一个二进制 crate 如何利用 <code>aggregator</code> 库 crate 的例子:</p>
<pre><code class="language-rust ignore">use aggregator::{Summary, Tweet};
fn main() {
let tweet = Tweet {
username: String::from(&quot;horse_ebooks&quot;),
content: String::from(
&quot;of course, as you probably already know, people&quot;,
),
reply: false,
retweet: false,
};
println!(&quot;1 new tweet: {}&quot;, tweet.summarize());
}</code></pre>
<p>这会打印出 <code>1 new tweet: horse_ebooks: of course, as you probably already know, people</code></p>
<p>其他依赖 <code>aggregator</code> crate 的 crate 也可以将 <code>Summary</code> 引入作用域以便为其自己的类型实现该 trait。需要注意的限制是只有在 trait 或类型至少有一个属于当前 crate 时,我们才能对类型实现该 trait。例如可以为 <code>aggregator</code> crate 的自定义类型 <code>Tweet</code> 实现如标准库中的 <code>Display</code> trait这是因为 <code>Tweet</code> 类型位于 <code>aggregator</code> crate 本地的作用域中。类似地,也可以在 <code>aggregator</code> crate 中为 <code>Vec&lt;T&gt;</code> 实现 <code>Summary</code>,这是因为 <code>Summary</code> trait 位于 <code>aggregator</code> crate 本地作用域中。</p>
<p>但是不能为外部类型实现外部 trait。例如不能在 <code>aggregator</code> crate 中为 <code>Vec&lt;T&gt;</code> 实现 <code>Display</code> trait。这是因为 <code>Display</code><code>Vec&lt;T&gt;</code> 都定义于标准库中,它们并不位于 <code>aggregator</code> crate 本地作用域中。这个限制是被称为 <strong>相干性</strong><em>coherence</em>)的程序属性的一部分,或者更具体的说是 <strong>孤儿规则</strong><em>orphan rule</em>),其得名于不存在父类型。这条规则确保了其他人编写的代码不会破坏你代码,反之亦然。没有这条规则的话,两个 crate 可以分别对相同类型实现相同的 trait而 Rust 将无从得知应该使用哪一个实现。</p>
<h3 id="默认实现"><a class="header" href="#默认实现">默认实现</a></h3>
<p>有时为 trait 中的某些或全部方法提供默认的行为,而不是在每个类型的每个实现中都定义自己的行为是很有用的。这样当为某个特定类型实现 trait 时,可以选择保留或重载每个方法的默认行为。</p>
<p>示例 10-14 中我们为 <code>Summary</code> trait 的 <code>summarize</code> 方法指定一个默认的字符串值,而不是像示例 10-12 中那样只是定义方法签名:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub trait Summary {
fn summarize(&amp;self) -&gt; String {
String::from(&quot;(Read more...)&quot;)
}
}
<span class="boring">
</span><span class="boring">pub struct NewsArticle {
</span><span class="boring"> pub headline: String,
</span><span class="boring"> pub location: String,
</span><span class="boring"> pub author: String,
</span><span class="boring"> pub content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for NewsArticle {}
</span><span class="boring">
</span><span class="boring">pub struct Tweet {
</span><span class="boring"> pub username: String,
</span><span class="boring"> pub content: String,
</span><span class="boring"> pub reply: bool,
</span><span class="boring"> pub retweet: bool,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for Tweet {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;{}: {}&quot;, self.username, self.content)
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 10-14<code>Summary</code> trait 的定义,带有一个 <code>summarize</code> 方法的默认实现</span></p>
<p>如果想要对 <code>NewsArticle</code> 实例使用这个默认实现,可以通过 <code>impl Summary for NewsArticle {}</code> 指定一个空的 <code>impl</code> 块。</p>
<p>虽然我们不再直接为 <code>NewsArticle</code> 定义 <code>summarize</code> 方法了,但是我们提供了一个默认实现并且指定 <code>NewsArticle</code> 实现 <code>Summary</code> trait。因此我们仍然可以对 <code>NewsArticle</code> 实例调用 <code>summarize</code> 方法,如下所示:</p>
<pre><code class="language-rust ignore"><span class="boring">use aggregator::{self, NewsArticle, Summary};
</span><span class="boring">
</span><span class="boring">fn main() {
</span> let article = NewsArticle {
headline: String::from(&quot;Penguins win the Stanley Cup Championship!&quot;),
location: String::from(&quot;Pittsburgh, PA, USA&quot;),
author: String::from(&quot;Iceburgh&quot;),
content: String::from(
&quot;The Pittsburgh Penguins once again are the best \
hockey team in the NHL.&quot;,
),
};
println!(&quot;New article available! {}&quot;, article.summarize());
<span class="boring">}</span></code></pre>
<p>这段代码会打印 <code>New article available! (Read more...)</code></p>
<p><code>summarize</code> 创建默认实现并不要求对示例 10-13 中 <code>Tweet</code> 上的 <code>Summary</code> 实现做任何改变。其原因是重载一个默认实现的语法与实现没有默认实现的 trait 方法的语法一样。</p>
<p>默认实现允许调用相同 trait 中的其他方法哪怕这些方法没有默认实现。如此trait 可以提供很多有用的功能而只需要实现指定一小部分内容。例如,我们可以定义 <code>Summary</code> trait使其具有一个需要实现的 <code>summarize_author</code> 方法,然后定义一个 <code>summarize</code> 方法,此方法的默认实现调用 <code>summarize_author</code> 方法:</p>
<pre><code class="language-rust noplayground">pub trait Summary {
fn summarize_author(&amp;self) -&gt; String;
fn summarize(&amp;self) -&gt; String {
format!(&quot;(Read more from {}...)&quot;, self.summarize_author())
}
}
<span class="boring">
</span><span class="boring">pub struct Tweet {
</span><span class="boring"> pub username: String,
</span><span class="boring"> pub content: String,
</span><span class="boring"> pub reply: bool,
</span><span class="boring"> pub retweet: bool,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for Tweet {
</span><span class="boring"> fn summarize_author(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;@{}&quot;, self.username)
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>为了使用这个版本的 <code>Summary</code>,只需在实现 trait 时定义 <code>summarize_author</code> 即可:</p>
<pre><code class="language-rust ignore"><span class="boring">pub trait Summary {
</span><span class="boring"> fn summarize_author(&amp;self) -&gt; String;
</span><span class="boring">
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;(Read more from {}...)&quot;, self.summarize_author())
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct Tweet {
</span><span class="boring"> pub username: String,
</span><span class="boring"> pub content: String,
</span><span class="boring"> pub reply: bool,
</span><span class="boring"> pub retweet: bool,
</span><span class="boring">}
</span><span class="boring">
</span>impl Summary for Tweet {
fn summarize_author(&amp;self) -&gt; String {
format!(&quot;@{}&quot;, self.username)
}
}</code></pre>
<p>一旦定义了 <code>summarize_author</code>,我们就可以对 <code>Tweet</code> 结构体的实例调用 <code>summarize</code> 了,而 <code>summarize</code> 的默认实现会调用我们提供的 <code>summarize_author</code> 定义。因为实现了 <code>summarize_author</code><code>Summary</code> trait 就提供了 <code>summarize</code> 方法的功能,且无需编写更多的代码。</p>
<pre><code class="language-rust ignore"><span class="boring">use aggregator::{self, Summary, Tweet};
</span><span class="boring">
</span><span class="boring">fn main() {
</span> let tweet = Tweet {
username: String::from(&quot;horse_ebooks&quot;),
content: String::from(
&quot;of course, as you probably already know, people&quot;,
),
reply: false,
retweet: false,
};
println!(&quot;1 new tweet: {}&quot;, tweet.summarize());
<span class="boring">}</span></code></pre>
<p>这会打印出 <code>1 new tweet: (Read more from @horse_ebooks...)</code></p>
<p>注意无法从相同方法的重载实现中调用默认方法。</p>
<h3 id="trait-作为参数"><a class="header" href="#trait-作为参数">trait 作为参数</a></h3>
<p>知道了如何定义 trait 和在类型上实现这些 trait 之后,我们可以探索一下如何使用 trait 来接受多种不同类型的参数。示例 10-13 中为 <code>NewsArticle</code><code>Tweet</code> 类型实现了 <code>Summary</code> trait用其来定义了一个函数 <code>notify</code> 来调用其参数 <code>item</code> 上的 <code>summarize</code> 方法,该参数是实现了 <code>Summary</code> trait 的某种类型。为此可以使用 <code>impl Trait</code> 语法,像这样:</p>
<pre><code class="language-rust ignore"><span class="boring">pub trait Summary {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct NewsArticle {
</span><span class="boring"> pub headline: String,
</span><span class="boring"> pub location: String,
</span><span class="boring"> pub author: String,
</span><span class="boring"> pub content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for NewsArticle {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;{}, by {} ({})&quot;, self.headline, self.author, self.location)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct Tweet {
</span><span class="boring"> pub username: String,
</span><span class="boring"> pub content: String,
</span><span class="boring"> pub reply: bool,
</span><span class="boring"> pub retweet: bool,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for Tweet {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;{}: {}&quot;, self.username, self.content)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>pub fn notify(item: &amp;impl Summary) {
println!(&quot;Breaking news! {}&quot;, item.summarize());
}</code></pre>
<p>对于 <code>item</code> 参数,我们指定了 <code>impl</code> 关键字和 trait 名称,而不是具体的类型。该参数支持任何实现了指定 trait 的类型。在 <code>notify</code> 函数体中,可以调用任何来自 <code>Summary</code> trait 的方法,比如 <code>summarize</code>。我们可以传递任何 <code>NewsArticle</code><code>Tweet</code> 的实例来调用 <code>notify</code>。任何用其它如 <code>String</code><code>i32</code> 的类型调用该函数的代码都不能编译,因为它们没有实现 <code>Summary</code></p>
<h4 id="trait-bound-语法"><a class="header" href="#trait-bound-语法">Trait Bound 语法</a></h4>
<p><code>impl Trait</code> 语法更直观,但它实际上是更长形式的 <em>trait bound</em> 语法的语法糖。它看起来像:</p>
<pre><code class="language-rust ignore">pub fn notify&lt;T: Summary&gt;(item: &amp;T) {
println!(&quot;Breaking news! {}&quot;, item.summarize());
}</code></pre>
<p>这与之前的例子相同不过稍微冗长了一些。trait bound 与泛型参数声明在一起,位于尖括号中的冒号后面。</p>
<p><code>impl Trait</code> 很方便,适用于短小的例子。更长的 trait bound 则适用于更复杂的场景。例如,可以获取两个实现了 <code>Summary</code> 的参数。使用 <code>impl Trait</code> 的语法看起来像这样:</p>
<pre><code class="language-rust ignore">pub fn notify(item1: &amp;impl Summary, item2: &amp;impl Summary) {</code></pre>
<p>这适用于 <code>item1</code><code>item2</code> 允许是不同类型的情况(只要它们都实现了 <code>Summary</code>)。不过如果你希望强制它们都是相同类型呢?这只有在使用 trait bound 时才有可能:</p>
<pre><code class="language-rust ignore">pub fn notify&lt;T: Summary&gt;(item1: &amp;T, item2: &amp;T) {</code></pre>
<p>泛型 <code>T</code> 被指定为 <code>item1</code><code>item2</code> 的参数限制,如此传递给参数 <code>item1</code><code>item2</code> 值的具体类型必须一致。</p>
<h4 id="通过--指定多个-trait-bound"><a class="header" href="#通过--指定多个-trait-bound">通过 <code>+</code> 指定多个 trait bound</a></h4>
<p>如果 <code>notify</code> 需要显示 <code>item</code> 的格式化形式,同时也要使用 <code>summarize</code> 方法,那么 <code>item</code> 就需要同时实现两个不同的 trait<code>Display</code><code>Summary</code>。这可以通过 <code>+</code> 语法实现:</p>
<pre><code class="language-rust ignore">pub fn notify(item: &amp;(impl Summary + Display)) {</code></pre>
<p><code>+</code> 语法也适用于泛型的 trait bound</p>
<pre><code class="language-rust ignore">pub fn notify&lt;T: Summary + Display&gt;(item: &amp;T) {</code></pre>
<p>通过指定这两个 trait bound<code>notify</code> 的函数体可以调用 <code>summarize</code> 并使用 <code>{}</code> 来格式化 <code>item</code></p>
<h4 id="通过-where-简化-trait-bound"><a class="header" href="#通过-where-简化-trait-bound">通过 <code>where</code> 简化 trait bound</a></h4>
<p>然而,使用过多的 trait bound 也有缺点。每个泛型有其自己的 trait bound所以有多个泛型参数的函数在名称和参数列表之间会有很长的 trait bound 信息这使得函数签名难以阅读。为此Rust 有另一个在函数签名之后的 <code>where</code> 从句中指定 trait bound 的语法。所以除了这么写:</p>
<pre><code class="language-rust ignore">fn some_function&lt;T: Display + Clone, U: Clone + Debug&gt;(t: &amp;T, u: &amp;U) -&gt; i32 {</code></pre>
<p>还可以像这样使用 <code>where</code> 从句:</p>
<pre><code class="language-rust ignore">fn some_function&lt;T, U&gt;(t: &amp;T, u: &amp;U) -&gt; i32
where
T: Display + Clone,
U: Clone + Debug,
{
<span class="boring"> unimplemented!()
</span><span class="boring">}</span></code></pre>
<p>这个函数签名就显得不那么杂乱,函数名、参数列表和返回值类型都离得很近,看起来跟没有那么多 trait bounds 的函数很像。</p>
<h3 id="返回实现了-trait-的类型"><a class="header" href="#返回实现了-trait-的类型">返回实现了 trait 的类型</a></h3>
<p>也可以在返回值中使用 <code>impl Trait</code> 语法,来返回实现了某个 trait 的类型:</p>
<pre><code class="language-rust ignore"><span class="boring">pub trait Summary {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct NewsArticle {
</span><span class="boring"> pub headline: String,
</span><span class="boring"> pub location: String,
</span><span class="boring"> pub author: String,
</span><span class="boring"> pub content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for NewsArticle {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;{}, by {} ({})&quot;, self.headline, self.author, self.location)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct Tweet {
</span><span class="boring"> pub username: String,
</span><span class="boring"> pub content: String,
</span><span class="boring"> pub reply: bool,
</span><span class="boring"> pub retweet: bool,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for Tweet {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;{}: {}&quot;, self.username, self.content)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn returns_summarizable() -&gt; impl Summary {
Tweet {
username: String::from(&quot;horse_ebooks&quot;),
content: String::from(
&quot;of course, as you probably already know, people&quot;,
),
reply: false,
retweet: false,
}
}</code></pre>
<p>通过使用 <code>impl Summary</code> 作为返回值类型,我们指定了 <code>returns_summarizable</code> 函数返回某个实现了 <code>Summary</code> trait 的类型,但是不确定其具体的类型。在这个例子中 <code>returns_summarizable</code> 返回了一个 <code>Tweet</code>,不过调用方并不知情。</p>
<p>返回一个只是指定了需要实现的 trait 的类型的能力在闭包和迭代器场景十分的有用,第十三章会介绍它们。闭包和迭代器创建只有编译器知道的类型,或者是非常非常长的类型。<code>impl Trait</code> 允许你简单的指定函数返回一个 <code>Iterator</code> 而无需写出实际的冗长的类型。</p>
<p>不过这只适用于返回单一类型的情况。例如,这段代码的返回值类型指定为返回 <code>impl Summary</code>,但是返回了 <code>NewsArticle</code><code>Tweet</code> 就行不通:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">pub trait Summary {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct NewsArticle {
</span><span class="boring"> pub headline: String,
</span><span class="boring"> pub location: String,
</span><span class="boring"> pub author: String,
</span><span class="boring"> pub content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for NewsArticle {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;{}, by {} ({})&quot;, self.headline, self.author, self.location)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct Tweet {
</span><span class="boring"> pub username: String,
</span><span class="boring"> pub content: String,
</span><span class="boring"> pub reply: bool,
</span><span class="boring"> pub retweet: bool,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for Tweet {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!(&quot;{}: {}&quot;, self.username, self.content)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn returns_summarizable(switch: bool) -&gt; impl Summary {
if switch {
NewsArticle {
headline: String::from(
&quot;Penguins win the Stanley Cup Championship!&quot;,
),
location: String::from(&quot;Pittsburgh, PA, USA&quot;),
author: String::from(&quot;Iceburgh&quot;),
content: String::from(
&quot;The Pittsburgh Penguins once again are the best \
hockey team in the NHL.&quot;,
),
}
} else {
Tweet {
username: String::from(&quot;horse_ebooks&quot;),
content: String::from(
&quot;of course, as you probably already know, people&quot;,
),
reply: false,
retweet: false,
}
}
}</code></pre>
<p>这里尝试返回 <code>NewsArticle</code><code>Tweet</code>。这不能编译,因为 <code>impl Trait</code> 工作方式的限制。第十七章的 <a href="ch17-02-trait-objects.html#%E9%A1%BE%E5%8F%8A%E4%B8%8D%E5%90%8C%E7%B1%BB%E5%9E%8B%E5%80%BC%E7%9A%84-trait-%E5%AF%B9%E8%B1%A1">“顾及不同类型值的 trait 对象”</a> 部分会介绍如何编写这样一个函数。</p>
<h3 id="使用-trait-bound-有条件地实现方法"><a class="header" href="#使用-trait-bound-有条件地实现方法">使用 trait bound 有条件地实现方法</a></h3>
<p>通过使用带有 trait bound 的泛型参数的 <code>impl</code> 块,可以有条件地只为那些实现了特定 trait 的类型实现方法。例如,示例 10-15 中的类型 <code>Pair&lt;T&gt;</code> 总是实现了 <code>new</code> 方法并返回一个 <code>Pair&lt;T&gt;</code> 的实例(回忆一下第五章的 <a href="ch05-03-method-syntax.html#%E5%AE%9A%E4%B9%89%E6%96%B9%E6%B3%95">“定义方法”</a> 部分,<code>Self</code> 是一个 <code>impl</code> 块类型的类型别名type alias在这里是 <code>Pair&lt;T&gt;</code>)。不过在下一个 <code>impl</code> 块中,只有那些为 <code>T</code> 类型实现了 <code>PartialOrd</code> trait来允许比较 <strong></strong> <code>Display</code> trait来启用打印<code>Pair&lt;T&gt;</code> 才会实现 <code>cmp_display</code> 方法:</p>
<pre><code class="language-rust noplayground">use std::fmt::Display;
struct Pair&lt;T&gt; {
x: T,
y: T,
}
impl&lt;T&gt; Pair&lt;T&gt; {
fn new(x: T, y: T) -&gt; Self {
Self { x, y }
}
}
impl&lt;T: Display + PartialOrd&gt; Pair&lt;T&gt; {
fn cmp_display(&amp;self) {
if self.x &gt;= self.y {
println!(&quot;The largest member is x = {}&quot;, self.x);
} else {
println!(&quot;The largest member is y = {}&quot;, self.y);
}
}
}</code></pre>
<p><span class="caption">示例 10-15根据 trait bound 在泛型上有条件的实现方法</span></p>
<p>也可以对任何实现了特定 trait 的类型有条件地实现 trait。对任何满足特定 trait bound 的类型实现 trait 被称为 <em>blanket implementations</em>,它们被广泛的用于 Rust 标准库中。例如,标准库为任何实现了 <code>Display</code> trait 的类型实现了 <code>ToString</code> trait。这个 <code>impl</code> 块看起来像这样:</p>
<pre><code class="language-rust ignore">impl&lt;T: Display&gt; ToString for T {
// --snip--
}</code></pre>
<p>因为标准库有了这些 blanket implementation我们可以对任何实现了 <code>Display</code> trait 的类型调用由 <code>ToString</code> 定义的 <code>to_string</code> 方法。例如,可以将整型转换为对应的 <code>String</code> 值,因为整型实现了 <code>Display</code></p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = 3.to_string();
<span class="boring">}</span></code></pre></pre>
<p>blanket implementation 会出现在 trait 文档的 “Implementers” 部分。</p>
<p>trait 和 trait bound 让我们能够使用泛型类型参数来减少重复,而且能够向编译器明确指定泛型类型需要拥有哪些行为。然后编译器可以利用 trait bound 信息检查代码中所用到的具体类型是否提供了正确的行为。在动态类型语言中如果我们调用了一个未定义的方法会在运行时出现错误。Rust 将这些错误移动到了编译时,甚至在代码能够运行之前就强迫我们修复问题。另外,我们也无需编写运行时检查行为的代码,因为在编译时就已经检查过了。这样既提升了性能又不必放弃泛型的灵活性。</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="ch10-01-syntax.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="ch10-03-lifetime-syntax.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="ch10-01-syntax.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="ch10-03-lifetime-syntax.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js"></script>
<script src="mark.min.js"></script>
<script src="searcher.js"></script>
<script src="clipboard.min.js"></script>
<script src="highlight.js"></script>
<script src="book.js"></script>
<!-- Custom JS scripts -->
<script src="ferris.js"></script>
</div>
</body>
</html>