|
|
<!DOCTYPE HTML>
|
|
|
<html lang="en" class="light sidebar-visible" dir="ltr">
|
|
|
<head>
|
|
|
<!-- Book generated using mdBook -->
|
|
|
<meta charset="UTF-8">
|
|
|
<title>Trait:定义共同行为 - Rust 程序设计语言 简体中文版</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-2459343d.css">
|
|
|
<link rel="stylesheet" href="css/chrome-ae938929.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-d5741f6a.js";
|
|
|
</script>
|
|
|
<!-- Start loading toc.js asap -->
|
|
|
<script src="toc-9d5d6d0e.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">Rust 程序设计语言 简体中文版</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/KaiserY/trpl-zh-cn/tree/main" 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="trait定义共同行为"><a class="header" href="#trait定义共同行为">Trait:定义共同行为</a></h2>
|
|
|
<!-- https://github.com/rust-lang/book/blob/main/src/ch10-02-traits.md -->
|
|
|
<!-- commit e5c8a0c99d5d3d830ad35e67f203a3378b4de16f -->
|
|
|
<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>SocialPost</code> 最多只能存放 280 个字符的内容,以及指示该帖子是新发布的、转发的还是对另一条帖子的回复的元数据。</p>
|
|
|
<p>我们想要创建一个名为 <code>aggregator</code> 的多媒体聚合库用来显示可能储存在 <code>NewsArticle</code> 或 <code>SocialPost</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(&self) -> 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(&self) -> 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>SocialPost</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(&self) -> 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(&self) -> String {
|
|
|
format!("{}, by {} ({})", self.headline, self.author, self.location)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
pub struct SocialPost {
|
|
|
pub username: String,
|
|
|
pub content: String,
|
|
|
pub reply: bool,
|
|
|
pub repost: bool,
|
|
|
}
|
|
|
|
|
|
impl Summary for SocialPost {
|
|
|
fn summarize(&self) -> String {
|
|
|
format!("{}: {}", self.username, self.content)
|
|
|
}
|
|
|
}</code></pre>
|
|
|
<p><span class="caption">示例 10-13:在 <code>NewsArticle</code> 和 <code>SocialPost</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>SocialPost</code> 上实现了<code>Summary</code> trait,crate 的用户可以像调用常规方法一样调用 <code>NewsArticle</code> 和 <code>SocialPost</code> 实例的 trait 方法了。唯一的区别是 trait 必须和类型一起引入作用域以便使用额外的 trait 方法。这是一个二进制 crate 如何利用 <code>aggregator</code> 库 crate 的例子:</p>
|
|
|
<pre><code class="language-rust ignore">use aggregator::{SocialPost, Summary};
|
|
|
|
|
|
fn main() {
|
|
|
let post = SocialPost {
|
|
|
username: String::from("horse_ebooks"),
|
|
|
content: String::from(
|
|
|
"of course, as you probably already know, people",
|
|
|
),
|
|
|
reply: false,
|
|
|
repost: false,
|
|
|
};
|
|
|
|
|
|
println!("1 new post: {}", post.summarize());
|
|
|
}</code></pre>
|
|
|
<p>这会打印出 <code>1 new post: 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>SocialPost</code> 实现如标准库中的 <code>Display</code> trait,这是因为 <code>SocialPost</code> 类型位于 <code>aggregator</code> crate 本地的作用域中。类似地,也可以在 <code>aggregator</code> crate 中为 <code>Vec<T></code> 实现 <code>Summary</code>,这是因为 <code>Summary</code> trait 位于 <code>aggregator</code> crate 本地作用域中。</p>
|
|
|
<p>但是不能为外部类型实现外部 trait。例如,不能在 <code>aggregator</code> crate 中为 <code>Vec<T></code> 实现 <code>Display</code> trait。这是因为 <code>Display</code> 和 <code>Vec<T></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(&self) -> String {
|
|
|
String::from("(Read more...)")
|
|
|
}
|
|
|
}
|
|
|
<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 SocialPost {
|
|
|
</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 repost: bool,
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">impl Summary for SocialPost {
|
|
|
</span><span class="boring"> fn summarize(&self) -> String {
|
|
|
</span><span class="boring"> format!("{}: {}", 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("Penguins win the Stanley Cup Championship!"),
|
|
|
location: String::from("Pittsburgh, PA, USA"),
|
|
|
author: String::from("Iceburgh"),
|
|
|
content: String::from(
|
|
|
"The Pittsburgh Penguins once again are the best \
|
|
|
hockey team in the NHL.",
|
|
|
),
|
|
|
};
|
|
|
|
|
|
println!("New article available! {}", article.summarize());
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>这段代码会打印 <code>New article available! (Read more...)</code>。</p>
|
|
|
<p>为 <code>summarize</code> 创建默认实现并不要求对示例 10-13 中 <code>SocialPost</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(&self) -> String;
|
|
|
|
|
|
fn summarize(&self) -> String {
|
|
|
format!("(Read more from {}...)", self.summarize_author())
|
|
|
}
|
|
|
}
|
|
|
<span class="boring">
|
|
|
</span><span class="boring">pub struct SocialPost {
|
|
|
</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 repost: bool,
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">impl Summary for SocialPost {
|
|
|
</span><span class="boring"> fn summarize_author(&self) -> String {
|
|
|
</span><span class="boring"> format!("@{}", 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(&self) -> String;
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring"> fn summarize(&self) -> String {
|
|
|
</span><span class="boring"> format!("(Read more from {}...)", self.summarize_author())
|
|
|
</span><span class="boring"> }
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">pub struct SocialPost {
|
|
|
</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 repost: bool,
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span>impl Summary for SocialPost {
|
|
|
fn summarize_author(&self) -> String {
|
|
|
format!("@{}", self.username)
|
|
|
}
|
|
|
}</code></pre>
|
|
|
<p>一旦定义了 <code>summarize_author</code>,我们就可以对 <code>SocialPost</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, SocialPost, Summary};
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span> let post = SocialPost {
|
|
|
username: String::from("horse_ebooks"),
|
|
|
content: String::from(
|
|
|
"of course, as you probably already know, people",
|
|
|
),
|
|
|
reply: false,
|
|
|
repost: false,
|
|
|
};
|
|
|
|
|
|
println!("1 new social post: {}", post.summarize());
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>这会打印出 <code>1 new post: (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>SocialPost</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(&self) -> 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(&self) -> String {
|
|
|
</span><span class="boring"> format!("{}, by {} ({})", self.headline, self.author, self.location)
|
|
|
</span><span class="boring"> }
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">pub struct SocialPost {
|
|
|
</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 repost: bool,
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">impl Summary for SocialPost {
|
|
|
</span><span class="boring"> fn summarize(&self) -> String {
|
|
|
</span><span class="boring"> format!("{}: {}", self.username, self.content)
|
|
|
</span><span class="boring"> }
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span>pub fn notify(item: &impl Summary) {
|
|
|
println!("Breaking news! {}", 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>SocialPost</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<T: Summary>(item: &T) {
|
|
|
println!("Breaking news! {}", 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: &impl Summary, item2: &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<T: Summary>(item1: &T, item2: &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>我们也可以指定多个 trait bound。假设我们希望 <code>notify</code> 在 <code>item</code> 上既能使用格式化显示,又能使用 <code>summarize</code> 方法:在 <code>notify</code> 的定义中,指定 <code>item</code> 必须同时实现 <code>Display</code> 和 <code>Summary</code> 两个 trait。这可以通过 <code>+</code> 语法实现:</p>
|
|
|
<pre><code class="language-rust ignore">pub fn notify(item: &(impl Summary + Display)) {</code></pre>
|
|
|
<p><code>+</code> 语法也适用于泛型的 trait bound:</p>
|
|
|
<pre><code class="language-rust ignore">pub fn notify<T: Summary + Display>(item: &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<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {</code></pre>
|
|
|
<p>还可以像这样使用 <code>where</code> 从句:</p>
|
|
|
<pre><code class="language-rust ignore">fn some_function<T, U>(t: &T, u: &U) -> 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(&self) -> 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(&self) -> String {
|
|
|
</span><span class="boring"> format!("{}, by {} ({})", self.headline, self.author, self.location)
|
|
|
</span><span class="boring"> }
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">pub struct SocialPost {
|
|
|
</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 repost: bool,
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">impl Summary for SocialPost {
|
|
|
</span><span class="boring"> fn summarize(&self) -> String {
|
|
|
</span><span class="boring"> format!("{}: {}", self.username, self.content)
|
|
|
</span><span class="boring"> }
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span>fn returns_summarizable() -> impl Summary {
|
|
|
SocialPost {
|
|
|
username: String::from("horse_ebooks"),
|
|
|
content: String::from(
|
|
|
"of course, as you probably already know, people",
|
|
|
),
|
|
|
reply: false,
|
|
|
repost: false,
|
|
|
}
|
|
|
}</code></pre>
|
|
|
<p>通过使用 <code>impl Summary</code> 作为返回值类型,我们指定了 <code>returns_summarizable</code> 函数返回某个实现了 <code>Summary</code> trait 的类型,但是不确定其具体的类型。在这个例子中 <code>returns_summarizable</code> 返回了一个 <code>SocialPost</code>,不过调用方并不知情。</p>
|
|
|
<p>返回一个只是指定了需要实现的 trait 的类型的能力在闭包和迭代器场景十分的有用,第十三章会介绍它们。闭包和迭代器创建只有编译器知道的类型,或者是非常非常长的类型。<code>impl Trait</code> 允许你简单的指定函数返回一个 <code>Iterator</code> 而无需写出实际的冗长的类型。</p>
|
|
|
<p>不过这只适用于返回单一类型的情况。例如,这段代码的返回值类型指定为返回 <code>impl Summary</code>,但是返回了 <code>NewsArticle</code> 或 <code>SocialPost</code> 就行不通:</p>
|
|
|
<pre><code class="language-rust ignore does_not_compile"><span class="boring">pub trait Summary {
|
|
|
</span><span class="boring"> fn summarize(&self) -> 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(&self) -> String {
|
|
|
</span><span class="boring"> format!("{}, by {} ({})", self.headline, self.author, self.location)
|
|
|
</span><span class="boring"> }
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">pub struct SocialPost {
|
|
|
</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 repost: bool,
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span><span class="boring">impl Summary for SocialPost {
|
|
|
</span><span class="boring"> fn summarize(&self) -> String {
|
|
|
</span><span class="boring"> format!("{}: {}", self.username, self.content)
|
|
|
</span><span class="boring"> }
|
|
|
</span><span class="boring">}
|
|
|
</span><span class="boring">
|
|
|
</span>fn returns_summarizable(switch: bool) -> impl Summary {
|
|
|
if switch {
|
|
|
NewsArticle {
|
|
|
headline: String::from(
|
|
|
"Penguins win the Stanley Cup Championship!",
|
|
|
),
|
|
|
location: String::from("Pittsburgh, PA, USA"),
|
|
|
author: String::from("Iceburgh"),
|
|
|
content: String::from(
|
|
|
"The Pittsburgh Penguins once again are the best \
|
|
|
hockey team in the NHL.",
|
|
|
),
|
|
|
}
|
|
|
} else {
|
|
|
SocialPost {
|
|
|
username: String::from("horse_ebooks"),
|
|
|
content: String::from(
|
|
|
"of course, as you probably already know, people",
|
|
|
),
|
|
|
reply: false,
|
|
|
repost: false,
|
|
|
}
|
|
|
}
|
|
|
}</code></pre>
|
|
|
<p>这里尝试返回 <code>NewsArticle</code> 或 <code>SocialPost</code> 是不被允许的,原因在于编译器中 <code>impl Trait</code> 语法的实现限制。第十八章的 <a href="ch18-02-trait-objects.html#顾及不同类型值的-trait-对象">“顾及不同类型值的 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<T></code> 总是实现了 <code>new</code> 方法并返回一个 <code>Pair<T></code> 的实例(回忆一下第五章的 <a href="ch05-03-method-syntax.html#定义方法">“定义方法”</a> 部分,<code>Self</code> 是一个 <code>impl</code> 块类型的类型别名(type alias),在这里是 <code>Pair<T></code>)。不过在下一个 <code>impl</code> 块中,只有那些为 <code>T</code> 类型实现了 <code>PartialOrd</code> trait(来允许比较) <strong>和</strong> <code>Display</code> trait(来启用打印)的 <code>Pair<T></code> 才会实现 <code>cmp_display</code> 方法:</p>
|
|
|
<pre><code class="language-rust noplayground">use std::fmt::Display;
|
|
|
|
|
|
struct Pair<T> {
|
|
|
x: T,
|
|
|
y: T,
|
|
|
}
|
|
|
|
|
|
impl<T> Pair<T> {
|
|
|
fn new(x: T, y: T) -> Self {
|
|
|
Self { x, y }
|
|
|
}
|
|
|
}
|
|
|
|
|
|
impl<T: Display + PartialOrd> Pair<T> {
|
|
|
fn cmp_display(&self) {
|
|
|
if self.x >= self.y {
|
|
|
println!("The largest member is x = {}", self.x);
|
|
|
} else {
|
|
|
println!("The largest member is y = {}", 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<T: Display> 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 class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span>let s = 3.to_string();
|
|
|
<span class="boring">}</span></code></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">
|
|
|
<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="ch10-03-lifetime-syntax.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="ch10-01-syntax.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="ch10-03-lifetime-syntax.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-c2a407aa.js"></script>
|
|
|
|
|
|
<script src="clipboard-1626706a.min.js"></script>
|
|
|
<script src="highlight-abc7f01d.js"></script>
|
|
|
<script src="book-a0b12cfe.js"></script>
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
<script src="ferris-2317480c.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
</body>
|
|
|
</html>
|