mirror of
https://github.com/KaiserY/trpl-zh-cn
synced 2024-11-14 21:11:31 +08:00
622 lines
56 KiB
HTML
622 lines
56 KiB
HTML
<!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 href="ch07-02-defining-modules-to-control-scope-and-privacy.html"><strong aria-hidden="true">7.2.</strong> 定义模块来控制作用域与私有性</a></li><li class="chapter-item expanded "><a href="ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html"><strong aria-hidden="true">7.3.</strong> 引用模块项目的路径</a></li><li class="chapter-item expanded "><a href="ch07-04-bringing-paths-into-scope-with-the-use-keyword.html"><strong aria-hidden="true">7.4.</strong> 使用 use 关键字将路径引入作用域</a></li><li class="chapter-item expanded "><a href="ch07-05-separating-modules-into-different-files.html"><strong aria-hidden="true">7.5.</strong> 将模块拆分成多个文件</a></li></ol></li><li class="chapter-item expanded "><a href="ch08-00-common-collections.html"><strong aria-hidden="true">8.</strong> 常见集合</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch08-01-vectors.html"><strong aria-hidden="true">8.1.</strong> 使用 Vector 储存列表</a></li><li class="chapter-item expanded "><a href="ch08-02-strings.html"><strong aria-hidden="true">8.2.</strong> 使用字符串储存 UTF-8 编码的文本</a></li><li class="chapter-item expanded "><a href="ch08-03-hash-maps.html"><strong aria-hidden="true">8.3.</strong> 使用 Hash Map 储存键值对</a></li></ol></li><li class="chapter-item expanded "><a href="ch09-00-error-handling.html"><strong aria-hidden="true">9.</strong> 错误处理</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong aria-hidden="true">9.1.</strong> 用 panic! 处理不可恢复的错误</a></li><li class="chapter-item expanded "><a href="ch09-02-recoverable-errors-with-result.html"><strong aria-hidden="true">9.2.</strong> 用 Result 处理可恢复的错误</a></li><li class="chapter-item expanded "><a href="ch09-03-to-panic-or-not-to-panic.html"><strong aria-hidden="true">9.3.</strong> 要不要 panic!</a></li></ol></li><li class="chapter-item expanded "><a href="ch10-00-generics.html"><strong aria-hidden="true">10.</strong> 泛型、Trait 和生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch10-01-syntax.html"><strong aria-hidden="true">10.1.</strong> 泛型数据类型</a></li><li class="chapter-item expanded "><a href="ch10-02-traits.html" class="active"><strong aria-hidden="true">10.2.</strong> Trait:定义共同行为</a></li><li class="chapter-item expanded "><a href="ch10-03-lifetime-syntax.html"><strong aria-hidden="true">10.3.</strong> 生命周期确保引用有效</a></li></ol></li><li class="chapter-item expanded "><a href="ch11-00-testing.html"><strong aria-hidden="true">11.</strong> 编写自动化测试</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch11-01-writing-tests.html"><strong aria-hidden="true">11.1.</strong> 如何编写测试</a></li><li class="chapter-item expanded "><a href="ch11-02-running-tests.html"><strong aria-hidden="true">11.2.</strong> 控制测试如何运行</a></li><li class="chapter-item expanded "><a href="ch11-03-test-organization.html"><strong aria-hidden="true">11.3.</strong> 测试的组织结构</a></li></ol></li><li class="chapter-item expanded "><a href="ch12-00-an-io-project.html"><strong aria-hidden="true">12.</strong> 一个 I/O 项目:构建命令行程序</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch12-01-accepting-command-line-arguments.html"><strong aria-hidden="true">12.1.</strong> 接受命令行参数</a></li><li class="chapter-item expanded "><a href="ch12-02-reading-a-file.html"><strong aria-hidden="true">12.2.</strong> 读取文件</a></li><li class="chapter-item expanded "><a href="ch12-03-improving-error-handling-and-modularity.html"><strong aria-hidden="true">12.3.</strong> 重构以改进模块化与错误处理</a></li><li class="chapter-item expanded "><a href="ch12-04-testing-the-librarys-functionality.html"><strong aria-hidden="true">12.4.</strong> 采用测试驱动开发完善库的功能</a></li><li class="chapter-item expanded "><a href="ch12-05-working-with-environment-variables.html"><strong aria-hidden="true">12.5.</strong> 处理环境变量</a></li><li class="chapter-item expanded "><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong aria-hidden="true">12.6.</strong> 将错误信息输出到标准错误而不是标准输出</a></li></ol></li><li class="chapter-item expanded "><a href="ch13-00-functional-features.html"><strong aria-hidden="true">13.</strong> Rust 中的函数式语言功能:迭代器与闭包</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch13-01-closures.html"><strong aria-hidden="true">13.1.</strong> 闭包:可以捕获其环境的匿名函数</a></li><li class="chapter-item expanded "><a href="ch13-02-iterators.html"><strong aria-hidden="true">13.2.</strong> 使用迭代器处理元素序列</a></li><li class="chapter-item expanded "><a href="ch13-03-improving-our-io-project.html"><strong aria-hidden="true">13.3.</strong> 改进之前的 I/O 项目</a></li><li class="chapter-item expanded "><a href="ch13-04-performance.html"><strong aria-hidden="true">13.4.</strong> 性能比较:循环对迭代器</a></li></ol></li><li class="chapter-item expanded "><a href="ch14-00-more-about-cargo.html"><strong aria-hidden="true">14.</strong> 更多关于 Cargo 和 Crates.io 的内容</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch14-01-release-profiles.html"><strong aria-hidden="true">14.1.</strong> 采用发布配置自定义构建</a></li><li class="chapter-item expanded "><a href="ch14-02-publishing-to-crates-io.html"><strong aria-hidden="true">14.2.</strong> 将 crate 发布到 Crates.io</a></li><li class="chapter-item expanded "><a href="ch14-03-cargo-workspaces.html"><strong aria-hidden="true">14.3.</strong> Cargo 工作空间</a></li><li class="chapter-item expanded "><a href="ch14-04-installing-binaries.html"><strong aria-hidden="true">14.4.</strong> 使用 cargo install 安装二进制文件</a></li><li class="chapter-item expanded "><a href="ch14-05-extending-cargo.html"><strong aria-hidden="true">14.5.</strong> Cargo 自定义扩展命令</a></li></ol></li><li class="chapter-item expanded "><a href="ch15-00-smart-pointers.html"><strong aria-hidden="true">15.</strong> 智能指针</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch15-01-box.html"><strong aria-hidden="true">15.1.</strong> 使用 Box<T> 指向堆上数据</a></li><li class="chapter-item expanded "><a href="ch15-02-deref.html"><strong aria-hidden="true">15.2.</strong> 使用 Deref Trait 将智能指针当作常规引用处理</a></li><li class="chapter-item expanded "><a href="ch15-03-drop.html"><strong aria-hidden="true">15.3.</strong> 使用 Drop Trait 运行清理代码</a></li><li class="chapter-item expanded "><a href="ch15-04-rc.html"><strong aria-hidden="true">15.4.</strong> Rc<T> 引用计数智能指针</a></li><li class="chapter-item expanded "><a href="ch15-05-interior-mutability.html"><strong aria-hidden="true">15.5.</strong> RefCell<T> 与内部可变性模式</a></li><li class="chapter-item expanded "><a href="ch15-06-reference-cycles.html"><strong aria-hidden="true">15.6.</strong> 引用循环会导致内存泄漏</a></li></ol></li><li class="chapter-item expanded "><a href="ch16-00-concurrency.html"><strong aria-hidden="true">16.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch16-01-threads.html"><strong aria-hidden="true">16.1.</strong> 使用线程同时地运行代码</a></li><li class="chapter-item expanded "><a href="ch16-02-message-passing.html"><strong aria-hidden="true">16.2.</strong> 使用消息传递在线程间通信</a></li><li class="chapter-item expanded "><a href="ch16-03-shared-state.html"><strong aria-hidden="true">16.3.</strong> 共享状态并发</a></li><li class="chapter-item expanded "><a href="ch16-04-extensible-concurrency-sync-and-send.html"><strong aria-hidden="true">16.4.</strong> 使用 Sync 与 Send Traits 的可扩展并发</a></li></ol></li><li class="chapter-item expanded "><a href="ch17-00-oop.html"><strong aria-hidden="true">17.</strong> Rust 的面向对象编程特性</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch17-01-what-is-oo.html"><strong aria-hidden="true">17.1.</strong> 面向对象语言的特点</a></li><li class="chapter-item expanded "><a href="ch17-02-trait-objects.html"><strong aria-hidden="true">17.2.</strong> 顾及不同类型值的 trait 对象</a></li><li class="chapter-item expanded "><a href="ch17-03-oo-design-patterns.html"><strong aria-hidden="true">17.3.</strong> 面向对象设计模式的实现</a></li></ol></li><li class="chapter-item expanded "><a href="ch18-00-patterns.html"><strong aria-hidden="true">18.</strong> 模式与模式匹配</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch18-01-all-the-places-for-patterns.html"><strong aria-hidden="true">18.1.</strong> 所有可能会用到模式的位置</a></li><li class="chapter-item expanded "><a href="ch18-02-refutability.html"><strong aria-hidden="true">18.2.</strong> Refutability(可反驳性): 模式是否会匹配失效</a></li><li class="chapter-item expanded "><a href="ch18-03-pattern-syntax.html"><strong aria-hidden="true">18.3.</strong> 模式语法</a></li></ol></li><li class="chapter-item expanded "><a href="ch19-00-advanced-features.html"><strong aria-hidden="true">19.</strong> 高级特征</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch19-01-unsafe-rust.html"><strong aria-hidden="true">19.1.</strong> 不安全的 Rust</a></li><li class="chapter-item expanded "><a href="ch19-03-advanced-traits.html"><strong aria-hidden="true">19.2.</strong> 高级 trait</a></li><li class="chapter-item expanded "><a href="ch19-04-advanced-types.html"><strong aria-hidden="true">19.3.</strong> 高级类型</a></li><li class="chapter-item expanded "><a href="ch19-05-advanced-functions-and-closures.html"><strong aria-hidden="true">19.4.</strong> 高级函数与闭包</a></li><li class="chapter-item expanded "><a href="ch19-06-macros.html"><strong aria-hidden="true">19.5.</strong> 宏</a></li></ol></li><li class="chapter-item expanded "><a href="ch20-00-final-project-a-web-server.html"><strong aria-hidden="true">20.</strong> 最后的项目:构建多线程 web server</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch20-01-single-threaded.html"><strong aria-hidden="true">20.1.</strong> 建立单线程 web server</a></li><li class="chapter-item expanded "><a href="ch20-02-multithreaded.html"><strong aria-hidden="true">20.2.</strong> 将单线程 server 变为多线程 server</a></li><li class="chapter-item expanded "><a href="ch20-03-graceful-shutdown-and-cleanup.html"><strong aria-hidden="true">20.3.</strong> 优雅停机与清理</a></li></ol></li><li class="chapter-item expanded "><a href="appendix-00.html"><strong aria-hidden="true">21.</strong> 附录</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="appendix-01-keywords.html"><strong aria-hidden="true">21.1.</strong> A - 关键字</a></li><li class="chapter-item expanded "><a href="appendix-02-operators.html"><strong aria-hidden="true">21.2.</strong> B - 运算符与符号</a></li><li class="chapter-item expanded "><a href="appendix-03-derivable-traits.html"><strong aria-hidden="true">21.3.</strong> C - 可派生的 trait</a></li><li class="chapter-item expanded "><a href="appendix-04-useful-development-tools.html"><strong aria-hidden="true">21.4.</strong> D - 实用开发工具</a></li><li class="chapter-item expanded "><a href="appendix-05-editions.html"><strong aria-hidden="true">21.5.</strong> E - 版本</a></li><li class="chapter-item expanded "><a href="appendix-06-translation.html"><strong aria-hidden="true">21.6.</strong> F - 本书译本</a></li><li class="chapter-item expanded "><a href="appendix-07-nightly-rust.html"><strong aria-hidden="true">21.7.</strong> G - Rust 是如何开发的与 “Nightly Rust”</a></li></ol></li></ol>
|
||
</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(&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>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(&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 Tweet {
|
||
pub username: String,
|
||
pub content: String,
|
||
pub reply: bool,
|
||
pub retweet: bool,
|
||
}
|
||
|
||
impl Summary for Tweet {
|
||
fn summarize(&self) -> String {
|
||
format!("{}: {}", 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> trait,crate 的用户可以像调用常规方法一样调用 <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("horse_ebooks"),
|
||
content: String::from(
|
||
"of course, as you probably already know, people",
|
||
),
|
||
reply: false,
|
||
retweet: false,
|
||
};
|
||
|
||
println!("1 new tweet: {}", 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<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 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(&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>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(&self) -> String;
|
||
|
||
fn summarize(&self) -> String {
|
||
format!("(Read more from {}...)", 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(&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 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(&self) -> String {
|
||
format!("@{}", 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("horse_ebooks"),
|
||
content: String::from(
|
||
"of course, as you probably already know, people",
|
||
),
|
||
reply: false,
|
||
retweet: false,
|
||
};
|
||
|
||
println!("1 new tweet: {}", 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(&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 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(&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>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<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>如果 <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: &(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 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(&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 {
|
||
Tweet {
|
||
username: String::from("horse_ebooks"),
|
||
content: String::from(
|
||
"of course, as you probably already know, people",
|
||
),
|
||
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(&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 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(&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 {
|
||
Tweet {
|
||
username: String::from("horse_ebooks"),
|
||
content: String::from(
|
||
"of course, as you probably already know, people",
|
||
),
|
||
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<T></code> 总是实现了 <code>new</code> 方法并返回一个 <code>Pair<T></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<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><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>
|