trpl-zh-cn/print.html

20016 lines
1.6 MiB
HTML
Raw Normal View History

<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Rust 程序设计语言 简体中文版</title>
<meta name="robots" content="noindex">
<!-- 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.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">
<link rel="stylesheet" href="theme/semantic-notes.css">
<link rel="stylesheet" href="theme/listing.css">
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded affix "><a href="title-page.html">Rust 程序设计语言</a></li><li class="chapter-item expanded affix "><a href="foreword.html">前言</a></li><li class="chapter-item expanded affix "><a href="ch00-00-introduction.html">简介</a></li><li class="chapter-item expanded "><a href="ch01-00-getting-started.html"><strong aria-hidden="true">1.</strong> 入门指南</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch01-01-installation.html"><strong aria-hidden="true">1.1.</strong> 安装</a></li><li class="chapter-item expanded "><a href="ch01-02-hello-world.html"><strong aria-hidden="true">1.2.</strong> Hello, World!</a></li><li class="chapter-item expanded "><a href="ch01-03-hello-cargo.html"><strong aria-hidden="true">1.3.</strong> Hello, Cargo!</a></li></ol></li><li class="chapter-item expanded "><a href="ch02-00-guessing-game-tutorial.html"><strong aria-hidden="true">2.</strong> 写个猜数字游戏</a></li><li class="chapter-item expanded "><a href="ch03-00-common-programming-concepts.html"><strong aria-hidden="true">3.</strong> 常见编程概念</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch03-01-variables-and-mutability.html"><strong aria-hidden="true">3.1.</strong> 变量与可变性</a></li><li class="chapter-item expanded "><a href="ch03-02-data-types.html"><strong aria-hidden="true">3.2.</strong> 数据类型</a></li><li class="chapter-item expanded "><a href="ch03-03-how-functions-work.html"><strong aria-hidden="true">3.3.</strong> 函数</a></li><li class="chapter-item expanded "><a href="ch03-04-comments.html"><strong aria-hidden="true">3.4.</strong> 注释</a></li><li class="chapter-item expanded "><a href="ch03-05-control-flow.html"><strong aria-hidden="true">3.5.</strong> 控制流</a></li></ol></li><li class="chapter-item expanded "><a href="ch04-00-understanding-ownership.html"><strong aria-hidden="true">4.</strong> 认识所有权</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch04-01-what-is-ownership.html"><strong aria-hidden="true">4.1.</strong> 什么是所有权?</a></li><li class="chapter-item expanded "><a href="ch04-02-references-and-borrowing.html"><strong aria-hidden="true">4.2.</strong> 引用与借用</a></li><li class="chapter-item expanded "><a href="ch04-03-slices.html"><strong aria-hidden="true">4.3.</strong> Slice 类型</a></li></ol></li><li class="chapter-item expanded "><a href="ch05-00-structs.html"><strong aria-hidden="true">5.</strong> 使用结构体组织相关联的数据</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch05-01-defining-structs.html"><strong aria-hidden="true">5.1.</strong> 结构体的定义和实例化</a></li><li class="chapter-item expanded "><a href="ch05-02-example-structs.html"><strong aria-hidden="true">5.2.</strong> 结构体示例程序</a></li><li class="chapter-item expanded "><a href="ch05-03-method-syntax.html"><strong aria-hidden="true">5.3.</strong> 方法语法</a></li></ol></li><li class="chapter-item expanded "><a href="ch06-00-enums.html"><strong aria-hidden="true">6.</strong> 枚举和模式匹配</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch06-01-defining-an-enum.html"><strong aria-hidden="true">6.1.</strong> 枚举的定义</a></li><li class="chapter-item expanded "><a href="ch06-02-match.html"><strong aria-hidden="true">6.2.</strong> match 控制流结构</a></li><li class="chapter-item expanded "><a href="ch06-03-if-let.html"><strong aria-hidden="true">6.3.</strong> if let 简洁控制流</a></li></ol></li><li class="chapter-item expanded "><a href="ch07-00-managing-growing-projects-with-packages-crates-and-modules.html"><strong aria-hidden="true">7.</strong> 使用包、Crate 和模块管理不断增长的项目</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch07-01-packages-and-crates.html"><strong aria-hidden="true">7.1.</strong> 包和 Crate</a></li><li class="chapter-item expanded "><a h
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Rust 程序设计语言 简体中文版</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/KaiserY/trpl-zh-cn/tree/main" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
</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>
<h1 id="rust-程序设计语言"><a class="header" href="#rust-程序设计语言">Rust 程序设计语言</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/title-page.md">title-page.md</a>
<br>
commit d94e03a18a2590ed3f1c67b859cb11528d2a2d5c</p>
</blockquote>
<p><strong>本书的英文原版作者为 Steve Klabnik 和 Carol Nichols并由 Rust 社区补充完善。本简体中文译本由 Rust 中文社区翻译。</strong></p>
<p>本书假设你使用 Rust 1.78.02024-05-02 发布)或更新的版本。请查看 <a href="ch01-01-installation.html">第 1 章的 “安装” 部分</a> 了解如何安装和升级 Rust。</p>
<p>本书的英文原版 HTML 格式可以在 <a href="https://doc.rust-lang.org/stable/book/">https://doc.rust-lang.org/stable/book/</a> 在线阅读;使用 <code>rustup</code> 安装的 Rust 也包含一份英文离线版,运行 <code>rustup docs --book</code> 即可打开。</p>
<p>本书还有一些社区 <a href="appendix-06-translation.html">翻译版本</a>。简体中文译本可以在 <a href="https://kaisery.github.io/trpl-zh-cn/">https://kaisery.github.io/trpl-zh-cn/</a> 在线阅读。</p>
<p>本书也有 <a href="https://nostarch.com/rust-programming-language-2nd-edition">由 No Starch Press 出版的纸质版和电子版</a></p>
<blockquote>
<p><strong>🚨 想要具有互动性的学习体验吗?试试 Rust Book 的另一个版本,其中包括测验、高亮、可视化等功能</strong><a href="https://rust-book.cs.brown.edu">https://rust-book.cs.brown.edu</a></p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="前言"><a class="header" href="#前言">前言</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/foreword.md">foreword.md</a>
<br>
commit 1fedfc4b96c2017f64ecfcf41a0a07e2e815f24f</p>
</blockquote>
<p>Rust 程序设计语言的本质实际在于 <strong>赋能</strong><em>empowerment</em>无论你现在编写的是何种代码Rust 能让你在更为广泛的编程领域走得更远,写出自信。(这一点并不显而易见)</p>
<p>举例来说,那些“系统层面”的工作涉及内存管理、数据表示和并发等底层细节。从传统角度来看,这是一个神秘的编程领域,只为浸润多年的极少数人所触及,也只有他们能避开那些臭名昭著的陷阱。即使谨慎的实践者,亦唯恐代码出现漏洞、崩溃或损坏。</p>
<p>Rust 破除了这些障碍:它消除了旧的陷阱,并提供了伴你一路同行的友好、精良的工具。想要 “深入” 底层控制的程序员可以使用 Rust无需时刻担心出现崩溃或安全漏洞也无需因为工具链不靠谱而被迫去了解其中的细节。更妙的是语言设计本身会自然而然地引导你编写出可靠的代码并且运行速度和内存使用上都十分高效。</p>
<p>已经在从事编写底层代码的程序员可以使用 Rust 来提升信心。例如,在 Rust 中引入并行是相对低风险的操作,因为编译器会替你找到经典的错误。同时你可以自信地采取更加激进的优化,而不会意外引入崩溃或漏洞。</p>
<p>但 Rust 并不局限于底层系统编程。它表达力强、写起来舒适,让人能够轻松地编写出命令行应用、网络服务器等各种类型的代码——在本书中就有这两者的简单示例。使用 Rust 能让你把在一个领域中学习的技能延伸到另一个领域:你可以通过编写网页应用来学习 Rust接着将同样的技能应用到你的 Raspberry Pi树莓派上。</p>
<p>本书全面介绍了 Rust 为用户赋予的能力。其内容平易近人,致力于帮助你提升 Rust 的知识,并且提升你作为程序员整体的理解与自信。欢迎你加入 Rust 社区,让我们准备深入学习 Rust 吧!</p>
<p>—— Nicholas Matsakis 和 Aaron Turon</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="简介"><a class="header" href="#简介">简介</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch00-00-introduction.md">ch00-00-introduction.md</a>
<br>
commit 1fb74c3f1d8aeba39373e9f4cdb9a4bdca95604f</p>
</blockquote>
<blockquote>
<p>注意:此书的英文原版与 <a href="https://nostarch.com/">No Starch Press</a> 出版的《<a href="https://nostarch.com/rust-programming-language-2nd-edition">The Rust Programming Language</a>》纸质版和电子版一致。</p>
</blockquote>
<p>欢迎阅读《Rust 程序设计语言》,这是一本关于 Rust 的入门书籍。Rust 程序设计语言能帮助你编写更快、更可靠的软件。在编程语言设计中,高层的工程学与底层的控制往往是难以兼得的;而 Rust 则试图挑战这一矛盾。通过平衡强大的技术能力与优秀的开发者体验Rust 为你提供了控制底层细节(如内存使用)的选项,而无需承受通常与此类控制相关的所有繁琐细节。</p>
<h2 id="rust-适合哪些人"><a class="header" href="#rust-适合哪些人">Rust 适合哪些人</a></h2>
<p>Rust 因多种原因适合许多人。让我们看看几个最重要的群体。</p>
<h3 id="开发者团队"><a class="header" href="#开发者团队">开发者团队</a></h3>
<p>Rust 已证明是一个对于具有不同系统编程知识水平的大型开发团队协作而言,非常高效的工具。底层代码容易出现各种微妙的错误,在大多数其他语言中,这些错误只能通过广泛的测试和经验丰富的开发者的仔细审核代码来捕捉。在 Rust 中,编译器充当了守门员的角色,拒绝编译包含这些难以察觉的错误的代码,包括并发错误。通过与编译器合作,团队可以将时间集中在程序逻辑上,而不是追踪 bug。</p>
<p>Rust 也为系统编程世界带来了现代化的开发工具:</p>
<ul>
<li>Cargo 是内置的依赖管理器和构建工具,它能轻松增加、编译和管理依赖,并使依赖在 Rust 生态系统中保持一致。</li>
<li>Rustfmt 格式化工具确保开发者遵循一致的代码风格。</li>
<li>rust-analyzer 为集成开发环境IDE提供了强大的代码补全和内联错误信息功能。</li>
</ul>
<p>通过使用 Rust 生态系统中丰富的工具,开发者在编写系统级代码时可以更加高效。</p>
<h3 id="学生"><a class="header" href="#学生">学生</a></h3>
<p>Rust 适合学生群体,也适合有兴趣学习系统概念的人。许多人通过 Rust 学习了操作系统开发等主题。社区对学生问题非常欢迎并乐于回答。通过类似这本书以及其他内容的努力Rust 团队希望使系统概念能为更多人所易于理解,特别是编程新手。</p>
<h3 id="公司"><a class="header" href="#公司">公司</a></h3>
<p>数百家大小规模的公司在生产环境中使用 Rust 完成各种任务包括命令行工具、Web 服务、DevOps 工具、嵌入式设备、音视频分析与转码、加密货币、生物信息学、搜索引擎、物联网IOT程序、机器学习甚至是 Firefox 浏览器的重要部分。</p>
<h3 id="开源开发者"><a class="header" href="#开源开发者">开源开发者</a></h3>
<p>Rust 适合那些希望构建 Rust 编程语言、社区、开发工具和库的开发者。我们非常欢迎你为 Rust 语言作出贡献。</p>
<h3 id="重视速度和稳定性的开发者"><a class="header" href="#重视速度和稳定性的开发者">重视速度和稳定性的开发者</a></h3>
<p>Rust 适合那些渴望在编程语言中寻求速度与稳定性的开发者。对于速度来说,既是指 Rust 可以运行的多快,也是指编写 Rust 程序的速度。Rust 编译器的检查确保了增加功能和重构代码时的稳定性这与那些缺乏这些检查的语言中脆弱的祖传代码形成了鲜明对比开发者往往不敢去修改这些代码。通过追求零成本抽象zero-cost abstractions—— 将高级语言特性编译成底层代码并且与手写的代码运行速度同样快。Rust 努力确保代码又安全又快速。</p>
<p>这里提到的只是几个较大的受益群体Rust 语言也希望能支持更多其他用户。总的来说Rust 最重要的目标是消除数十年来程序员习以为常的取舍,让安全和高效、速度和易读易用<strong>可以兼得</strong>。试试看 Rust说不定它的选择就适合你。</p>
<h2 id="本书适合哪些人"><a class="header" href="#本书适合哪些人">本书适合哪些人</a></h2>
<p>本书假设你已经有其他编程语言的经验,任何语言均可,我们尽可能让各种语言背景的人都能读懂。本书的重点不是程序设计<strong>本身</strong>,也不是程序设计思维。如果你完全没学过编程,建议你先阅读专门介绍程序设计的书籍。</p>
<h2 id="如何阅读本书"><a class="header" href="#如何阅读本书">如何阅读本书</a></h2>
<p>本书大体上假设您按从头到尾的顺序阅读。后面的章节建立在前面章节概念的基础上。前面的章节可能不会深入介绍部分主题,而是留待后续章节重新讨论。</p>
<p>本书分为两类章节:概念章节和项目章节。在概念章节中,我们学习 Rust 的某个方面。在项目章节中,我们应用目前所学的知识一同构建小型程序。第二、十二和二十章是项目章节;其余都是概念章节。</p>
<p>第一章介绍如何安装 Rust如何编写一个 “Hello, world!” 程序,以及如何使用 Rust 的包管理器和构建工具 Cargo。第二章是一个编写 Rust 语言的实战介绍,我们会构建一个猜数字游戏。我们会站在较高的层次介绍一些概念,而后续章节将提供更多细节。如果你希望立刻就动手实践一下,第二章是开始的好地方。第三章介绍 Rust 中类似其他编程语言的特性,第四章会学习 Rust 的所有权系统。如果你是一个特别细致的学习者,喜欢在进入下一环节之前学习每一个细节,你可能会想要跳过第二章,直接阅读第三章,等到你想要通过项目应用所学到的细节时再回到第二章。</p>
<p>第五章讨论结构体struct和方法第六章介绍枚举enum<code>match</code> 表达式和 <code>if let</code> 控制流结构。在 Rust 中,创建自定义类型需要用到结构体和枚举。</p>
<p>第七章介绍 Rust 的模块module系统其中的私有性规则用来组织代码和公开的 API应用程序接口。第八章讨论标准库提供的常见集合数据结构例如 Vector向量、字符串和 Hash Map散列表。第九章探索 Rust 的错误处理的理念与技术。</p>
<p>第十章深入介绍泛型generic、Trait 和生命周期lifetime这些功能让你能够定义适用于多种类型的代码。第十一章全面讲述了测试因为就算 Rust 有安全保证,也需要测试确保程序逻辑正确。第十二章中将会构建我们自己的 <code>grep</code> 命令行工具的功能子集实现,用于在文件中搜索文本。为此会用到之前章节讨论的很多概念。</p>
<p>第十三章探索闭包closure和迭代器iterator这两个 Rust 特性来自函数式编程语言。第十四章会深入探讨 Cargo 并介绍分享代码库的最佳实践。第十五章讨论标准库提供的智能指针以及相关的 Trait。</p>
<p>第十六章将引导我们了解不同的并发编程模型,并探讨 Rust 如何帮助你无畏地进行多线程编程。第十七章将在此基础上进一步探索 Rust 的 async 和 await 语法,以及它们所支持的轻量级并发模型。</p>
<p>第十八章着眼于 Rust 风格与你可能比较熟悉的 OOP面向对象编程原则之间的比较。</p>
<p>第十九章介绍模式和模式匹配,它是在 Rust 程序中表达思想的有效方式。第二十章是一个高级主题大杂烩,包括不安全 Rustunsafe Rust、宏macro和更多关于生命周期、Trait、类型、函数和闭包的内容。</p>
<p>第二十一章我们将会完成一个项目,实现一个底层的、多线程的 Web 服务器!</p>
<p>最后的附录包含了一些关于该语言的实用信息,其格式更像是参考资料。附录 A 涵盖了 Rust 的关键字,附录 B 涵盖了 Rust 的运算符和符号,附录 C 涵盖了标准库提供的可派生 Trait附录 D 涵盖了一些有用的开发工具,而附录 E 解释了 Rust 版本。在附录 F 中,你可以找到本书的翻译版本,而在附录 G 中,我们将讨论 Rust 是如何制作的以及什么是 nightly Rust。</p>
<p>阅读本书没有错误的方式:如果你想跳过前面的内容,尽管跳过!如果你遇到任何困惑,可能需要回到前面的章节。请采取对你最有效的方式。</p>
<p><span id="ferris"></span></p>
<p>学习 Rust 的一个重要部分是学会如何阅读编译器显示的错误信息它们会指引你编写出能运行的代码。为此我们将提供许多不能编译的示例以及在每种情况下编译器将显示的错误信息。请知悉如果你输入并运行一个随机示例它可能无法编译确保你阅读了示例周围的文本以判断你尝试运行的示例是否出错。Ferris 也将帮助你区分那些不是意在工作的代码:</p>
<div class="table-wrapper"><table><thead><tr><th>Ferris</th><th>含义</th></tr></thead><tbody>
<tr><td><img src="img/ferris/does_not_compile.svg" class="ferris-explain" alt="Ferris 头上有问号"/></td><td>这段代码无法通过编译!</td></tr>
<tr><td><img src="img/ferris/panics.svg" class="ferris-explain" alt="Ferris 举起两只钳子"/></td><td>这段代码会 Panic</td></tr>
<tr><td><img src="img/ferris/not_desired_behavior.svg" class="ferris-explain" alt="Ferris 举起一只钳子并耸肩"/></td><td>这段代码的运行结果不符合预期。</td></tr>
</tbody></table>
</div>
<p>在大部分情况,我们会指导你将无法通过编译的代码修改为正确版本。</p>
<h2 id="源代码"><a class="header" href="#源代码">源代码</a></h2>
<p>生成本书的源码可以在 <a href="https://github.com/rust-lang/book/tree/main/src">GitHub</a> 上找到。</p>
<blockquote>
<p>译者注:此译本也有 <a href="https://github.com/KaiserY/trpl-zh-cn">GitHub 仓库</a>,欢迎提交 Issue 和 PR :)</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="入门指南"><a class="header" href="#入门指南">入门指南</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch01-00-getting-started.md">ch01-00-getting-started.md</a>
<br>
commit 1fedfc4b96c2017f64ecfcf41a0a07e2e815f24f</p>
</blockquote>
<p>让我们开始 Rust 之旅!有很多内容需要学习,但每次旅程总有起点。在本章中,我们会讨论:</p>
<ul>
<li>在 Linux、macOS 和 Windows 上安装 Rust</li>
<li>编写一个打印 <code>Hello, world!</code> 的程序</li>
<li>使用 Rust 的包管理器和构建系统 <code>cargo</code></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h2 id="安装"><a class="header" href="#安装">安装</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch01-01-installation.md">ch01-01-installation.md</a> <br>
commit d5eb2f7a8e9c6f51b4478f9cd46f55448e2ca2c1</p>
</blockquote>
<p>第一步是安装 Rust。我们会通过 <code>rustup</code> 下载 Rust这是一个管理 Rust 版本和相关工具的命令行工具。下载时需要联网。</p>
<blockquote>
<p>注意:如果你出于某些理由倾向于不使用 <code>rustup</code>,请到 <a href="https://forge.rust-lang.org/infra/other-installation-methods.html">Rust 的其他安装方法页面</a> 查看其它安装选项。</p>
</blockquote>
<p>接下来的步骤会安装最新的稳定版 Rust 编译器。Rust 的稳定性确保本书所有示例在最新版本的 Rust 中能够继续编译。不同版本的输出可能略有不同,因为 Rust 经常改进错误信息和警告。也就是说,任何通过这些步骤安装的最新稳定版 Rust都应该能正常运行本书中的内容。</p>
<blockquote>
<h3 id="命令行标记"><a class="header" href="#命令行标记">命令行标记</a></h3>
<p>本章和全书中,我们会展示一些在终端中使用的命令。所有需要输入到终端的行都以 <code>$</code> 开头。你不需要输入<code>$</code>字符;这里显示的<code>$</code>字符表示命令行提示符,仅用于提示每行命令的起点。不以 <code>$</code> 起始的行通常展示前一个命令的输出。另外PowerShell 专用的示例会采用 <code>&gt;</code> 而不是 <code>$</code></p>
</blockquote>
<h3 id="在-linux-或-macos-上安装-rustup"><a class="header" href="#在-linux-或-macos-上安装-rustup">在 Linux 或 macOS 上安装 <code>rustup</code></a></h3>
<p>如果你使用 Linux 或 macOS打开终端并输入如下命令</p>
<pre><code class="language-console">$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
</code></pre>
<p>此命令下载一个脚本并开始安装 <code>rustup</code> 工具,这会安装最新稳定版 Rust。过程中可能会提示你输入密码。如果安装成功将会出现如下内容</p>
<pre><code class="language-text">Rust is installed now. Great!
</code></pre>
<p>另外,你还需要一个 <em>链接器linker</em>,这是 Rust 用来将其编译的输出连接到一个文件中的程序。很可能你已经有一个了。如果你遇到了链接器错误,请尝试安装一个 C 编译器它通常包括一个链接器。C 编译器也很有用,因为一些常见的 Rust 包依赖于 C 代码,因此需要安装一个 C 编译器。</p>
<p>在 macOS 上,你可以通过运行以下命令获得 C 语言编译器:</p>
<pre><code class="language-console">$ xcode-select --install
</code></pre>
<p>Linux 用户通常需要根据发行版distribution文档安装 GCC 或 Clang。比如如果你使用 Ubuntu可以安装 <code>build-essential</code> 包。</p>
<h3 id="在-windows-上安装-rustup"><a class="header" href="#在-windows-上安装-rustup">在 Windows 上安装 <code>rustup</code></a></h3>
<p>在 Windows 上,前往 <a href="https://www.rust-lang.org/tools/install">https://www.rust-lang.org/install.html</a> 并按照说明安装 Rust。在安装过程的某个步骤你会被提示要安装 Visual Studio。它提供了一个链接器和编译程序所需的原生库。如果你在此步骤需要更多帮助请访问 <a href="https://rust-lang.github.io/rustup/installation/windows-msvc.html">https://rust-lang.github.io/rustup/installation/windows-msvc.html</a></p>
<p>本书的余下部分会使用能同时运行于 <em>cmd.exe</em> 和 PowerShell 的命令。如果存在特定差异,我们会解释使用哪一个。</p>
<h3 id="故障排除troubleshooting"><a class="header" href="#故障排除troubleshooting">故障排除Troubleshooting</a></h3>
<p>要检查是否正确安装了 Rust打开命令行并输入</p>
<pre><code class="language-console">$ rustc --version
</code></pre>
<p>你应该可以看到按照以下格式显示的最新稳定版本的版本号、对应的 Commit Hash 和 Commit 日期:</p>
<pre><code class="language-text">rustc x.y.z (abcabcabc yyyy-mm-dd)
</code></pre>
<p>如果看到了这样的信息,就说明 Rust 已经安装成功了!</p>
<blockquote>
<p>译者:恭喜入坑!(此处应该有掌声!)</p>
</blockquote>
<p>如果没看到,请按照下面说明的方法检查 Rust 是否在您的 <code>%PATH%</code> 系统变量中。</p>
<p>在 Windows CMD 中,请使用命令:</p>
<pre><code class="language-console">&gt; echo %PATH%
</code></pre>
<p>在 PowerShell 中,请使用命令:</p>
<pre><code class="language-powershell">&gt; echo $env:Path
</code></pre>
<p>在 Linux 和 macOS 中,请使用命令:</p>
<pre><code class="language-console">$ echo $PATH
</code></pre>
<p>如果一切正确但 Rust 仍不能使用,有许多地方可以求助。您可以在<a href="https://www.rust-lang.org/community">社区页面</a>查看如何与其他 RustaceansRust 用户的称号,有自嘲意味)联系。</p>
<h2 id="更新与卸载"><a class="header" href="#更新与卸载">更新与卸载</a></h2>
<p>通过 <code>rustup</code> 安装了 Rust 之后,更新到最新版本就很简单了,只需要在您对应的命令行中运行如下更新脚本:</p>
<pre><code class="language-console">$ rustup update
</code></pre>
<p>若要卸载 Rust 和 <code>rustup</code>,请在命令行中运行如下卸载脚本:</p>
<pre><code class="language-console">$ rustup self uninstall
</code></pre>
<h3 id="本地文档"><a class="header" href="#本地文档">本地文档</a></h3>
<p>安装程序也自带一份文档的本地拷贝,可以离线阅读。运行 <code>rustup doc</code> 在浏览器中查看本地文档。</p>
<p>任何时候如果你拿不准标准库中的类型或函数的用途和用法请查阅应用程序接口application programming interfaceAPI文档</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="hello-world"><a class="header" href="#hello-world">Hello, World!</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch01-02-hello-world.md">ch01-02-hello-world.md</a>
<br>
commit 1fb74c3f1d8aeba39373e9f4cdb9a4bdca95604f</p>
</blockquote>
<p>既然安装好了 Rust是时候来编写第一个 Rust 程序了。当学习一门新语言的时候,使用该语言在屏幕上打印 <code>Hello, world!</code> 是一项传统,我们将沿用这一传统!</p>
<blockquote>
<p>注意本书假设你熟悉基本的命令行操作。Rust 对于你的编辑器、工具以及代码位于何处并没有特定的要求如果你更倾向于使用集成开发环境IDE而不是命令行请尽管使用你喜欢的 IDE。目前很多 IDE 都在一定程度上支持 Rust查看 IDE 文档以了解更多细节。Rust 团队一直致力于借助 <code>rust-analyzer</code> 提供强大的 IDE 支持。详见<a href="appendix-04-useful-development-tools.html">附录 D</a><!-- ignore --></p>
</blockquote>
<h3 id="创建项目目录"><a class="header" href="#创建项目目录">创建项目目录</a></h3>
<p>首先创建一个存放 Rust 代码的目录。Rust 并不关心代码的存放位置,不过对于本书的练习和项目来说,我们建议你在 home 目录中创建 <em>projects</em> 目录,并将你的所有项目存放在这里。</p>
<p>打开终端并输入如下命令创建 <em>projects</em> 目录,并在 <em>projects</em> 目录中为 “Hello, world!” 项目创建一个目录。</p>
<p>对于 Linux、macOS 和 Windows PowerShell输入</p>
<pre><code class="language-console">$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
</code></pre>
<p>对于 Windows CMD输入</p>
<pre><code class="language-doscon">&gt; mkdir "%USERPROFILE%\projects"
&gt; cd /d "%USERPROFILE%\projects"
&gt; mkdir hello_world
&gt; cd hello_world
</code></pre>
<h3 id="编写并运行-rust-程序"><a class="header" href="#编写并运行-rust-程序">编写并运行 Rust 程序</a></h3>
<p>接下来,新建一个源文件,命名为 <em>main.rs</em>。Rust 源文件总是以 <em>.rs</em> 扩展名结尾。如果文件名包含多个单词,那么按照命名习惯,应当使用下划线来分隔单词。例如命名为 <em>hello_world.rs</em>,而不是 <em>helloworld.rs</em></p>
<p>现在打开刚创建的 <em>main.rs</em> 文件,输入示例 1-1 中的代码。</p>
<figure class="listing">
<p><span class="file-name">文件名main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
println!("Hello, world!");
}</code></pre></pre>
<figcaption>示例 1-1一个打印 `Hello, world!` 的程序</figcaption>
</figure>
<p>保存文件,并回到当前目录为“~/projects/hello_world”的终端窗口。在 Linux 或 macOS 上,输入如下命令,编译并运行文件:</p>
<pre><code class="language-console">$ rustc main.rs
$ ./main
Hello, world!
</code></pre>
<p>在 Windows 上,输入命令 <code>.\main.exe</code>,而不是 <code>./main</code></p>
<pre><code class="language-powershell">&gt; rustc main.rs
&gt; .\main.exe
Hello, world!
</code></pre>
<p>不管使用何种操作系统,终端应该打印字符串 <code>Hello, world!</code>。如果没有看到这些输出,回到安装部分的 <a href="ch01-01-installation.html#%E6%95%85%E9%9A%9C%E6%8E%92%E9%99%A4troubleshooting">“故障排除”</a> 小节查找有帮助的方法。</p>
<p>如果 <code>Hello, world!</code> 出现了,恭喜你!你已经正式编写了一个 Rust 程序。现在你成为一名 Rust 程序员,欢迎!</p>
<h3 id="分析这个-rust-程序"><a class="header" href="#分析这个-rust-程序">分析这个 Rust 程序</a></h3>
<p>现在,让我们回过头来仔细看看这个 “Hello, world!” 程序。这是第一块拼图:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
}</code></pre></pre>
<p>这几行定义了一个名叫 <code>main</code> 的函数。<code>main</code> 函数是一个特殊的函数:在可执行的 Rust 程序中,它总是最先运行的代码。第一行代码声明了一个叫做 <code>main</code> 的函数,它没有参数也没有返回值。如果有参数的话,它们的名称应该出现在小括号 <code>()</code> 中。</p>
<p>函数体被包裹在 <code>{}</code> 中。Rust 要求所有函数体都要用花括号包裹起来。一般来说,将左花括号与函数声明置于同一行并以空格分隔,是良好的代码风格。</p>
<blockquote>
<p>注:如果你希望在 Rust 项目中保持一种标准风格,可以使用名为 <code>rustfmt</code> 的自动格式化工具将代码格式化为特定的风格(更多内容详见<a href="appendix-04-useful-development-tools.html">附录 D</a> 中的 <code>rustfmt</code><!-- ignore -->。Rust 团队已经在标准的 Rust 发行版中包含了这个工具,就像 <code>rustc</code> 一样。所以它应该已经安装在你的电脑中了!</p>
</blockquote>
<p><code>main</code> 函数中有如下代码:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span> println!("Hello, world!");
<span class="boring">}</span></code></pre></pre>
<p>这行代码完成这个简单程序的所有工作:在屏幕上打印文本。这里有四个重要的细节需要注意。首先 Rust 的缩进风格使用 4 个空格,而不是 1 个制表符tab</p>
<p>第二,<code>println!</code> 调用了一个 Rust 宏macro。如果是调用函数则应输入 <code>println</code>(没有<code>!</code>)。我们将在第二十章详细讨论宏。现在你只需记住,当看到符号 <code>!</code> 的时候,就意味着调用的是宏而不是普通函数,并且宏并不总是遵循与函数相同的规则。</p>
<p>第三,<code>"Hello, world!"</code> 是一个字符串。我们把这个字符串作为一个参数传递给 <code>println!</code>,字符串将被打印到屏幕上。</p>
<p>第四,该行以分号结尾(<code>;</code>),这代表一个表达式的结束和下一个表达式的开始。大部分 Rust 代码行以分号结尾。</p>
<h3 id="编译和运行是彼此独立的步骤"><a class="header" href="#编译和运行是彼此独立的步骤">编译和运行是彼此独立的步骤</a></h3>
<p>你刚刚运行了一个新创建的程序,那么让我们检查此过程中的每一个步骤。</p>
<p>在运行 Rust 程序之前,必须先使用 Rust 编译器编译它,即输入 <code>rustc</code> 命令并传入源文件名称,如下:</p>
<pre><code class="language-console">$ rustc main.rs
</code></pre>
<p>如果你有 C 或 C++ 背景,就会发现这与 <code>gcc</code><code>clang</code> 类似。编译成功后Rust 会输出一个二进制的可执行文件。</p>
<p>在 Linux、macOS 或 Windows 的 PowerShell 上,在 shell 中输入 <code>ls</code> 命令可以看见这个可执行文件。</p>
<pre><code class="language-console">$ ls
main main.rs
</code></pre>
<p>在 Linux 和 macOS你会看到两个文件。在 Windows PowerShell 中,你会看到同使用 CMD 相同的三个文件。在 Windows 的 CMD 上,则输入如下内容:</p>
<pre><code class="language-doscon">&gt; dir /B %= the /B option says to only show the file names =%
main.exe
main.pdb
main.rs
</code></pre>
<p>这展示了扩展名为 <em>.rs</em> 的源文件、可执行文件(在 Windows 下是 <em>main.exe</em>,其它平台是 <em>main</em>),以及当使用 CMD 时会有一个包含调试信息、扩展名为 <em>.pdb</em> 的文件。从这里开始运行 <em>main</em><em>main.exe</em> 文件,如下:</p>
<pre><code class="language-console">$ ./main # Windows 是 .\main.exe
</code></pre>
<p>如果这里的 <em>main.rs</em> 是上文所述的 “Hello, world!” 程序,那么在终端上就会打印出 <code>Hello, world!</code></p>
<p>如果你更熟悉动态语言,如 Ruby、Python 或 JavaScript则可能不习惯将编译和运行分为两个单独的步骤。Rust 是一种 <strong>预编译静态类型</strong><em>ahead-of-time compiled</em>)语言,这意味着你可以编译程序,并将可执行文件送给其他人,他们甚至不需要安装 Rust 就可以运行。如果你给他人一个 <em>.rb</em><em>.py</em><em>.js</em> 文件,他们需要先分别安装 RubyPythonJavaScript 实现运行时环境VM。不过在这些语言中只需要一句命令就可以编译和运行程序。这一切都是语言设计上的权衡取舍。</p>
<p>仅仅使用 <code>rustc</code> 编译简单程序是没问题的,不过随着项目的增长,你可能需要管理你项目的方方面面,并让代码易于分享。接下来,我们要介绍一个叫做 Cargo 的工具,它会帮助你编写真实世界中的 Rust 程序。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="hello-cargo"><a class="header" href="#hello-cargo">Hello, Cargo!</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch01-03-hello-cargo.md">ch01-03-hello-cargo.md</a>
<br>
commit 299fd1f3e11dd61ca136fb51d713f6b0ba7515ff</p>
</blockquote>
<p>Cargo 是 Rust 的构建系统和包管理器。大多数 Rustacean 们使用 Cargo 来管理他们的 Rust 项目,因为它可以为你处理很多任务,比如构建代码、下载依赖库并编译这些库。(我们把代码所需要的库叫做 <strong>依赖</strong><em>dependencies</em>))。</p>
<p>最简单的 Rust 程序,比如我们刚刚编写的,没有任何依赖。如果使用 Cargo 来构建 “Hello, world!” 项目,将只会用到 Cargo 构建代码的那部分功能。在编写更复杂的 Rust 程序时,你将添加依赖项,如果使用 Cargo 启动项目,则添加依赖项将更容易。</p>
<p>由于绝大多数 Rust 项目使用 Cargo本书接下来的部分假设你也使用 Cargo。如果使用 <a href="ch01-01-installation.html#%E5%AE%89%E8%A3%85">“安装”</a> 部分介绍的官方安装包的话,则自带了 Cargo。如果通过其他方式安装的话可以在终端输入如下命令检查是否安装了 Cargo</p>
<pre><code class="language-console">$ cargo --version
</code></pre>
<p>如果你看到了版本号,说明已安装!如果看到类似 <code>command not found</code> 的错误,你应该查看相应安装文档以确定如何单独安装 Cargo。</p>
<h3 id="使用-cargo-创建项目"><a class="header" href="#使用-cargo-创建项目">使用 Cargo 创建项目</a></h3>
<p>我们使用 Cargo 创建一个新项目,然后看看与上面的 “Hello, world!” 项目有什么不同。回到 <em>projects</em> 目录(或者你存放代码的目录)。接着,可在任何操作系统下运行以下命令:</p>
<pre><code class="language-console">$ cargo new hello_cargo
$ cd hello_cargo
</code></pre>
<p>第一行命令新建了名为 <em>hello_cargo</em> 的目录和项目。我们将项目命名为 <em>hello_cargo</em>,同时 Cargo 在一个同名目录中创建项目文件。</p>
<p>进入 <em>hello_cargo</em> 目录并列出文件。将会看到 Cargo 生成了两个文件和一个目录:一个 <em>Cargo.toml</em> 文件,一个 <em>src</em> 目录,以及位于 <em>src</em> 目录中的 <em>main.rs</em> 文件。</p>
<p>这也会在 <em>hello_cargo</em> 目录初始化了一个 git 仓库,以及一个 <em>.gitignore</em> 文件。如果在一个已经存在的 git 仓库中运行 <code>cargo new</code>,则这些 git 相关文件则不会生成;可以通过运行 <code>cargo new --vcs=git</code> 来覆盖这些行为。</p>
<blockquote>
<p>注意Git 是一个常用的版本控制系统version control systemVCS。可以通过 <code>--vcs</code> 参数使 <code>cargo new</code> 切换到其它版本控制系统VCS或者不使用 VCS。运行 <code>cargo new --help</code> 参看可用的选项。</p>
</blockquote>
<p>请自行选用文本编辑器打开 <em>Cargo.toml</em> 文件。它应该看起来如示例 1-2 所示:</p>
<figure class="listing">
<p><span class="file-name">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
</code></pre>
<figcaption>示例 1-2*cargo new* 命令生成的 *Cargo.toml* 的内容</figcaption>
</figure>
<p>这个文件使用 <a href="https://toml.io"><em>TOML</em></a><!-- ignore --> (<em>Tom's Obvious, Minimal Language</em>) 格式,这是 Cargo 配置文件的格式。</p>
<p>第一行,<code>[package]</code>是一个片段section标题表明下面的语句用来配置一个包。随着我们在这个文件增加更多的信息还将增加其他片段section</p>
<p>接下来的三行设置了 Cargo 编译程序所需的配置:项目的名称、项目的版本以及要使用的 Rust 版本。<a href="appendix-05-editions.html">附录 E</a> 会介绍 <code>edition</code> 的值。</p>
<p>最后一行,<code>[dependencies]</code>,是罗列项目依赖的片段的开始。在 Rust 中,代码包被称为 <em>crates</em>。这个项目并不需要其他的 crate不过在第二章的第一个项目会用到依赖那时会用得上这个片段。</p>
<p>现在打开 <em>src/main.rs</em> 看看:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
println!("Hello, world!");
}</code></pre></pre>
<p>Cargo 为你生成了一个 “Hello, world!” 程序,正如我们之前编写的示例 1-1目前为止我们的项目与 Cargo 生成项目的区别是 Cargo 将代码放在 <em>src</em> 目录,同时项目根目录包含一个 <em>Cargo.toml</em> 配置文件。</p>
<p>Cargo 期望源文件存放在 <em>src</em> 目录中。项目根目录只存放 README、license 信息、配置文件和其他跟代码无关的文件。使用 Cargo 帮助你保持项目干净整洁,一切井井有条。</p>
<p>如果没有使用 Cargo 开始项目,比如我们创建的 “Hello, world!” 项目,你可以将其转换为使用 Cargo 的项目。将项目代码移入 <em>src</em> 目录,并创建一个合适的 <em>Cargo.toml</em> 文件。一个简单的创建 <em>Cargo.toml</em> 文件的方法是运行 <code>cargo init</code>,它会自动为你创建该文件。</p>
<h3 id="构建并运行-cargo-项目"><a class="header" href="#构建并运行-cargo-项目">构建并运行 Cargo 项目</a></h3>
<p>现在让我们看看通过 Cargo 构建和运行 “Hello, world!” 程序有什么不同!在 <em>hello_cargo</em> 目录下,输入下面的命令来构建项目:</p>
<pre><code class="language-console">$ cargo build
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
</code></pre>
<p>这个命令会创建一个可执行文件 <em>target/debug/hello_cargo</em> (在 Windows 上是 <em>target\debug\hello_cargo.exe</em>而不是放在目前目录下。由于默认的构建方法是调试构建debug buildCargo 会将可执行文件放在名为 <em>debug</em> 的目录中。可以通过这个命令运行可执行文件:</p>
<pre><code class="language-console">$ ./target/debug/hello_cargo # 或者在 Windows 下为 .\target\debug\hello_cargo.exe
Hello, world!
</code></pre>
<p>如果一切顺利,终端上应该会打印出 <code>Hello, world!</code>。首次运行 <code>cargo build</code> 时,也会使 Cargo 在项目根目录创建一个新文件:<em>Cargo.lock</em>。这个文件记录项目依赖的实际版本。这个项目并没有依赖,所以其内容比较少。你自己永远也不需要碰这个文件,让 Cargo 处理它就行了。</p>
<p>我们刚刚使用 <code>cargo build</code> 构建了项目,并使用 <code>./target/debug/hello_cargo</code> 运行了程序,也可以使用 <code>cargo run</code> 在一个命令中同时编译并运行生成的可执行文件:</p>
<pre><code class="language-console">$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/hello_cargo`
Hello, world!
</code></pre>
<p>比起要记得运行 <code>cargo build</code> 之后再用可执行文件的完整路径来运行程序,使用 <code>cargo run</code> 可以实现完全相同的效果,而且要方便得多,所以大多数开发者会使用 <code>cargo run</code></p>
<p>注意这一次并没有出现表明 Cargo 正在编译 <code>hello_cargo</code> 的输出。Cargo 发现文件并没有被改变所以它并没有重新编译而是直接运行了可执行文件。如果修改了源文件的话Cargo 会在运行之前重新构建项目,并会出现像这样的输出:</p>
<pre><code class="language-console">$ cargo run
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs
Running `target/debug/hello_cargo`
Hello, world!
</code></pre>
<p>Cargo 还提供了一个叫 <code>cargo check</code> 的命令。该命令快速检查代码确保其可以编译,但并不产生可执行文件:</p>
<pre><code class="language-console">$ cargo check
Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
</code></pre>
<p>为什么你会不需要可执行文件呢?通常 <code>cargo check</code> 要比 <code>cargo build</code> 快得多,因为它省略了生成可执行文件的步骤。如果你在编写代码时持续的进行检查,<code>cargo check</code> 可以让你快速了解现在的代码能不能正常通过编译!为此很多 Rustaceans 编写代码时定期运行 <code>cargo check</code> 确保它们可以编译。当准备好使用可执行文件时才运行 <code>cargo build</code></p>
<p>我们回顾下已学习的 Cargo 内容:</p>
<ul>
<li>可以使用 <code>cargo new</code> 创建项目。</li>
<li>可以使用 <code>cargo build</code> 构建项目。</li>
<li>可以使用 <code>cargo run</code> 一步构建并运行项目。</li>
<li>可以使用 <code>cargo check</code> 在不生成二进制文件的情况下构建项目来检查错误。</li>
<li>有别于将构建结果放在与源码相同的目录Cargo 会将其放到 <em>target/debug</em> 目录。</li>
</ul>
<p>使用 Cargo 的一个额外的优点是,不管你使用什么操作系统,其命令都是一样的。所以从现在开始本书将不再为 Linux 和 macOS 以及 Windows 提供相应的命令。</p>
<h3 id="发布release构建"><a class="header" href="#发布release构建">发布release构建</a></h3>
<p>当项目最终准备好发布时,可以使用 <code>cargo build --release</code> 来优化编译项目。这会在 <em>target/release</em> 而不是 <em>target/debug</em> 下生成可执行文件。这些优化可以让 Rust 代码运行的更快,不过启用这些优化也需要消耗更长的编译时间。这也就是为什么会有两种不同的配置:一种是为了开发,你需要经常快速重新构建;另一种是为用户构建最终程序,它们不会经常重新构建,并且希望程序运行得越快越好。如果你在测试代码的运行时间,请确保运行 <code>cargo build --release</code> 并使用 <em>target/release</em> 下的可执行文件进行测试。</p>
<h3 id="把-cargo-当作习惯"><a class="header" href="#把-cargo-当作习惯">把 Cargo 当作习惯</a></h3>
<p>对于简单项目Cargo 并不比 <code>rustc</code> 提供了更多的优势,不过随着开发的深入,终将证明其价值。一旦程序壮大到由多个文件组成,亦或者是需要其他的依赖,让 Cargo 协调构建过程就会简单得多。</p>
<p>即便 <code>hello_cargo</code> 项目十分简单,它现在也使用了很多在你之后的 Rust 生涯将会用到的实用工具。其实,要在任何已存在的项目上工作时,可以使用如下命令通过 Git 检出代码,移动到该项目目录并构建:</p>
<pre><code class="language-console">$ git clone example.org/someproject
$ cd someproject
$ cargo build
</code></pre>
<p>关于更多 Cargo 的信息,请查阅 <a href="https://doc.rust-lang.org/cargo/">其文档</a></p>
<h2 id="总结"><a class="header" href="#总结">总结</a></h2>
<p>你已经准备好开启 Rust 之旅了!在本章中,你学习了如何:</p>
<ul>
<li>使用 <code>rustup</code> 安装最新稳定版的 Rust</li>
<li>更新到新版的 Rust</li>
<li>打开本地安装的文档</li>
<li>直接通过 <code>rustc</code> 编写并运行 Hello, world! 程序</li>
<li>使用 Cargo 创建并运行新项目</li>
</ul>
<p>是时候通过构建更实质性的程序来熟悉读写 Rust 代码了。所以在第二章我们会构建一个猜猜看游戏程序。如果你更愿意从学习 Rust 常用的编程概念开始,请阅读第三章,接着再回到第二章。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="写个猜数字游戏"><a class="header" href="#写个猜数字游戏">写个猜数字游戏</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch02-00-guessing-game-tutorial.md">ch02-00-guessing-game-tutorial.md</a>
<br>
commit 11ca3d508b0a28b03f7d9f16c88726088fafd87e</p>
</blockquote>
<p>让我们一起动手完成一个项目来快速上手 Rust本章将介绍一些 Rust 中常见的概念,并通过真实的程序来展示如何运用它们。你将会学到 <code>let</code><code>match</code>、方法methods、关联函数associated functions、外部 crate 等知识!后续章节会深入探讨这些概念的细节。在这一章,我们将主要练习基础内容。</p>
<p>我们会实现一个经典的新手编程问题:猜数字游戏。游戏的规则如下:程序将会生成一个 1 到 100 之间的随机整数。然后提示玩家输入一个猜测值。输入后,程序会指示该猜测是太低还是太高。如果猜对了,游戏会打印祝贺信息并退出。</p>
<h2 id="准备一个新项目"><a class="header" href="#准备一个新项目">准备一个新项目</a></h2>
<p>要创建一个新项目,进入第一章中创建的 <em>projects</em> 目录,使用 Cargo 新建一个项目,如下:</p>
<pre><code class="language-console">$ cargo new guessing_game
$ cd guessing_game
</code></pre>
<p>第一个命令,<code>cargo new</code>,它获取项目的名称(<code>guessing_game</code>)作为第一个参数。第二个命令进入到新创建的项目目录。</p>
<p>看看生成的 <em>Cargo.toml</em> 文件:</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
</code></pre>
<p>正如第一章那样,<code>cargo new</code> 生成了一个 “Hello, world!” 程序。查看 <em>src/main.rs</em> 文件:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
println!("Hello, world!");
}</code></pre></pre>
<p>现在使用 <code>cargo run</code> 命令,一步完成 “Hello, world!” 程序的编译和运行:</p>
<pre><code class="language-console">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.50s
Running `target/debug/guessing_game`
Hello, world!
</code></pre>
<p>当你需要在项目中快速迭代时,<code>run</code> 命令就能派上用场,正如我们在这个游戏项目中做的,在下一次迭代之前快速测试每一次迭代。</p>
<p>重新打开 <em>src/main.rs</em> 文件。我们将会在这个文件中编写全部的代码。</p>
<h2 id="处理一次猜测"><a class="header" href="#处理一次猜测">处理一次猜测</a></h2>
<p>猜数字程序的第一部分请求和处理用户输入,并检查输入是否符合预期的格式。首先,我们会允许玩家输入一个猜测。在 <em>src/main.rs</em> 中输入示例 2-1 中的代码。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&amp;mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
}</code></pre>
<figcaption>示例 2-1获取用户猜测并打印的代码</figcaption>
</figure>
<p>这些代码包含很多信息,我们一行一行地过一遍。为了获取用户输入并打印结果作为输出,我们需要将 <code>io</code> 输入/输出库引入当前作用域。<code>io</code> 库来自于标准库,也被称为 <code>std</code></p>
<pre><code class="language-rust ignore">use std::io;
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {}", guess);
</span><span class="boring">}</span></code></pre>
<p>默认情况下Rust 设定了若干个会自动导入到每个程序作用域中的标准库内容,这组内容被称为 <em>预导入prelude</em> 内容。你可以在<a href="https://doc.rust-lang.org/std/prelude/index.html">标准库文档</a>中查看预导入的所有内容。</p>
<p>如果你需要的类型不在预导入内容中,就必须使用 <code>use</code> 语句显式地将其引入作用域。<code>std::io</code> 库提供很多有用的功能,包括接收用户输入的功能。</p>
<p>如第一章所提及,<code>main</code> 函数是程序的入口点:</p>
<pre><code class="language-rust ignore"><span class="boring">use std::io;
</span><span class="boring">
</span>fn main() {
<span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {}", guess);
</span><span class="boring">}</span></code></pre>
<p><code>fn</code> 语法声明了一个新函数,小括号 <code>()</code> 表明没有参数,大括号 <code>{</code> 作为函数体的开始。</p>
<p>第一章也提及了 <code>println!</code> 是一个在屏幕上打印字符串的宏:</p>
<pre><code class="language-rust ignore"><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span> println!("Guess the number!");
println!("Please input your guess.");
<span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {}", guess);
</span><span class="boring">}</span></code></pre>
<p>这些代码仅仅打印提示,介绍游戏的内容然后请求用户输入。</p>
<h3 id="使用变量储存值"><a class="header" href="#使用变量储存值">使用变量储存值</a></h3>
<p>接下来,创建一个 <strong>变量</strong><em>variable</em>)来储存用户输入,像这样:</p>
<pre><code class="language-rust ignore"><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span> let mut guess = String::new();
<span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {}", guess);
</span><span class="boring">}</span></code></pre>
<p>现在程序开始变得有意思了!这一小行代码发生了很多事。我们使用 <code>let</code> 语句来创建变量。这里是另外一个例子:</p>
<pre><code class="language-rust ignore">let apples = 5;</code></pre>
<p>这行代码新建了一个叫做 <code>apples</code> 的变量并把它绑定到值 <code>5</code> 上。在 Rust 中,变量默认是不可变的,这意味着一旦我们给变量赋值,这个值就不再可以修改了。我们将会在第三章的 <a href="ch03-01-variables-and-mutability.html#%E5%8F%98%E9%87%8F%E5%92%8C%E5%8F%AF%E5%8F%98%E6%80%A7">“变量与可变性”</a> 部分详细讨论这个概念。下面的例子展示了如何在变量名前使用 <code>mut</code> 来使一个变量可变:</p>
<pre><code class="language-rust ignore">let apples = 5; // 不可变
let mut bananas = 5; // 可变</code></pre>
<blockquote>
<p>注意:<code>//</code> 语法开始一个注释持续到行尾。Rust 忽略注释中的所有内容,<a href="ch03-04-comments.html">第三章</a>将会详细介绍注释。</p>
</blockquote>
<p>回到猜数字程序中。现在我们知道了 <code>let mut guess</code> 会引入一个叫做 <code>guess</code> 的可变变量。等号(<code>=</code>)告诉 Rust 我们现在想将某个值绑定在变量上。等号的右边是 <code>guess</code> 所绑定的值,它是 <code>String::new</code> 的结果,这个函数会返回一个 <code>String</code> 的新实例。<a href="https://doc.rust-lang.org/std/string/struct.String.html"><code>String</code></a><!-- ignore --> 是一个标准库提供的字符串类型,它是 UTF-8 编码的可增长文本块。</p>
<p><code>::new</code> 那一行的 <code>::</code> 语法表明 <code>new</code><code>String</code> 类型的一个 <strong>关联函数</strong><em>associated function</em>)。关联函数是针对某个类型实现的函数,在这个例子中是 <code>String</code>。这个 <code>new</code> 函数创建了一个新的空字符串。你会发现许多类型上都有一个 <code>new</code> 函数,因为这是为某种类型创建新值的常用函数名。</p>
<p>总的来说,<code>let mut guess = String::new();</code> 这一行创建了一个可变变量,当前它绑定到一个新的 <code>String</code> 空实例上。</p>
<h3 id="接收用户输入"><a class="header" href="#接收用户输入">接收用户输入</a></h3>
<p>回忆一下,我们在程序的第一行使用 <code>use std::io;</code> 从标准库中引入了输入/输出功能。现在调用 <code>io</code> 库中的函数 <code>stdin</code>,这允许我们处理用户输入:</p>
<pre><code class="language-rust ignore"><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span> io::stdin()
.read_line(&amp;mut guess)
<span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {}", guess);
</span><span class="boring">}</span></code></pre>
<p>如果程序的开头没有使用 <code>use std::io;</code> 引入 <code>io</code> 库,我们仍可以通过把函数调用写成 <code>std::io::stdin</code> 来使用该函数。<code>stdin</code> 函数返回一个 <a href="https://doc.rust-lang.org/std/io/struct.Stdin.html"><code>std::io::Stdin</code></a><!-- ignore --> 的实例,这是一种代表终端标准输入句柄的类型。</p>
<p>接下来,代码中的 <code>.read_line(&amp;mut guess)</code> 调用了标准输入句柄上的 <a href="https://doc.rust-lang.org/std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> 方法,以获取用户输入。我们还将 <code>&amp;mut guess</code> 作为参数传递给 <code>read_line</code> 函数,让其将用户输入储存到这个字符串中。<code>read_line</code> 的工作是,无论用户在标准输入中键入什么内容,都将其追加(不会覆盖其原有内容)到一个字符串中,因此它需要字符串作为参数。这个字符串参数应该是可变的,以便 <code>read_line</code> 将用户输入附加上去。</p>
<p><code>&amp;</code> 表示这个参数是一个 <strong>引用</strong><em>reference</em>它允许多处代码访问同一处数据而无需在内存中多次拷贝。引用是一个复杂的特性Rust 的一个主要优势就是安全而简单的操纵引用。完成当前程序并不需要了解如此多细节。现在,我们只需知道它像变量一样,默认是不可变的。因此,需要写成 <code>&amp;mut guess</code> 来使其可变,而不是 <code>&amp;guess</code>。(第四章会更全面的解释引用。)</p>
<h3 id="使用-result-类型来处理潜在的错误"><a class="header" href="#使用-result-类型来处理潜在的错误">使用 <code>Result</code> 类型来处理潜在的错误</a></h3>
<p>我们还没有完全分析完这行代码。虽然我们已经讲到了第三行代码但要注意它仍是逻辑行虽然换行了但仍是语句的一部分。后一部分是这个方法method</p>
<pre><code class="language-rust ignore"><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span> .expect("Failed to read line");
<span class="boring">
</span><span class="boring"> println!("You guessed: {}", guess);
</span><span class="boring">}</span></code></pre>
<p>我们也可以将代码这样写:</p>
<pre><code class="language-rust ignore">io::stdin().read_line(&amp;mut guess).expect("Failed to read line");</code></pre>
<p>不过,过长的代码行难以阅读,所以最好拆开来写。通常来说,当使用 <code>.method_name()</code> 语法调用方法时引入换行符和空格将长的代码行拆开是明智的。现在来看看这行代码干了什么。</p>
<p>之前提到了 <code>read_line</code> 会将用户输入附加到传递给它的字符串中,不过它也会返回一个类型为 <code>Result</code> 的值。
<a href="https://doc.rust-lang.org/std/result/enum.Result.html"><code>Result</code></a><!-- ignore --> 是一种<a href="ch06-00-enums.html"><em>枚举类型</em></a><!-- ignore -->,通常也写作 <em>enum</em>。枚举类型变量的值可以是多种可能状态中的一个。我们把每种可能的状态称为一种 <em>枚举成员variant</em></p>
<p><a href="ch06-00-enums.html">第六章</a>将介绍枚举的更多细节。这里的 <code>Result</code> 类型将用来编码错误处理的信息。</p>
<p><code>Result</code> 的成员是 <code>Ok</code><code>Err</code><code>Ok</code> 成员表示操作成功,内部包含成功时产生的值。<code>Err</code> 成员则意味着操作失败,并且 <code>Err</code> 中包含有关操作失败的原因或方式的信息。</p>
<p>这些 <code>Result</code> 类型的作用是编码错误处理信息。<code>Result</code> 类型的值,像其他类型一样,拥有定义于其上的方法。<code>Result</code> 的实例拥有 <a href="https://doc.rust-lang.org/std/result/enum.Result.html#method.expect"><code>expect</code> 方法</a><!-- ignore -->。如果 <code>io::Result</code> 实例的值是 <code>Err</code><code>expect</code> 会导致程序崩溃,并显示当做参数传递给 <code>expect</code> 的信息。如果 <code>read_line</code> 方法返回 <code>Err</code>,则可能是来源于底层操作系统错误的结果。如果 <code>Result</code> 实例的值是 <code>Ok</code><code>expect</code> 会获取 <code>Ok</code> 中的值并原样返回。在本例中,这个值是用户输入到标准输入中的字节数。</p>
<p>如果不调用 <code>expect</code>,程序也能编译,不过会出现一个警告:</p>
<pre><code class="language-console">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
warning: unused `Result` that must be used
--&gt; src/main.rs:10:5
|
10 | io::stdin().read_line(&amp;mut guess);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
|
10 | let _ = io::stdin().read_line(&amp;mut guess);
| +++++++
warning: `guessing_game` (bin "guessing_game") generated 1 warning
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.59s
</code></pre>
<p>Rust 警告我们没有使用 <code>read_line</code> 的返回值 <code>Result</code>,说明有一个可能的错误没有处理。</p>
<p>消除警告的正确做法是实际去编写错误处理代码,不过由于我们就是希望程序在出现问题时立即崩溃,所以直接使用 <code>expect</code><a href="ch09-02-recoverable-errors-with-result.html">第九章</a> 会学习如何从错误中恢复。</p>
<h3 id="使用-println-占位符打印值"><a class="header" href="#使用-println-占位符打印值">使用 <code>println!</code> 占位符打印值</a></h3>
<p>除了位于结尾的右花括号,目前为止就只有这一行代码值得讨论一下了,就是这一行:</p>
<pre><code class="language-rust ignore"><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span> println!("You guessed: {}", guess);
<span class="boring">}</span></code></pre>
<p>这行代码现在打印了存储用户输入的字符串。<code>{}</code> 这对大括号是一个占位符:把 <code>{}</code> 想象成小蟹钳可以夹住合适的值。当打印变量的值时变量名可以写进大括号中。当打印表达式的执行结果时格式化字符串format string中大括号中留空格式化字符串后跟逗号分隔的需要打印的表达式列表其顺序与每一个空大括号占位符的顺序一致。在一个 <code>println!</code> 调用中打印变量和表达式的值看起来像这样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let x = 5;
let y = 10;
println!("x = {x} and y + 2 = {}", y + 2);
<span class="boring">}</span></code></pre></pre>
<p>这行代码会打印出 <code>x = 5 and y + 2 = 12</code></p>
<h3 id="测试第一部分代码"><a class="header" href="#测试第一部分代码">测试第一部分代码</a></h3>
<p>让我们来测试下猜数字游戏的第一部分。使用 <code>cargo run</code> 运行:</p>
<pre><code class="language-console">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 6.44s
Running `target/debug/guessing_game`
Guess the number!
Please input your guess.
6
You guessed: 6
</code></pre>
<p>至此为止,游戏的第一部分已经完成:我们从键盘获取输入并打印了出来。</p>
<h2 id="生成一个秘密数字"><a class="header" href="#生成一个秘密数字">生成一个秘密数字</a></h2>
<p>接下来,需要生成一个秘密数字,好让用户来猜。秘密数字应该每次都不同,这样重复玩才不会乏味;范围应该在 1 到 100 之间这样才不会太困难。Rust 标准库中尚未包含随机数功能。然而Rust 团队还是提供了一个包含上述功能的 <a href="https://crates.io/crates/rand"><code>rand</code> crate</a></p>
<h3 id="使用-crate-来增加更多功能"><a class="header" href="#使用-crate-来增加更多功能">使用 crate 来增加更多功能</a></h3>
<p>记住crate 是一组 Rust 源代码文件。我们正在构建的项目是一个 <em>二进制 crate</em>,它生成一个可执行文件。 <code>rand</code> crate 是一个 <em>库 crate</em>,库 crate 可以包含任意能被其他程序使用的代码,但是无法独立执行。</p>
<p>Cargo 对外部 crate 的运用是其真正的亮点所在。在我们使用 <code>rand</code> 编写代码之前,需要修改 <em>Cargo.toml</em> 文件,引入一个 <code>rand</code> 依赖。现在打开这个文件并将下面这一行添加到 <code>[dependencies]</code> 片段标题之下。在当前版本下,请确保按照我们这里的方式指定 <code>rand</code>,否则本教程中的示例代码可能无法工作。</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[dependencies]
rand = "0.8.5"
</code></pre>
<p><em>Cargo.toml</em> 文件中,标题以及之后的内容属同一个片段,直到遇到下一个标题才开始新的片段。<code>[dependencies]</code> 片段告诉 Cargo 本项目依赖了哪些外部 crate 及其版本。本例中,我们使用语义化版本 <code>0.8.5</code> 来指定 <code>rand</code> crate。Cargo 理解 <a href="http://semver.org">语义化版本Semantic Versioning</a><!-- ignore -->(有时也称为 <em>SemVer</em>),这是一种定义版本号的标准。<code>0.8.5</code> 事实上是 <code>^0.8.5</code> 的简写,它表示任何至少是 <code>0.8.5</code> 但小于 <code>0.9.0</code> 的版本。</p>
<p>Cargo 认为这些版本与 <code>0.8.5</code> 版本的公有 API 相兼容这样的版本指定确保了我们可以获取能使本章代码编译的最新的补丁patch版本。任何大于等于 <code>0.9.0</code> 的版本不能保证和接下来的示例采用了相同的 API。</p>
<p>现在,不修改任何代码,构建项目,如示例 2-2 所示。</p>
<figure class="listing">
<pre><code class="language-console">$ cargo build
Updating crates.io index
Downloaded rand v0.8.5
Downloaded libc v0.2.127
Downloaded getrandom v0.2.7
Downloaded cfg-if v1.0.0
Downloaded ppv-lite86 v0.2.16
Downloaded rand_chacha v0.3.1
Downloaded rand_core v0.6.3
Compiling libc v0.2.127
Compiling getrandom v0.2.7
Compiling cfg-if v1.0.0
Compiling ppv-lite86 v0.2.16
Compiling rand_core v0.6.3
Compiling rand_chacha v0.3.1
Compiling rand v0.8.5
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53s
</code></pre>
<figcaption>示例 2-2将 rand crate 添加为依赖之后运行 `cargo build` 的输出</figcaption>
</figure>
<p>可能会出现不同的版本号(多亏了语义化版本,它们与代码是兼容的!),并且显示的行数可能会有所不同(取决于操作系统),行的顺序也可能会不同。</p>
<p>现在我们有了一个外部依赖Cargo 从 <em>registry</em> 上获取所有包的最新版本信息,这是一份来自 <a href="https://crates.io/">Crates.io</a> 的数据副本。Crates.io 是 Rust 生态系统中,人们发布其开源 Rust 项目的平台,供他人使用。</p>
<p>在更新完 <em>registry</em>Cargo 检查 <code>[dependencies]</code> 片段并下载列表中包含但还未下载的 crates。本例中虽然只声明了 <code>rand</code> 一个依赖,然而 Cargo 还是额外获取了 <code>rand</code> 所需要的其他 crates因为 <code>rand</code> 依赖它们来正常工作。下载完成后Rust 编译依赖,然后使用这些依赖编译项目。</p>
<p>如果不做任何修改,立刻再次运行 <code>cargo build</code>,则不会看到任何除了 <code>Finished</code> 行之外的输出。Cargo 知道它已经下载并编译了依赖,同时 <em>Cargo.toml</em> 文件也没有变动。Cargo 还知道代码也没有任何修改,所以它不会重新编译代码。因为无事可做,它会简单地退出。</p>
<p>如果打开 <em>src/main.rs</em> 文件,做一些无关紧要的修改,保存并再次构建,则会出现两行输出:</p>
<pre><code class="language-console">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
</code></pre>
<p>这一行表示 Cargo 只针对 <em>src/main.rs</em> 文件的微小修改而更新构建。依赖没有变化,所以 Cargo 知道它可以复用已经为此下载并编译的代码。它只是重新构建了部分(项目)代码。</p>
<h4 id="cargolock-文件确保构建是可重现的"><a class="header" href="#cargolock-文件确保构建是可重现的"><em>Cargo.lock</em> 文件确保构建是可重现的</a></h4>
<p>Cargo 有一个机制确保无论是你还是其他人在任何时候重新构建代码都会生成相同的构建产物Cargo 只会使用你指定的依赖版本,除非你明确指定其他版本。例如,如果下周 <code>rand</code> crate 的 <code>0.8.6</code> 版本出来了,该版本包含了一个重要的 bug 修复但同时也引入了一个会破坏你代码的回归问题。为了解决这个问题Rust 在你第一次运行 <code>cargo build</code> 时创建了 <em>Cargo.lock</em> 文件,我们现在可以在 <em>guessing_game</em> 目录找到它。</p>
<p>当第一次构建项目时Cargo 计算出所有符合要求的依赖版本并写入 <em>Cargo.lock</em> 文件。当将来构建项目时Cargo 会发现 <em>Cargo.lock</em> 已存在并使用其中指定的版本,而不是再次计算所有的版本。这使得你拥有了一个自动化的可重现的构建。换句话说,项目会持续使用 <code>0.8.5</code> 直到你显式升级,多亏有了 <em>Cargo.lock</em> 文件。由于 <em>Cargo.lock</em> 文件对于“可重复构建”非常重要,因此它通常会和项目中的其余代码一样纳入到版本控制系统中。</p>
<h4 id="更新-crate-到一个新版本"><a class="header" href="#更新-crate-到一个新版本">更新 crate 到一个新版本</a></h4>
<p>当你 <strong>确实</strong> 需要升级 crate 时Cargo 提供了这样一个命令,<code>update</code>,它会忽略 <em>Cargo.lock</em> 文件,并计算出所有符合 <em>Cargo.toml</em> 声明的最新版本。Cargo 接下来会把这些版本写入 <em>Cargo.lock</em> 文件。不过Cargo 默认只会寻找大于 <code>0.8.5</code> 而小于 <code>0.9.0</code> 的版本。如果 <code>rand</code> crate 发布了两个新版本,<code>0.8.6</code><code>0.9.0</code>,在运行 <code>cargo update</code> 时会出现如下内容:</p>
<pre><code class="language-console">$ cargo update
Updating crates.io index
Updating rand v0.8.5 -&gt; v0.8.6
</code></pre>
<p>Cargo 忽略了 <code>0.9.0</code> 版本。这时,你也会注意到的 <em>Cargo.lock</em> 文件中的变化无外乎现在使用的 <code>rand</code> crate 版本是<code>0.8.6</code> 。如果想要使用 <code>0.9.0</code> 版本的 <code>rand</code> 或是任何 <code>0.9.x</code> 系列的版本,必须像这样更新 <em>Cargo.toml</em> 文件:</p>
<pre><code class="language-toml">[dependencies]
rand = "0.9.0"
</code></pre>
<p>下一次运行 <code>cargo build</code>Cargo 会更新可用 crate 的 registry并根据你指定的新版本重新评估 <code>rand</code> 的要求。</p>
<p>第十四章会讲到 <a href="http://doc.crates.io">Cargo</a><!-- ignore --> 及其<a href="http://doc.crates.io/crates-io.html">生态系统</a><!-- ignore --> 的更多内容,不过目前你只需要了解这么多。通过 Cargo 复用库文件非常容易,因此 Rustacean 能够编写出由很多包组装而成的更轻巧的项目。</p>
<h3 id="生成一个随机数"><a class="header" href="#生成一个随机数">生成一个随机数</a></h3>
<p>让我们开始使用 <code>rand</code> 来生成一个猜数字随机数。下一步是更新 <em>src/main.rs</em>,如示例 2-3 所示。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&amp;mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}</code></pre>
<figcaption>示例 2-3添加生成随机数的代码</figcaption>
</figure>
<p>首先,我们新增了一行 <code>use rand::Rng;</code><code>Rng</code> 是一个 trait它定义了随机数生成器应实现的方法想使用这些方法的话此 trait 必须在作用域中。第十章会详细介绍 trait。</p>
<p>接下来,我们在中间还新增加了两行。第一行调用了 <code>rand::thread_rng</code> 函数提供实际使用的随机数生成器:它位于当前执行线程的本地环境中,并从操作系统获取 seed。接着调用随机数生成器的 <code>gen_range</code> 方法。这个方法由 <code>use rand::Rng</code> 语句引入到作用域的 <code>Rng</code> trait 定义。<code>gen_range</code> 方法获取一个范围表达式range expression作为参数并生成一个在此范围之间的随机数。这里使用的这类范围表达式使用了 <code>start..=end</code> 这样的形式,也就是说包含了上下端点,所以需要指定 <code>1..=100</code> 来请求一个 1 和 100 之间的数。</p>
<blockquote>
<p>注意:你不可能凭空就知道应该 use 哪个 trait 以及该从 crate 中调用哪个方法,因此每个 crate 有使用说明文档。Cargo 有一个很棒的功能是:运行 <code>cargo doc --open</code> 命令来构建所有本地依赖提供的文档,并在浏览器中打开。例如,假设你对 <code>rand</code> crate 中的其他功能感兴趣,你可以运行 <code>cargo doc --open</code> 并点击左侧导航栏中的 <code>rand</code></p>
</blockquote>
<p>新增加的第二行代码打印出了秘密数字。这在开发程序时很有用,因为可以测试它,不过在最终版本中会删掉它。如果游戏一开始就打印出结果就没什么可玩的了!</p>
<p>尝试运行程序几次:</p>
<pre><code class="language-console">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 7
Please input your guess.
4
You guessed: 4
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 83
Please input your guess.
5
You guessed: 5
</code></pre>
<p>你应该能得到不同的随机数,同时它们应该都是在 1 和 100 之间的。干得漂亮!</p>
<h2 id="比较猜测的数字和秘密数字"><a class="header" href="#比较猜测的数字和秘密数字">比较猜测的数字和秘密数字</a></h2>
<p>现在有了用户输入和一个随机数,我们可以比较它们。这个步骤如示例 2-4 所示。注意这段代码还不能通过编译,我们稍后会解释。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
// --snip--
<span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span><span class="boring"> println!("The secret number is: {secret_number}");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span>
println!("You guessed: {guess}");
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!("Too small!"),
Ordering::Greater =&gt; println!("Too big!"),
Ordering::Equal =&gt; println!("You win!"),
}
}</code></pre>
<figcaption>示例 2-4处理比较两个数字可能的返回值</figcaption>
</figure>
<p>首先我们增加了另一个 <code>use</code> 声明,从标准库引入了一个叫做 <code>std::cmp::Ordering</code> 的类型到作用域中。 <code>Ordering</code> 也是一个枚举,不过它的成员是 <code>Less</code><code>Greater</code><code>Equal</code>。这是比较两个值时可能出现的三种结果。</p>
<p>接着,底部的五行新代码使用了 <code>Ordering</code> 类型,<code>cmp</code> 方法用来比较两个值并可以在任何可比较的值上调用。它获取一个被比较值的引用:这里是把 <code>guess</code><code>secret_number</code> 做比较。然后它会返回一个刚才通过 <code>use</code> 引入作用域的 <code>Ordering</code> 枚举的成员。使用一个 <a href="ch06-02-match.html"><code>match</code></a><!-- ignore --> 表达式,根据对 <code>guess</code><code>secret_number</code> 调用 <code>cmp</code> 返回的 <code>Ordering</code> 成员来决定接下来做什么。</p>
<p>一个 <code>match</code> 表达式由 <strong>分支arms</strong> 构成。一个分支包含一个 <strong>模式</strong><em>pattern</em>和表达式开头的值与分支模式相匹配时应该执行的代码。Rust 获取提供给 <code>match</code> 的值并挨个检查每个分支的模式。<code>match</code> 结构和模式是 Rust 中强大的功能,它体现了代码可能遇到的多种情形,并帮助你确保没有遗漏处理。这些功能将分别在第六章和第十九章详细介绍。</p>
<p>让我们看看使用 <code>match</code> 表达式的例子。假设用户猜了 50这时随机生成的秘密数字是 38。</p>
<p>比较 50 与 38 时,因为 50 比 38 要大,<code>cmp</code> 方法会返回 <code>Ordering::Greater</code><code>Ordering::Greater</code><code>match</code> 表达式得到的值。它检查第一个分支的模式,<code>Ordering::Less</code><code>Ordering::Greater</code>并不匹配,所以它忽略了这个分支的代码并来到下一个分支。下一个分支的模式是 <code>Ordering::Greater</code><strong>正确</strong> 匹配!这个分支关联的代码被执行,在屏幕打印出 <code>Too big!</code><code>match</code> 表达式会在第一次成功匹配后终止,因为该场景下没有检查最后一个分支的必要。</p>
<p>然而,示例 2-4 的代码目前并不能编译,可以尝试一下:</p>
<pre><code class="language-console">$ cargo build
Downloading crates ...
Downloaded rand_core v0.6.2
Downloaded getrandom v0.2.2
Downloaded rand_chacha v0.3.0
Downloaded ppv-lite86 v0.2.10
Downloaded libc v0.2.86
Compiling libc v0.2.86
Compiling getrandom v0.2.2
Compiling cfg-if v1.0.0
Compiling ppv-lite86 v0.2.10
Compiling rand_core v0.6.2
Compiling rand_chacha v0.3.0
Compiling rand v0.8.5
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
error[E0308]: mismatched types
--&gt; src/main.rs:22:21
|
22 | match guess.cmp(&amp;secret_number) {
| --- ^^^^^^^^^^^^^^ expected `&amp;String`, found `&amp;{integer}`
| |
| arguments to this method are incorrect
|
= note: expected reference `&amp;String`
found reference `&amp;{integer}`
note: method defined here
--&gt; /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/core/src/cmp.rs:839:8
For more information about this error, try `rustc --explain E0308`.
error: could not compile `guessing_game` (bin "guessing_game") due to 1 previous error
</code></pre>
<p>错误的核心表明这里有 <strong>不匹配的类型</strong><em>mismatched types</em>。Rust 有一个静态强类型系统,同时也有类型推断。当我们写出 <code>let guess = String::new()</code>Rust 推断出 <code>guess</code> 应该是 <code>String</code> 类型,并不需要我们写出类型。另一方面,<code>secret_number</code>,是数字类型。几个数字类型拥有 1 到 100 之间的值32 位数字 <code>i32</code>32 位无符号数字 <code>u32</code>64 位数字 <code>i64</code> 等等。Rust 默认使用 <code>i32</code>,所以它是 <code>secret_number</code> 的类型,除非增加类型信息,或任何能让 Rust 推断出不同数值类型的信息。这里错误的原因在于 Rust 不会比较字符串类型和数字类型。</p>
<p>所以我们必须把从输入中读取到的 <code>String</code> 转换为一个真正的数字类型,才好与秘密数字进行比较。这可以通过在 <code>main</code> 函数体中增加如下代码来实现:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use rand::Rng;
</span><span class="boring">use std::cmp::Ordering;
</span><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span><span class="boring"> println!("The secret number is: {secret_number}");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span> // --snip--
let mut guess = String::new();
io::stdin()
.read_line(&amp;mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("You guessed: {guess}");
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!("Too small!"),
Ordering::Greater =&gt; println!("Too big!"),
Ordering::Equal =&gt; println!("You win!"),
}
<span class="boring">}</span></code></pre>
<p>这行新代码是:</p>
<pre><code class="language-rust ignore">let guess: u32 = guess.trim().parse().expect("Please type a number!");</code></pre>
<p>这里创建了一个叫做 <code>guess</code> 的变量。不过等等,不是已经有了一个叫做 <code>guess</code> 的变量了吗?确实如此,不过 Rust 允许用一个新值来 <strong>隐藏</strong> <em>Shadowing</em> <code>guess</code> 之前的值。这个功能常用在需要转换值类型之类的场景。它允许我们复用 <code>guess</code> 变量的名字,而不是被迫创建两个不同变量,诸如 <code>guess_str</code><code>guess</code> 之类。<a href="ch03-01-variables-and-mutability.html#%E9%9A%90%E8%97%8F">第三章</a>会介绍 shadowing 的更多细节,现在只需知道这个功能经常用于将一个类型的值转换为另一个类型的值。</p>
<p>我们将这个新变量绑定到 <code>guess.trim().parse()</code> 表达式上。表达式中的 <code>guess</code> 指的是包含输入的字符串类型 <code>guess</code> 变量。<code>String</code> 实例的 <code>trim</code> 方法会去除字符串开头和结尾的空白字符,我们必须执行此方法才能将字符串与 <code>u32</code> 比较,因为 <code>u32</code> 只能包含数值型数据。用户必须输入 <span class="keystroke">enter</span> 键才能让 <code>read_line</code> 返回并输入他们的猜想这将会在字符串中增加一个换行newline符。例如用户输入 <span class="keystroke">5</span> 并按下 <span class="keystroke">enter</span>(在 Windows 上,按下 <span class="keystroke">enter</span> 键会得到一个回车符和一个换行符,<code>\r\n</code><code>guess</code> 看起来像这样:<code>5\n</code> 或者 <code>5\r\n</code><code>\n</code> 代表 “换行”,回车键;<code>\r</code> 代表 “回车”,回车键。<code>trim</code> 方法会消除 <code>\n</code> 或者 <code>\r\n</code>,只留下 <code>5</code></p>
<p><a href="https://doc.rust-lang.org/std/primitive.str.html#method.parse">字符串的 <code>parse</code> 方法</a><!-- ignore --> 将字符串转换成其他类型。这里用它来把字符串转换为数值。我们需要告诉 Rust 具体的数字类型,这里通过 <code>let guess: u32</code> 指定。<code>guess</code> 后面的冒号(<code>:</code>)告诉 Rust 我们指定了变量的类型。Rust 有一些内建的数字类型;<code>u32</code> 是一个无符号的 32 位整型。对于不大的正整数来说,它是不错的默认类型,<a href="ch03-02-data-types.html#%E6%95%B4%E5%9E%8B">第三章</a>还会讲到其他数字类型。</p>
<p>另外,程序中的 <code>u32</code> 注解以及与 <code>secret_number</code> 的比较,意味着 Rust 会推断出 <code>secret_number</code> 也是 <code>u32</code> 类型。现在可以使用相同类型比较两个值了!</p>
<p><code>parse</code> 方法只有在字符逻辑上可以转换为数字的时候才能工作所以非常容易出错。例如,字符串中包含 <code>A👍%</code>,就无法将其转换为一个数字。因此,<code>parse</code> 方法返回一个 <code>Result</code> 类型。像之前 <a href="ch02-00-guessing-game-tutorial.html#%E4%BD%BF%E7%94%A8-result-%E7%B1%BB%E5%9E%8B%E6%9D%A5%E5%A4%84%E7%90%86%E6%BD%9C%E5%9C%A8%E7%9A%84%E9%94%99%E8%AF%AF">“使用 <code>Result</code> 类型来处理潜在的错误”</a> 讨论的 <code>read_line</code> 方法那样,再次按部就班的用 <code>expect</code> 方法处理即可。如果 <code>parse</code> 不能从字符串生成一个数字,返回一个 <code>Result</code><code>Err</code> 成员时,<code>expect</code> 会使游戏崩溃并打印附带的信息。如果 <code>parse</code> 成功地将字符串转换为一个数字,它会返回 <code>Result</code><code>Ok</code> 成员,然后 <code>expect</code> 会返回 <code>Ok</code> 值中的数字。</p>
<p>现在让我们运行程序!</p>
<pre><code class="language-console">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 58
Please input your guess.
76
You guessed: 76
Too big!
</code></pre>
<p>漂亮!即便是在猜测之前添加了空格,程序依然能判断出用户猜测了 76。多运行程序几次输入不同的数字来检验不同的行为猜一个正确的数字猜一个过大的数字和猜一个过小的数字。</p>
<p>现在游戏已经大体上能玩了,不过用户只能猜一次。增加一个循环来改变它吧!</p>
<h2 id="使用循环来允许多次猜测"><a class="header" href="#使用循环来允许多次猜测">使用循环来允许多次猜测</a></h2>
<p><code>loop</code> 关键字创建了一个无限循环。我们会增加循环来给用户更多机会猜数字:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use rand::Rng;
</span><span class="boring">use std::cmp::Ordering;
</span><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span> // --snip--
println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
// --snip--
<span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> let guess: u32 = guess.trim().parse().expect("Please type a number!");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {guess}");
</span><span class="boring">
</span> match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!("Too small!"),
Ordering::Greater =&gt; println!("Too big!"),
Ordering::Equal =&gt; println!("You win!"),
}
}
}</code></pre>
<p>如上所示,我们将提示用户猜测之后的所有内容移动到了循环中。确保 loop 循环中的代码多缩进四个空格,再次运行程序。注意这里有一个新问题,因为程序忠实地执行了我们的要求:永远地请求另一个猜测,用户好像无法退出啊!</p>
<p>用户总能使用 <span class="keystroke">ctrl-c</span> 终止程序。不过还有另一个方法跳出无限循环,就是 <a href="ch02-00-guessing-game-tutorial.html#%E6%AF%94%E8%BE%83%E7%8C%9C%E6%B5%8B%E7%9A%84%E6%95%B0%E5%AD%97%E5%92%8C%E7%A7%98%E5%AF%86%E6%95%B0%E5%AD%97">“比较猜测与秘密数字”</a> 部分提到的 <code>parse</code>:如果用户输入的答案不是一个数字,程序会崩溃。我们可以利用这一点来退出,如下所示:</p>
<pre><code class="language-console">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 1.50s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 59
Please input your guess.
45
You guessed: 45
Too small!
Please input your guess.
60
You guessed: 60
Too big!
Please input your guess.
59
You guessed: 59
You win!
Please input your guess.
quit
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/main.rs:28:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>输入 <code>quit</code> 将会退出程序,同时你会注意到其他任何非数字输入也一样。然而,这并不理想,我们想要当猜测正确的数字时游戏停止。</p>
<h3 id="猜测正确后退出"><a class="header" href="#猜测正确后退出">猜测正确后退出</a></h3>
<p>让我们增加一个 <code>break</code> 语句,在用户猜对时退出游戏:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use rand::Rng;
</span><span class="boring">use std::cmp::Ordering;
</span><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span><span class="boring"> println!("The secret number is: {secret_number}");
</span><span class="boring">
</span><span class="boring"> loop {
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> let guess: u32 = guess.trim().parse().expect("Please type a number!");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {guess}");
</span><span class="boring">
</span> // --snip--
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!("Too small!"),
Ordering::Greater =&gt; println!("Too big!"),
Ordering::Equal =&gt; {
println!("You win!");
break;
}
}
}
}</code></pre>
<p>通过在 <code>You win!</code> 之后增加一行 <code>break</code>,用户猜对了神秘数字后会退出循环。退出循环也意味着退出程序,因为循环是 <code>main</code> 的最后一部分。</p>
<h3 id="处理无效输入"><a class="header" href="#处理无效输入">处理无效输入</a></h3>
<p>为了进一步改善游戏性,不要在用户输入非数字时崩溃,需要忽略非数字,让用户可以继续猜测。可以通过修改 <code>guess</code><code>String</code> 转化为 <code>u32</code> 那部分代码来实现,如示例 2-5 所示:</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use rand::Rng;
</span><span class="boring">use std::cmp::Ordering;
</span><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span><span class="boring"> println!("The secret number is: {secret_number}");
</span><span class="boring">
</span><span class="boring"> loop {
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span> // --snip--
io::stdin()
.read_line(&amp;mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
println!("You guessed: {guess}");
// --snip--
<span class="boring">
</span><span class="boring"> match guess.cmp(&amp;secret_number) {
</span><span class="boring"> Ordering::Less =&gt; println!("Too small!"),
</span><span class="boring"> Ordering::Greater =&gt; println!("Too big!"),
</span><span class="boring"> Ordering::Equal =&gt; {
</span><span class="boring"> println!("You win!");
</span><span class="boring"> break;
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<figcaption>示例 2-5忽略非数字的猜测并重新请求数字而不是让程序崩溃</figcaption>
</figure>
<p>我们将 <code>expect</code> 调用换成 <code>match</code> 语句,以从遇到错误就崩溃转换为处理错误。须知 <code>parse</code> 返回一个 <code>Result</code> 类型,而 <code>Result</code> 是一个拥有 <code>Ok</code><code>Err</code> 成员的枚举。这里使用的 <code>match</code> 表达式,和之前处理 <code>cmp</code> 方法返回 <code>Ordering</code> 时用的一样。</p>
<p>如果 <code>parse</code> 能够成功的将字符串转换为一个数字,它会返回一个包含结果数字的 <code>Ok</code>。这个 <code>Ok</code> 值与 <code>match</code> 第一个分支的模式相匹配,该分支对应的动作返回 <code>Ok</code> 值中的数字 <code>num</code>,最后如愿变成新创建的 <code>guess</code> 变量。</p>
<p>如果 <code>parse</code> <strong></strong>能将字符串转换为一个数字,它会返回一个包含更多错误信息的 <code>Err</code><code>Err</code> 值不能匹配第一个 <code>match</code> 分支的 <code>Ok(num)</code> 模式,但是会匹配第二个分支的 <code>Err(_)</code> 模式:<code>_</code> 是一个通配符值,本例中用来匹配所有 <code>Err</code> 值,不管其中有何种信息。所以程序会执行第二个分支的动作,<code>continue</code> 意味着进入 <code>loop</code> 的下一次循环,请求另一个猜测。这样程序就有效的忽略了 <code>parse</code> 可能遇到的所有错误!</p>
<p>现在程序中的一切都应该如预期般工作了。让我们试试吧:</p>
<pre><code class="language-console">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 4.45s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 61
Please input your guess.
10
You guessed: 10
Too small!
Please input your guess.
99
You guessed: 99
Too big!
Please input your guess.
foo
Please input your guess.
61
You guessed: 61
You win!
</code></pre>
<p>太棒了!再有最后一个小的修改,就能完成猜数字游戏了:还记得程序依然会打印出秘密数字。在测试时还好,但正式发布时会毁了游戏。删掉打印秘密数字的 <code>println!</code>。示例 2-6 为最终代码:</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&amp;mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
println!("You guessed: {guess}");
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!("Too small!"),
Ordering::Greater =&gt; println!("Too big!"),
Ordering::Equal =&gt; {
println!("You win!");
break;
}
}
}
}</code></pre>
<figcaption>示例 2-6猜数字游戏的完整代码</figcaption>
</figure>
<p>此时此刻,你顺利完成了猜数字游戏。恭喜!</p>
<h2 id="总结-1"><a class="header" href="#总结-1">总结</a></h2>
<p>本项目通过动手实践,向你介绍了 Rust 新概念:<code>let</code><code>match</code>、函数、使用外部 crate 等等,接下来的几章,你会继续深入学习这些概念。第三章介绍大部分编程语言都有的概念,比如变量、数据类型和函数,以及如何在 Rust 中使用它们。第四章探索所有权ownership这是一个 Rust 同其他语言大不相同的功能。第五章讨论结构体和方法的语法,而第六章侧重解释枚举。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="常见编程概念"><a class="header" href="#常见编程概念">常见编程概念</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch03-00-common-programming-concepts.md">ch03-00-common-programming-concepts.md</a>
<br>
commit d0acb2595c891de97a133d06635c50ab449dd65c</p>
</blockquote>
<p>本章介绍一些几乎所有编程语言都有的概念,以及它们在 Rust 中是如何工作的。很多编程语言的核心概念都是共通的,本章中展示的概念都不是 Rust 所特有的,不过我们会在 Rust 上下文中讨论它们,并解释使用这些概念的惯例。</p>
<p>具体来说,我们将会学习变量、基本类型、函数、注释和控制流。每一个 Rust 程序中都会用到这些基础知识,提早学习这些概念会让你在起步时就打下坚实的基础。</p>
<blockquote>
<h2 id="关键字"><a class="header" href="#关键字">关键字</a></h2>
<p>Rust 语言有一组保留的 <strong>关键字</strong><em>keywords</em>),就像大部分语言一样,它们只能由语言本身使用。记住,你不能使用这些关键字作为变量或函数的名称。大部分关键字有特殊的意义,你将在 Rust 程序中使用它们完成各种任务;一些关键字目前没有相应的功能,是为将来可能添加的功能保留的。可以在<a href="appendix-01-keywords.html">附录 A</a><!-- ignore --> 中找到关键字的列表。</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h2 id="变量和可变性"><a class="header" href="#变量和可变性">变量和可变性</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch03-01-variables-and-mutability.md">ch03-01-variables-and-mutability.md</a></p>
<p>commit 21a2ed14f4480dab62438dcc1130291bebc65379</p>
</blockquote>
<p>正如第二章中<a href="ch02-00-guessing-game-tutorial.html#%E4%BD%BF%E7%94%A8%E5%8F%98%E9%87%8F%E5%82%A8%E5%AD%98%E5%80%BC">“使用变量储存值”</a><!-- ignore --> 部分提到的那样变量默认是不可改变的immutable。这是 Rust 提供给你的众多优势之一,让你得以充分利用 Rust 提供的安全性和简单并发性来编写代码。不过,你仍然可以使用可变变量。让我们探讨一下 Rust 为何及如何鼓励你利用不可变性,以及何时你会选择不使用不可变性。</p>
<p>当变量不可变时,一旦值被绑定一个名称上,你就不能改变这个值。为了对此进行说明,使用 <code>cargo new variables</code> 命令在 <em>projects</em> 目录生成一个叫做 <em>variables</em> 的新项目。</p>
<p>接着,在新建的 <em>variables</em> 目录,打开 <em>src/main.rs</em> 并将代码替换为如下代码这些代码还不能编译我们会首次检查到不可变错误immutability error</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}</code></pre>
<p>保存并使用 <code>cargo run</code> 运行程序。应该会看到一条与不可变性有关的错误信息,如下输出所示:</p>
<pre><code class="language-console">$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
--&gt; src/main.rs:4:5
|
2 | let x = 5;
| - first assignment to `x`
3 | println!("The value of x is: {x}");
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut x = 5;
| +++
For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` (bin "variables") due to 1 previous error
</code></pre>
<p>这个例子展示了编译器如何帮助你找出程序中的错误。虽然编译错误令人沮丧,但那只是表示程序不能安全的完成你想让它完成的工作;并 <strong>不能</strong> 说明你不是一个好程序员!经验丰富的 Rustacean 们一样会遇到编译错误。</p>
<p>错误信息指出错误的原因是 <code>不能对不可变变量 x 二次赋值</code><code>cannot assign twice to immutable variable `x` </code>),因为你尝试对不可变变量 <code>x</code> 赋第二个值。</p>
<p>在尝试改变预设为不可变的值时,产生编译时错误是很重要的,因为这种情况可能导致 bug。如果一部分代码假设一个值永远也不会改变而另一部分代码改变了这个值第一部分代码就有可能以不可预料的方式运行。不得不承认这种 bug 的起因难以跟踪,尤其是第二部分代码只是 <strong>有时</strong> 会改变值。</p>
<p>Rust 编译器保证,如果声明一个值不会变,它就真的不会变,所以你不必自己跟踪它。这意味着你的代码更易于推导。</p>
<p>不过可变性也是非常有用的,可以用来更方便地编写代码。尽管变量默认是不可变的,你仍然可以在变量名前添加 <code>mut</code> 来使其可变,正如在<a href="ch02-00-guessing-game-tutorial.html#%E4%BD%BF%E7%94%A8%E5%8F%98%E9%87%8F%E5%82%A8%E5%AD%98%E5%80%BC">第二章</a>所做的那样。<code>mut</code> 也向读者表明了其他代码将会改变这个变量值的意图。</p>
<p>例如,让我们将 <em>src/main.rs</em> 修改为如下代码:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}</code></pre></pre>
<p>现在运行这个程序,出现如下内容:</p>
<pre><code class="language-console">$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/variables`
The value of x is: 5
The value of x is: 6
</code></pre>
<p>通过 <code>mut</code>,允许把绑定到 <code>x</code> 的值从 <code>5</code> 改成 <code>6</code>。是否让变量可变的最终决定权仍然在你,取决于在某个特定情况下,你是否认为变量可变会让代码更加清晰明了。</p>
<h3 id="常量"><a class="header" href="#常量">常量</a></h3>
<p>类似于不可变变量,<em>常量 (constants)</em> 是绑定到一个名称的不允许改变的值,不过常量与变量还是有一些区别。</p>
<p>首先,不允许对常量使用 <code>mut</code>。常量不光默认不可变,它总是不可变。声明常量使用 <code>const</code> 关键字而不是 <code>let</code>,并且 <em>必须</em> 注明值的类型。在下一部分,<a href="ch03-02-data-types.html#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">“数据类型”</a> 中会介绍类型和类型注解,现在无需关心这些细节,记住总是标注类型即可。</p>
<p>常量可以在任何作用域中声明,包括全局作用域,这在一个值需要被很多部分的代码用到时很有用。</p>
<p>最后一个区别是,常量只能被设置为常量表达式,而不可以是其他任何只能在运行时计算出的值。</p>
<p>下面是一个声明常量的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
<span class="boring">}</span></code></pre></pre>
<p>常量的名称是 <code>THREE_HOURS_IN_SECONDS</code>,它的值被设置为 60一分钟内的秒数乘以 60一小时内的分钟数再乘以 3我们在这个程序中要计算的小时数的结果。Rust 对常量的命名约定是在单词之间使用全大写加下划线。编译器能够在编译时计算一组有限的操作,这使我们可以选择以更容易理解和验证的方式写出此值,而不是将此常量设置为值 10,800。有关声明常量时可以使用哪些操作的详细信息请参阅 <a href="https://doc.rust-lang.org/reference/const_eval.html">Rust Reference 的常量求值部分</a></p>
<p>在声明它的作用域之中,常量在整个程序生命周期中都有效,此属性使得常量可以作为多处代码使用的全局范围的值,例如一个游戏中所有玩家可以获取的最高分或者光速。</p>
<p>将遍布于应用程序中的硬编码值声明为常量,能帮助后来的代码维护人员了解值的意图。如果将来需要修改硬编码值,也只需修改汇聚于一处的硬编码值。</p>
<h3 id="隐藏"><a class="header" href="#隐藏">隐藏</a></h3>
<p>正如在<a href="ch02-00-guessing-game-tutorial.html#%E6%AF%94%E8%BE%83%E7%8C%9C%E6%B5%8B%E7%9A%84%E6%95%B0%E5%AD%97%E5%92%8C%E7%A7%98%E5%AF%86%E6%95%B0%E5%AD%97">第二章</a>猜数字游戏中所讲我们可以定义一个与之前变量同名的新变量。Rustacean 们称之为第一个变量被第二个 <strong>隐藏Shadowing</strong> 了,这意味着当您使用变量的名称时,编译器将看到第二个变量。实际上,第二个变量“遮蔽”了第一个变量,此时任何使用该变量名的行为中都会视为是在使用第二个变量,直到第二个变量自己也被隐藏或第二个变量的作用域结束。可以用相同变量名称来隐藏一个变量,以及重复使用 <code>let</code> 关键字来多次隐藏,如下所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("The value of x in the inner scope is: {x}");
}
println!("The value of x is: {x}");
}</code></pre></pre>
<p>这个程序首先将 <code>x</code> 绑定到值 <code>5</code> 上。接着通过 <code>let x =</code> 创建了一个新变量 <code>x</code>,获取初始值并加 <code>1</code>,这样 <code>x</code> 的值就变成 <code>6</code> 了。然后,在使用花括号创建的内部作用域内,第三个 <code>let</code> 语句也隐藏了 <code>x</code> 并创建了一个新的变量,将之前的值乘以 <code>2</code><code>x</code> 得到的值是 <code>12</code>。当该作用域结束时,内部 shadowing 的作用域也结束了,<code>x</code> 又返回到 <code>6</code>。运行这个程序,它会有如下输出:</p>
<pre><code class="language-console">$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/variables`
The value of x in the inner scope is: 12
The value of x is: 6
</code></pre>
<p>隐藏与将变量标记为 <code>mut</code> 是有区别的。当不小心尝试对变量重新赋值时,如果没有使用 <code>let</code> 关键字,就会导致编译时错误。通过使用 <code>let</code>,我们可以用这个值进行一些计算,不过计算完之后变量仍然是不可变的。</p>
<p><code>mut</code> 与隐藏的另一个区别是,当再次使用 <code>let</code> 时,实际上创建了一个新变量,我们可以改变值的类型,并且复用这个名字。例如,假设程序请求用户输入空格字符来说明希望在文本之间显示多少个空格,接下来我们想将输入存储成数字(多少个空格):</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let spaces = " ";
let spaces = spaces.len();
<span class="boring">}</span></code></pre></pre>
<p>第一个 <code>spaces</code> 变量是字符串类型,第二个 <code>spaces</code> 变量是数字类型。隐藏使我们不必使用不同的名字,如 <code>spaces_str</code><code>spaces_num</code>;相反,我们可以复用 <code>spaces</code> 这个更简单的名字。然而,如果尝试使用 <code>mut</code>,将会得到一个编译时错误,如下所示:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let mut spaces = " ";
spaces = spaces.len();
<span class="boring">}</span></code></pre>
<p>这个错误说明,我们不能改变变量的类型:</p>
<pre><code class="language-console">$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0308]: mismatched types
--&gt; src/main.rs:3:14
|
2 | let mut spaces = " ";
| ----- expected due to this value
3 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected `&amp;str`, found `usize`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `variables` (bin "variables") due to 1 previous error
</code></pre>
<p>现在我们已经了解了变量如何工作,让我们看看变量可以拥有的更多数据类型。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="数据类型"><a class="header" href="#数据类型">数据类型</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch03-02-data-types.md">ch03-02-data-types.md</a>
<br>
commit d0acb2595c891de97a133d06635c50ab449dd65c</p>
</blockquote>
<p>在 Rust 中,每一个值都属于某一个 <strong>数据类型</strong><em>data type</em>),这告诉 Rust 它被指定为何种数据以便明确数据处理方式。我们将看到两类数据类型子集标量scalar和复合compound</p>
<p>记住Rust 是 <strong>静态类型</strong><em>statically typed</em>)语言,也就是说在编译时就必须知道所有变量的类型。根据值及其使用方式,编译器通常可以推断出我们想要用的类型。当多种类型均有可能时,比如第二章的 <a href="ch02-00-guessing-game-tutorial.html#%E6%AF%94%E8%BE%83%E7%8C%9C%E6%B5%8B%E7%9A%84%E6%95%B0%E5%AD%97%E5%92%8C%E7%A7%98%E5%AF%86%E6%95%B0%E5%AD%97">“比较猜测的数字和秘密数字”</a> 使用 <code>parse</code><code>String</code> 转换为数字时,必须增加类型注解,像这样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let guess: u32 = "42".parse().expect("Not a number!");
<span class="boring">}</span></code></pre></pre>
<p>如果不像上面的代码这样添加类型注解 <code>: u32</code>Rust 会显示如下错误,这说明编译器需要我们提供更多信息,来了解我们想要的类型:</p>
<pre><code class="language-console">$ cargo build
Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)
error[E0284]: type annotations needed
--&gt; src/main.rs:2:9
|
2 | let guess = "42".parse().expect("Not a number!");
| ^^^^^ ----- type must be known at this point
|
= note: cannot satisfy `&lt;_ as FromStr&gt;::Err == _`
help: consider giving `guess` an explicit type
|
2 | let guess: /* Type */ = "42".parse().expect("Not a number!");
| ++++++++++++
For more information about this error, try `rustc --explain E0284`.
error: could not compile `no_type_annotations` (bin "no_type_annotations") due to 1 previous error
</code></pre>
<p>你会看到其它数据类型的各种类型注解。</p>
<h3 id="标量类型"><a class="header" href="#标量类型">标量类型</a></h3>
<p><strong>标量</strong><em>scalar</em>类型代表一个单独的值。Rust 有四种基本的标量类型:整型、浮点型、布尔类型和字符类型。你可能在其他语言中见过它们。让我们深入了解它们在 Rust 中是如何工作的。</p>
<h4 id="整型"><a class="header" href="#整型">整型</a></h4>
<p><strong>整数</strong> 是一个没有小数部分的数字。我们在第二章使用过 <code>u32</code> 整数类型。该类型声明表明,它关联的值应该是一个占据 32 比特位的无符号整数(有符号整数类型以 <code>i</code> 开头而不是 <code>u</code>)。表格 3-1 展示了 Rust 内建的整数类型。我们可以使用其中的任一个来声明一个整数值的类型。</p>
<p><span class="caption">表格 3-1: Rust 中的整型</span></p>
<div class="table-wrapper"><table><thead><tr><th>长度</th><th>有符号</th><th>无符号</th></tr></thead><tbody>
<tr><td>8-bit</td><td><code>i8</code></td><td><code>u8</code></td></tr>
<tr><td>16-bit</td><td><code>i16</code></td><td><code>u16</code></td></tr>
<tr><td>32-bit</td><td><code>i32</code></td><td><code>u32</code></td></tr>
<tr><td>64-bit</td><td><code>i64</code></td><td><code>u64</code></td></tr>
<tr><td>128-bit</td><td><code>i128</code></td><td><code>u128</code></td></tr>
<tr><td>arch</td><td><code>isize</code></td><td><code>usize</code></td></tr>
</tbody></table>
</div>
<p>每一个变体都可以是有符号或无符号的,并有一个明确的大小。<strong>有符号</strong><strong>无符号</strong> 代表数字能否为负值,换句话说,这个数字是否有可能是负数(有符号数),或者永远为正而不需要符号(无符号数)。这有点像在纸上书写数字:当需要考虑符号的时候,数字以加号或减号作为前缀;然而,可以安全地假设为正数时,加号前缀通常省略。有符号数以<a href="https://en.wikipedia.org/wiki/Two%27s_complement">补码形式twos complement representation</a> 存储。</p>
<p>每一个有符号的变体可以储存包含从 -(2<sup>n - 1</sup>) 到 2<sup>n - 1</sup> - 1 在内的数字,这里 <em>n</em> 是变体使用的位数。所以 <code>i8</code> 可以储存从 -(2<sup>7</sup>) 到 2<sup>7</sup> - 1 在内的数字,也就是从 -128 到 127。无符号的变体可以储存从 0 到 2<sup>n</sup> - 1 的数字,所以 <code>u8</code> 可以储存从 0 到 2<sup>8</sup> - 1 的数字,也就是从 0 到 255。</p>
<p>另外,<code>isize</code><code>usize</code> 类型依赖运行程序的计算机架构64 位架构上它们是 64 位的32 位架构上它们是 32 位的。</p>
<p>可以使用表格 3-2 中的任何一种形式编写数字字面值。请注意可以是多种数字类型的数字字面值允许使用类型后缀,例如 <code>57u8</code> 来指定类型,同时也允许使用 <code>_</code> 做为分隔符以方便读数,例如<code>1_000</code>,它的值与你指定的 <code>1000</code> 相同。</p>
<p><span class="caption">表格 3-2: Rust 中的整型字面值</span></p>
<div class="table-wrapper"><table><thead><tr><th>数字字面值</th><th>例子</th></tr></thead><tbody>
<tr><td>Decimal (十进制)</td><td><code>98_222</code></td></tr>
<tr><td>Hex (十六进制)</td><td><code>0xff</code></td></tr>
<tr><td>Octal (八进制)</td><td><code>0o77</code></td></tr>
<tr><td>Binary (二进制)</td><td><code>0b1111_0000</code></td></tr>
<tr><td>Byte (单字节字符)(仅限于<code>u8</code>)</td><td><code>b'A'</code></td></tr>
</tbody></table>
</div>
<p>那么该使用哪种类型的数字呢如果拿不定主意Rust 的默认类型通常是个不错的起点,数字类型默认是 <code>i32</code><code>isize</code><code>usize</code> 主要作为某些集合的索引。</p>
<blockquote>
<h5 id="整型溢出"><a class="header" href="#整型溢出">整型溢出</a></h5>
<p>比方说有一个 <code>u8</code> ,它可以存放从零到 <code>255</code> 的值。那么当你将其修改为 <code>256</code> 时会发生什么呢?这被称为 “整型溢出”“integer overflow” ),这会导致以下两种行为之一的发生。当在 debug 模式编译时Rust 检查这类问题并使程序 <em>panic</em>,这个术语被 Rust 用来表明程序因错误而退出。第九章 <a href="ch09-01-unrecoverable-errors-with-panic.html"><code>panic!</code> 与不可恢复的错误”</a> 部分会详细介绍 panic。</p>
<p>使用 <code>--release</code> flag 在 release 模式中构建时Rust <strong>不会</strong>检测会导致 panic 的整型溢出。相反发生整型溢出时Rust 会进行一种被称为二进制补码 wrapping<em>twos complement wrapping</em>)的操作。简而言之,比此类型能容纳最大值还大的值会回绕到最小值,值 <code>256</code> 变成 <code>0</code>,值 <code>257</code> 变成 <code>1</code>,依此类推。程序不会 panic不过变量可能也不会是你所期望的值。依赖整型溢出 wrapping 的行为被认为是一种错误。</p>
<p>为了显式地处理溢出的可能性,可以使用这几类标准库提供的原始数字类型方法:</p>
<ul>
<li>所有模式下都可以使用 <code>wrapping_*</code> 方法进行 wrapping<code>wrapping_add</code></li>
<li>如果 <code>checked_*</code> 方法出现溢出,则返回 <code>None</code></li>
<li><code>overflowing_*</code> 方法返回值和一个布尔值,表示是否出现溢出</li>
<li><code>saturating_*</code> 方法在值的最小值或最大值处进行饱和处理</li>
</ul>
</blockquote>
<h4 id="浮点型"><a class="header" href="#浮点型">浮点型</a></h4>
<p>Rust 也有两个原生的 <strong>浮点数</strong><em>floating-point numbers</em>类型它们是带小数点的数字。Rust 的浮点数类型是 <code>f32</code><code>f64</code>,分别占 32 位和 64 位。默认类型是 <code>f64</code>,因为在现代 CPU 中,它与 <code>f32</code> 速度几乎一样,不过精度更高。所有的浮点型都是有符号的。</p>
<p>这是一个展示浮点数的实例:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}</code></pre></pre>
<p>浮点数采用 IEEE-754 标准表示。<code>f32</code> 是单精度浮点数,<code>f64</code> 是双精度浮点数。</p>
<h4 id="数值运算"><a class="header" href="#数值运算">数值运算</a></h4>
<p>Rust 中的所有数字类型都支持基本数学运算:加法、减法、乘法、除法和取余。整数除法会向零舍入到最接近的整数。下面的代码展示了如何在 <code>let</code> 语句中使用它们:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
// addition
let sum = 5 + 10;
// subtraction
let difference = 95.5 - 4.3;
// multiplication
let product = 4 * 30;
// division
let quotient = 56.7 / 32.2;
let truncated = -5 / 3; // 结果为 -1
// remainder
let remainder = 43 % 5;
}</code></pre></pre>
<p>这些语句中的每个表达式使用了一个数学运算符并计算出了一个值,然后绑定给一个变量。<a href="appendix-02-operators.html">附录 B</a><!-- ignore --> 包含 Rust 提供的所有运算符的列表。</p>
<h4 id="布尔型"><a class="header" href="#布尔型">布尔型</a></h4>
<p>正如其他大部分编程语言一样Rust 中的布尔类型有两个可能的值:<code>true</code><code>false</code>。Rust 中的布尔类型使用 <code>bool</code> 表示。例如:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let t = true;
let f: bool = false; // with explicit type annotation
}</code></pre></pre>
<p>使用布尔值的主要场景是条件表达式,例如 <code>if</code> 表达式。在 <a href="ch03-05-control-flow.html#%E6%8E%A7%E5%88%B6%E6%B5%81">“控制流”“Control Flow”</a> 部分将介绍 <code>if</code> 表达式在 Rust 中如何工作。</p>
<h4 id="字符类型"><a class="header" href="#字符类型">字符类型</a></h4>
<p>Rust 的 <code>char</code> 类型是语言中最原生的字母类型。下面是一些声明 <code>char</code> 值的例子:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let c = 'z';
let z: char = ''; // with explicit type annotation
let heart_eyed_cat = '😻';
}</code></pre></pre>
<p>注意,我们用单引号声明 <code>char</code> 字面量而与之相反的是使用双引号声明字符串字面量。Rust 的 <code>char</code> 类型的大小为四个字节 (four bytes),并代表了一个 Unicode 标量值Unicode Scalar Value这意味着它可以比 ASCII 表示更多内容。在 Rust 中带变音符号的字母Accented letters中文、日文、韩文等字符emoji绘文字以及零长度的空白字符都是有效的 <code>char</code> 值。Unicode 标量值包含从 <code>U+0000</code><code>U+D7FF</code><code>U+E000</code><code>U+10FFFF</code> 在内的值。不过,“字符” 并不是一个 Unicode 中的概念,所以人直觉上的 “字符” 可能与 Rust 中的 <code>char</code> 并不符合。第八章的 <a href="ch08-02-strings.html#%E4%BD%BF%E7%94%A8%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%82%A8%E5%AD%98-utf-8-%E7%BC%96%E7%A0%81%E7%9A%84%E6%96%87%E6%9C%AC">“使用字符串储存 UTF-8 编码的文本”</a> 中将详细讨论这个主题。</p>
<h3 id="复合类型"><a class="header" href="#复合类型">复合类型</a></h3>
<p><strong>复合类型</strong><em>Compound types</em>可以将多个值组合成一个类型。Rust 有两个原生的复合类型元组tuple和数组array</p>
<h4 id="元组类型"><a class="header" href="#元组类型">元组类型</a></h4>
<p>元组是一个将多个其他类型的值组合进一个复合类型的主要方式。元组长度固定:一旦声明,其长度不会增大或缩小。</p>
<p>我们使用包含在圆括号中的逗号分隔的值列表来创建一个元组。元组中的每一个位置都有一个类型,而且这些不同值的类型也不必是相同的。这个例子中使用了可选的类型注解:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}</code></pre></pre>
<p><code>tup</code> 变量绑定到整个元组上因为元组是一个单独的复合元素。为了从元组中获取单个值可以使用模式匹配pattern matching来解构destructure元组值像这样</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {y}");
}</code></pre></pre>
<p>程序首先创建了一个元组并绑定到 <code>tup</code> 变量上。接着使用了 <code>let</code> 和一个模式将 <code>tup</code> 分成了三个不同的变量,<code>x</code><code>y</code><code>z</code>。这叫做 <strong>解构</strong><em>destructuring</em>),因为它将一个元组拆成了三个部分。最后,程序打印出了 <code>y</code> 的值,也就是 <code>6.4</code></p>
<p>我们也可以使用点号(<code>.</code>)后跟值的索引来直接访问它们。例如:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;
}</code></pre></pre>
<p>这个程序创建了一个元组,<code>x</code>,然后使用其各自的索引访问元组中的每个元素。跟大多数编程语言一样,元组的第一个索引值是 0。</p>
<p>不带任何值的元组有个特殊的名称,叫做 <strong>单元unit</strong> 元组。这种值以及对应的类型都写作 <code>()</code>,表示空值或空的返回类型。如果表达式不返回任何其他值,则会隐式返回单元值。</p>
<h4 id="数组类型"><a class="header" href="#数组类型">数组类型</a></h4>
<p>另一个包含多个值的方式是 <strong>数组</strong><em>array</em>。与元组不同数组中的每个元素的类型必须相同。Rust 中的数组与一些其他语言中的数组不同Rust 中的数组长度是固定的。</p>
<p>我们将数组的值写成在方括号内,用逗号分隔:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let a = [1, 2, 3, 4, 5];
}</code></pre></pre>
<p>当你想要在栈stack而不是在堆heap上为数据分配空间<a href="ch04-01-what-is-ownership.html#%E6%A0%88stack%E4%B8%8E%E5%A0%86heap">第四章</a>将讨论栈与堆的更多内容),或者是想要确保总是有固定数量的元素时,数组非常有用。但是数组并不如 vector 类型灵活。vector 类型是标准库提供的一个 <strong>允许</strong> 增长和缩小长度的类似数组的集合类型。当不确定是应该使用数组还是 vector 的时候,那么很可能应该使用 vector。<a href="ch08-01-vectors.html">第八章</a>会详细讨论 vector。</p>
<p>然而,当你确定元素个数不会改变时,数组会更有用。例如,当你在一个程序中使用月份名字时,你更应趋向于使用数组而不是 vector因为你确定只会有 12 个元素。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
<span class="boring">}</span></code></pre></pre>
<p>可以像这样编写数组的类型:在方括号中包含每个元素的类型,后跟分号,再后跟数组元素的数量。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let a: [i32; 5] = [1, 2, 3, 4, 5];
<span class="boring">}</span></code></pre></pre>
<p>这里,<code>i32</code> 是每个元素的类型。分号之后,数字 <code>5</code> 表明该数组包含五个元素。</p>
<p>你还可以通过在方括号中指定初始值加分号再加元素个数的方式来创建一个每个元素都为相同值的数组:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let a = [3; 5];
<span class="boring">}</span></code></pre></pre>
<p>变量名为 <code>a</code> 的数组将包含 <code>5</code> 个元素,这些元素的值最初都将被设置为 <code>3</code>。这种写法与 <code>let a = [3, 3, 3, 3, 3];</code> 效果相同,但更简洁。</p>
<h5 id="访问数组元素"><a class="header" href="#访问数组元素">访问数组元素</a></h5>
<p>数组是可以在栈 (stack) 上分配的已知固定大小的单个内存块。可以使用索引来访问数组的元素,像这样:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];
}</code></pre></pre>
<p>在这个例子中,叫做 <code>first</code> 的变量的值是 <code>1</code>,因为它是数组索引 <code>[0]</code> 的值。变量 <code>second</code> 将会是数组索引 <code>[1]</code> 的值 <code>2</code></p>
<h5 id="无效的数组元素访问"><a class="header" href="#无效的数组元素访问">无效的数组元素访问</a></h5>
<p>让我们看看如果我们访问数组结尾之后的元素会发生什么呢?比如你执行以下代码,它使用类似于第 2 章中的猜数字游戏的代码从用户那里获取数组索引:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore panics">use std::io;
fn main() {
let a = [1, 2, 3, 4, 5];
println!("Please enter an array index.");
let mut index = String::new();
io::stdin()
.read_line(&amp;mut index)
.expect("Failed to read line");
let index: usize = index
.trim()
.parse()
.expect("Index entered was not a number");
let element = a[index];
println!("The value of the element at index {index} is: {element}");
}</code></pre>
<p>此代码编译成功。如果您使用 <code>cargo run</code> 运行此代码并输入 <code>0</code><code>1</code><code>2</code><code>3</code><code>4</code>,程序将在数组中的索引处打印出相应的值。如果你输入一个超过数组末端的数字,如 10你会看到这样的输出</p>
<pre><code class="language-console">thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:19:19
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>程序在索引操作中使用一个无效的值时导致 <strong>运行时</strong> 错误。程序带着错误信息退出,并且没有执行最后的 <code>println!</code> 语句。当尝试用索引访问一个元素时Rust 会检查指定的索引是否小于数组的长度。如果索引超出了数组长度Rust 会 <em>panic</em>,这是 Rust 术语,它用于程序因为错误而退出的情况。这种检查必须在运行时进行,特别是在这种情况下,因为编译器不可能知道用户在以后运行代码时将输入什么值。</p>
<p>这是第一个在实战中遇到的 Rust 安全原则的例子。在很多底层语言中并没有进行这类检查这样当提供了一个不正确的索引时就会访问无效的内存。通过立即退出而不是允许内存访问并继续执行Rust 让你避开此类错误。第九章会更详细地讨论 Rust 的错误处理机制,以及如何编写可读性强而又安全的代码,使程序既不会 panic 也不会导致非法内存访问。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="函数"><a class="header" href="#函数">函数</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch03-03-how-functions-work.md">ch03-03-how-functions-work.md</a>
<br>
commit d0acb2595c891de97a133d06635c50ab449dd65c</p>
</blockquote>
<p>函数在 Rust 代码中非常普遍。你已经见过语言中最重要的函数之一:<code>main</code> 函数,它是很多程序的入口点。你也见过 <code>fn</code> 关键字,它用来声明新函数。</p>
<p>Rust 代码中的函数和变量名使用 <em>snake case</em> 规范风格。在 snake case 中,所有字母都是小写并使用下划线分隔单词。这是一个包含函数定义示例的程序:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
println!("Hello, world!");
another_function();
}
fn another_function() {
println!("Another function.");
}</code></pre></pre>
<p>我们在 Rust 中通过输入 <code>fn</code> 后面跟着函数名和一对圆括号来定义函数。大括号告诉编译器哪里是函数体的开始和结尾。</p>
<p>可以使用函数名后跟圆括号来调用我们定义过的任意函数。因为程序中已定义 <code>another_function</code> 函数,所以可以在 <code>main</code> 函数中调用它。注意,源码中 <code>another_function</code> 定义在 <code>main</code> 函数 <strong>之后</strong>也可以定义在之前。Rust 不关心函数定义所在的位置,只要函数被调用时出现在调用之处可见的作用域内就行。</p>
<p>让我们新建一个叫做 <em>functions</em> 的二进制项目来进一步探索函数。将上面的 <code>another_function</code> 例子写入 <em>src/main.rs</em> 中并运行。你应该会看到如下输出:</p>
<pre><code class="language-console">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s
Running `target/debug/functions`
Hello, world!
Another function.
</code></pre>
<p><code>main</code> 函数中的代码会按顺序执行。首先,打印 “Hello, world!” 信息,然后调用 <code>another_function</code> 函数并打印它的信息。</p>
<h3 id="参数"><a class="header" href="#参数">参数</a></h3>
<p>我们可以定义为拥有 <strong>参数</strong><em>parameters</em>)的函数,参数是特殊变量,是函数签名的一部分。当函数拥有参数(形参)时,可以为这些参数提供具体的值(实参)。技术上讲,这些具体值被称为参数(<em>arguments</em>),但是在日常交流中,人们倾向于不区分使用 <em>parameter</em><em>argument</em> 来表示函数定义中的变量或调用函数时传入的具体值。</p>
<p>在这版 <code>another_function</code> 中,我们增加了一个参数:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
another_function(5);
}
fn another_function(x: i32) {
println!("The value of x is: {x}");
}</code></pre></pre>
<p>尝试运行程序,将会输出如下内容:</p>
<pre><code class="language-console">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.21s
Running `target/debug/functions`
The value of x is: 5
</code></pre>
<p><code>another_function</code> 的声明中有一个命名为 <code>x</code> 的参数。<code>x</code> 的类型被指定为 <code>i32</code>。当我们将 <code>5</code> 传给 <code>another_function</code> 时,<code>println!</code> 宏会把 <code>5</code> 放在格式字符串中包含 <code>x</code> 的那对花括号的位置。</p>
<p>在函数签名中,<strong>必须</strong> 声明每个参数的类型。这是 Rust 设计中一个经过慎重考虑的决定:要求在函数定义中提供类型注解,意味着编译器再也不需要你在代码的其他地方注明类型来指出你的意图。而且,在知道函数需要什么类型后,编译器就能够给出更有用的错误消息。</p>
<p>当定义多个参数时,使用逗号分隔,像这样:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
print_labeled_measurement(5, 'h');
}
fn print_labeled_measurement(value: i32, unit_label: char) {
println!("The measurement is: {value}{unit_label}");
}</code></pre></pre>
<p>这个例子创建了一个名为 <code>print_labeled_measurement</code> 的函数,它有两个参数。第一个参数名为 <code>value</code>,类型是 <code>i32</code>。第二个参数是 <code>unit_label</code> ,类型是 <code>char</code>。然后,该函数打印包含 <code>value</code><code>unit_label</code> 的文本。</p>
<p>尝试运行代码。使用上面的例子替换当前 <em>functions</em> 项目的 <em>src/main.rs</em> 文件,并用 <code>cargo run</code> 运行它:</p>
<pre><code class="language-console">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/functions`
The measurement is: 5h
</code></pre>
<p>因为我们使用 <code>5</code> 作为 <code>value</code> 的值,<code>h</code> 作为 <code>unit_label</code> 的值来调用函数,所以程序输出包含这些值。</p>
<h3 id="语句和表达式"><a class="header" href="#语句和表达式">语句和表达式</a></h3>
<p>函数体由一系列的语句和一个可选的结尾表达式构成。目前为止,我们提到的函数还不包含结尾表达式,不过你已经见过作为语句一部分的表达式。因为 Rust 是一门基于表达式expression-based的语言这是一个需要理解的不同于其他语言重要区别。其他语言并没有这样的区别所以让我们看看语句与表达式有什么区别以及这些区别是如何影响函数体的。</p>
<p><strong>语句</strong><em>Statements</em>)是执行一些操作但不返回值的指令。
<strong>表达式</strong><em>Expressions</em>)计算并产生一个值。让我们看一些例子。</p>
<p>实际上,我们已经使用过语句和表达式。使用 <code>let</code> 关键字创建变量并绑定一个值是一个语句。在列表 3-1 中,<code>let y = 6;</code> 是一个语句。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let y = 6;
}</code></pre></pre>
<p><span class="caption">列表 3-1包含一个语句的 <code>main</code> 函数定义</span></p>
<p>函数定义也是语句,上面整个例子本身就是一个语句。</p>
<p>语句不返回值。因此,不能把 <code>let</code> 语句赋值给另一个变量,比如下面的例子尝试做的,会产生一个错误:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let x = (let y = 6);
}</code></pre>
<p>当运行这个程序时,会得到如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error: expected expression, found `let` statement
--&gt; src/main.rs:2:14
|
2 | let x = (let y = 6);
| ^^^
|
= note: only supported directly in conditions of `if` and `while` expressions
warning: unnecessary parentheses around assigned value
--&gt; src/main.rs:2:13
|
2 | let x = (let y = 6);
| ^ ^
|
= note: `#[warn(unused_parens)]` on by default
help: remove these parentheses
|
2 - let x = (let y = 6);
2 + let x = let y = 6;
|
warning: `functions` (bin "functions") generated 1 warning
error: could not compile `functions` (bin "functions") due to 1 previous error; 1 warning emitted
</code></pre>
<p><code>let y = 6</code> 语句并不返回值,所以没有可以绑定到 <code>x</code> 上的值。这与其他语言不同,例如 C 和 Ruby它们的赋值语句会返回所赋的值。在这些语言中可以这么写 <code>x = y = 6</code>,这样 <code>x</code><code>y</code> 的值都是 <code>6</code>Rust 中不能这样写。</p>
<p>表达式会计算出一个值,并且你将编写的大部分 Rust 代码是由表达式组成的。考虑一个数学运算,比如 <code>5 + 6</code>,这是一个表达式并计算出值 <code>11</code>。表达式可以是语句的一部分:在示例 3-1 中,语句 <code>let y = 6;</code> 中的 <code>6</code> 是一个表达式,它计算出的值是 <code>6</code>。函数调用是一个表达式。宏调用是一个表达式。用大括号创建的一个新的块作用域也是一个表达式,例如:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let y = {
let x = 3;
x + 1
};
println!("The value of y is: {y}");
}</code></pre></pre>
<p>这个表达式:</p>
<pre><code class="language-rust ignore">{
let x = 3;
x + 1
}</code></pre>
<p>是一个代码块,它的值是 <code>4</code>。这个值作为 <code>let</code> 语句的一部分被绑定到 <code>y</code> 上。注意 <code>x+1</code> 这一行在结尾没有分号,与你见过的大部分代码行不同。表达式的结尾没有分号。如果在表达式的结尾加上分号,它就变成了语句,而语句不会返回值。在接下来探索具有返回值的函数和表达式时要谨记这一点。</p>
<h3 id="具有返回值的函数"><a class="header" href="#具有返回值的函数">具有返回值的函数</a></h3>
<p>函数可以向调用它的代码返回值。我们并不对返回值命名,但要在箭头(<code>-&gt;</code>)后声明它的类型。在 Rust 中,函数的返回值等同于函数体最后一个表达式的值。使用 <code>return</code> 关键字和指定值,可从函数中提前返回;但大部分函数隐式的返回最后的表达式。这是一个有返回值的函数的例子:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn five() -&gt; i32 {
5
}
fn main() {
let x = five();
println!("The value of x is: {x}");
}</code></pre></pre>
<p><code>five</code> 函数中没有函数调用、宏、甚至没有 <code>let</code> 语句 —— 只有数字 <code>5</code>。这在 Rust 中是一个完全有效的函数。注意,也指定了函数返回值的类型,就是 <code>-&gt; i32</code>。尝试运行代码;输出应该看起来像这样:</p>
<pre><code class="language-console">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/functions`
The value of x is: 5
</code></pre>
<p><code>five</code> 函数的返回值是 <code>5</code>,所以返回值类型是 <code>i32</code>。让我们仔细检查一下这段代码。有两个重要的部分:首先,<code>let x = five();</code> 这一行表明我们使用函数的返回值初始化一个变量。因为 <code>five</code> 函数返回 <code>5</code>,这一行与如下代码相同:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let x = 5;
<span class="boring">}</span></code></pre></pre>
<p>其次,<code>five</code> 函数没有参数并定义了返回值类型,不过函数体只有单单一个 <code>5</code> 也没有分号,因为这是一个表达式,我们想要返回它的值。</p>
<p>让我们看看另一个例子:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = plus_one(5);
println!("The value of x is: {x}");
}
fn plus_one(x: i32) -&gt; i32 {
x + 1
}</code></pre></pre>
<p>运行代码会打印出 <code>The value of x is: 6</code>。但如果在包含 <code>x + 1</code> 的行尾加上一个分号,把它从表达式变成语句,我们将看到一个错误。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let x = plus_one(5);
println!("The value of x is: {x}");
}
fn plus_one(x: i32) -&gt; i32 {
x + 1;
}</code></pre>
<p>运行代码会产生一个错误,如下:</p>
<pre><code class="language-console">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error[E0308]: mismatched types
--&gt; src/main.rs:7:24
|
7 | fn plus_one(x: i32) -&gt; i32 {
| -------- ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
8 | x + 1;
| - help: remove this semicolon to return this value
For more information about this error, try `rustc --explain E0308`.
error: could not compile `functions` (bin "functions") due to 1 previous error
</code></pre>
<p>主要的错误信息“mismatched types”类型不匹配揭示了代码的核心问题。函数 <code>plus_one</code> 的定义说明它要返回一个 <code>i32</code> 类型的值,不过语句并不会返回值,使用单位类型 <code>()</code> 表示不返回值。因为不返回值与函数定义相矛盾从而出现一个错误。在输出中Rust 提供了一条信息,可能有助于纠正这个错误:它建议删除分号,这会修复这个错误。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="注释"><a class="header" href="#注释">注释</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch03-04-comments.md">ch03-04-comments.md</a>
<br>
commit d0acb2595c891de97a133d06635c50ab449dd65c</p>
</blockquote>
<p>所有程序员都力求使其代码易于理解,不过有时还需要提供额外的解释。在这种情况下,程序员在源码中留下 <strong>注释</strong><em>comments</em>),编译器会忽略它们,不过阅读代码的人可能觉得有用。</p>
<p>这是一个简单的注释:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// hello, world
<span class="boring">}</span></code></pre></pre>
<p>在 Rust 中,惯用的注释样式是以两个斜杠开始注释,并持续到本行的结尾。对于超过一行的注释,需要在每一行前都加上 <code>//</code>,像这样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// So were doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain whats going on.
<span class="boring">}</span></code></pre></pre>
<p>注释也可以放在包含代码的行的末尾:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let lucky_number = 7; // Im feeling lucky today
}</code></pre></pre>
<p>不过你更经常看到的是以这种格式使用它们,也就是位于它所解释的代码行的上面一行:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
// Im feeling lucky today
let lucky_number = 7;
}</code></pre></pre>
<p>Rust 还有另一种注释,称为文档注释,我们将在 14 章的 <a href="ch14-02-publishing-to-crates-io.html">“将 crate 发布到 Crates.io” </a>部分讨论它。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="控制流"><a class="header" href="#控制流">控制流</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch03-05-control-flow.md">ch03-05-control-flow.md</a>
<br>
commit d0acb2595c891de97a133d06635c50ab449dd65c</p>
</blockquote>
<p>根据条件是否为真来决定是否执行某些代码以及根据条件是否为真来重复运行一段代码的能力是大部分编程语言的基本组成部分。Rust 代码中最常见的用来控制执行流的结构是 <code>if</code> 表达式和循环。</p>
<h3 id="if-表达式"><a class="header" href="#if-表达式"><code>if</code> 表达式</a></h3>
<p><code>if</code> 表达式允许根据条件执行不同的代码分支。你提供一个条件并表示 “如果条件满足,运行这段代码;如果条件不满足,不运行这段代码。</p>
<p><em>projects</em> 目录新建一个叫做 <em>branches</em> 的项目,来学习 <code>if</code> 表达式。在 <em>src/main.rs</em> 文件中,输入如下内容:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let number = 3;
if number &lt; 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}</code></pre></pre>
<p>所有的 <code>if</code> 表达式都以 <code>if</code> 关键字开头,其后跟一个条件。在这个例子中,条件检查变量 <code>number</code> 的值是否小于 5。在条件为 <code>true</code> 时希望执行的代码块位于紧跟条件之后的大括号中。<code>if</code> 表达式中与条件关联的代码块有时被叫做 <em>arms</em>,就像第二章 <a href="ch02-00-guessing-game-tutorial.html#%E6%AF%94%E8%BE%83%E7%8C%9C%E6%B5%8B%E7%9A%84%E6%95%B0%E5%AD%97%E5%92%8C%E7%A7%98%E5%AF%86%E6%95%B0%E5%AD%97">“比较猜测的数字和秘密数字”</a> 部分中讨论到的 <code>match</code> 表达式中的分支一样。</p>
<p>也可以包含一个可选的 <code>else</code> 表达式来提供一个在条件为 <code>false</code> 时应当执行的代码块,这里我们就这么做了。如果不提供 <code>else</code> 表达式并且条件为 <code>false</code> 时,程序会直接忽略 <code>if</code> 代码块并继续执行下面的代码。</p>
<p>尝试运行代码,应该能看到如下输出:</p>
<pre><code class="language-console">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
condition was true
</code></pre>
<p>尝试改变 <code>number</code> 的值使条件为 <code>false</code> 时看看会发生什么:</p>
<pre><code class="language-rust ignore"><span class="boring">fn main() {
</span> let number = 7;
<span class="boring">
</span><span class="boring"> if number &lt; 5 {
</span><span class="boring"> println!("condition was true");
</span><span class="boring"> } else {
</span><span class="boring"> println!("condition was false");
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>再次运行程序并查看输出:</p>
<pre><code class="language-console">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
condition was false
</code></pre>
<p>另外值得注意的是代码中的条件 <strong>必须</strong><code>bool</code> 值。如果条件不是 <code>bool</code> 值,我们将得到一个错误。例如,尝试运行以下代码:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let number = 3;
if number {
println!("number was three");
}
}</code></pre>
<p>这里 <code>if</code> 条件的值是 <code>3</code>Rust 抛出了一个错误:</p>
<pre><code class="language-console">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: mismatched types
--&gt; src/main.rs:4:8
|
4 | if number {
| ^^^^^^ expected `bool`, found integer
For more information about this error, try `rustc --explain E0308`.
error: could not compile `branches` (bin "branches") due to 1 previous error
</code></pre>
<p>这个错误表明 Rust 期望一个 <code>bool</code> 却得到了一个整数。不像 Ruby 或 JavaScript 这样的语言Rust 并不会尝试自动地将非布尔值转换为布尔值。必须总是显式地使用布尔值作为 <code>if</code> 的条件。例如,如果想要 <code>if</code> 代码块只在一个数字不等于 <code>0</code> 时执行,可以把 <code>if</code> 表达式修改成下面这样:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let number = 3;
if number != 0 {
println!("number was something other than zero");
}
}</code></pre></pre>
<p>运行代码会打印出 <code>number was something other than zero</code></p>
<h4 id="使用-else-if-处理多重条件"><a class="header" href="#使用-else-if-处理多重条件">使用 <code>else if</code> 处理多重条件</a></h4>
<p>可以将 <code>else if</code> 表达式与 <code>if</code><code>else</code> 组合来实现多重条件。例如:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
}</code></pre></pre>
<p>这个程序有四个可能的执行路径。运行后应该能看到如下输出:</p>
<pre><code class="language-console">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
number is divisible by 3
</code></pre>
<p>当执行这个程序时,它按顺序检查每个 <code>if</code> 表达式并执行第一个条件为 <code>true</code> 的代码块。注意即使 6 可以被 2 整除,也不会输出 <code>number is divisible by 2</code>,更不会输出 <code>else</code> 块中的 <code>number is not divisible by 4, 3, or 2</code>。原因是 Rust 只会执行第一个条件为 <code>true</code> 的代码块,并且一旦它找到一个以后,甚至都不会检查剩下的条件了。</p>
<p>使用过多的 <code>else if</code> 表达式会使代码显得杂乱无章,所以如果有多于一个 <code>else if</code> 表达式,最好重构代码。为此,第六章会介绍一个强大的 Rust 分支结构branching construct叫做 <code>match</code></p>
<h4 id="在-let-语句中使用-if"><a class="header" href="#在-let-语句中使用-if"><code>let</code> 语句中使用 <code>if</code></a></h4>
<p>因为 <code>if</code> 是一个表达式,我们可以在 <code>let</code> 语句的右侧使用它,例如在示例 3-2 中:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {number}");
}</code></pre></pre>
<p><span class="caption">示例 3-2<code>if</code> 表达式的返回值赋给一个变量</span></p>
<p><code>number</code> 变量将会绑定到表示 <code>if</code> 表达式结果的值上。运行这段代码看看会出现什么:</p>
<pre><code class="language-console">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/branches`
The value of number is: 5
</code></pre>
<p>记住,代码块的值是其最后一个表达式的值,而数字本身就是一个表达式。在这个例子中,整个 <code>if</code> 表达式的值取决于哪个代码块被执行。这意味着 <code>if</code> 的每个分支的可能的返回值都必须是相同类型;在示例 3-2 中,<code>if</code> 分支和 <code>else</code> 分支的结果都是 <code>i32</code> 整型。如果它们的类型不匹配,如下面这个例子,则会出现一个错误:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let condition = true;
let number = if condition { 5 } else { "six" };
println!("The value of number is: {number}");
}</code></pre>
<p>当编译这段代码时,会得到一个错误。<code>if</code><code>else</code> 分支的值类型是不相容的,同时 Rust 也准确地指出在程序中的何处发现的这个问题:</p>
<pre><code class="language-console">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: `if` and `else` have incompatible types
--&gt; src/main.rs:4:44
|
4 | let number = if condition { 5 } else { "six" };
| - ^^^^^ expected integer, found `&amp;str`
| |
| expected because of this
For more information about this error, try `rustc --explain E0308`.
error: could not compile `branches` (bin "branches") due to 1 previous error
</code></pre>
<p><code>if</code> 代码块中的表达式返回一个整数,而 <code>else</code> 代码块中的表达式返回一个字符串。这不可行因为变量必须只有一个类型。Rust 需要在编译时就确切的知道 <code>number</code> 变量的类型,这样它就可以在编译时验证在每处使用的 <code>number</code> 变量的类型是有效的。如果<code>number</code>的类型仅在运行时确定,则 Rust 无法做到这一点;且编译器必须跟踪每一个变量的多种假设类型,那么它就会变得更加复杂,对代码的保证也会减少。</p>
<h3 id="使用循环重复执行"><a class="header" href="#使用循环重复执行">使用循环重复执行</a></h3>
<p>多次执行同一段代码是很常用的Rust 为此提供了多种 <strong>循环</strong><em>loops</em>)。一个循环执行循环体中的代码直到结尾并紧接着回到开头继续执行。为了实验一下循环,让我们新建一个叫做 <em>loops</em> 的项目。</p>
<p>Rust 有三种循环:<code>loop</code><code>while</code><code>for</code>。我们每一个都试试。</p>
<h4 id="使用-loop-重复执行代码"><a class="header" href="#使用-loop-重复执行代码">使用 <code>loop</code> 重复执行代码</a></h4>
<p><code>loop</code> 关键字告诉 Rust 一遍又一遍地执行一段代码直到你明确要求停止。</p>
<p>作为一个例子,将 <em>loops</em> 目录中的 <em>src/main.rs</em> 文件修改为如下:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">fn main() {
loop {
println!("again!");
}
}</code></pre>
<p>当运行这个程序时,我们会看到连续的反复打印 <code>again!</code>,直到我们手动停止程序。大部分终端都支持一个快捷键,<span class="keystroke">ctrl-c</span>,来终止一个陷入无限循环的程序。尝试一下:</p>
<pre><code class="language-console">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished dev [unoptimized + debuginfo] target(s) in 0.29s
Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!
</code></pre>
<p>符号 <code>^C</code> 代表你在这按下了<span class="keystroke">ctrl-c</span>。在 <code>^C</code> 之后你可能看到也可能看不到 <code>again!</code> ,这取决于在接收到终止信号时代码执行到了循环的何处。</p>
<p>幸运的是Rust 提供了一种从代码中跳出循环的方法。可以使用 <code>break</code> 关键字来告诉程序何时停止循环。回忆一下在第二章猜猜看游戏的 <a href="ch02-00-guessing-game-tutorial.html#%E7%8C%9C%E6%B5%8B%E6%AD%A3%E7%A1%AE%E5%90%8E%E9%80%80%E5%87%BA">“猜测正确后退出”</a> 部分使用过它来在用户猜对数字赢得游戏后退出程序。</p>
<p>我们在猜谜游戏中也使用了 <code>continue</code>。循环中的 <code>continue</code> 关键字告诉程序跳过这个循环迭代中的任何剩余代码,并转到下一个迭代。</p>
<h4 id="从循环返回值"><a class="header" href="#从循环返回值">从循环返回值</a></h4>
<p><code>loop</code> 的一个用例是重试可能会失败的操作,比如检查线程是否完成了任务。然而你可能会需要将操作的结果传递给其它的代码。如果将返回值加入你用来停止循环的 <code>break</code> 表达式,它会被停止的循环返回:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}</code></pre></pre>
<p>在循环之前,我们声明了一个名为 <code>counter</code> 的变量并初始化为 <code>0</code>。接着声明了一个名为 <code>result</code> 来存放循环的返回值。在循环的每一次迭代中,我们将 <code>counter</code> 变量加 <code>1</code>,接着检查计数是否等于 <code>10</code>。当相等时,使用 <code>break</code> 关键字返回值 <code>counter * 2</code>。循环之后,我们通过分号结束赋值给 <code>result</code> 的语句。最后打印出 <code>result</code> 的值,也就是 <code>20</code></p>
<h4 id="循环标签在多个循环之间消除歧义"><a class="header" href="#循环标签在多个循环之间消除歧义">循环标签:在多个循环之间消除歧义</a></h4>
<p>如果存在嵌套循环,<code>break</code><code>continue</code> 应用于此时最内层的循环。你可以选择在一个循环上指定一个 <strong>循环标签</strong><em>loop label</em>),然后将标签与 <code>break</code><code>continue</code> 一起使用,使这些关键字应用于已标记的循环而不是最内层的循环。下面是一个包含两个嵌套循环的示例</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}</code></pre></pre>
<p>外层循环有一个标签 <code>counting_up</code>,它将从 0 数到 2。没有标签的内部循环从 10 向下数到 9。第一个没有指定标签的 <code>break</code> 将只退出内层循环。<code>break 'counting_up;</code> 语句将退出外层循环。这个代码打印:</p>
<pre><code class="language-console">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.58s
Running `target/debug/loops`
count = 0
remaining = 10
remaining = 9
count = 1
remaining = 10
remaining = 9
count = 2
remaining = 10
End count = 2
</code></pre>
<h4 id="while-条件循环"><a class="header" href="#while-条件循环"><code>while</code> 条件循环</a></h4>
<p>在程序中计算循环的条件也很常见。当条件为 <code>true</code>,执行循环。当条件不再为 <code>true</code>,调用 <code>break</code> 停止循环。这个循环类型可以通过组合 <code>loop</code><code>if</code><code>else</code><code>break</code> 来实现;如果你喜欢的话,现在就可以在程序中试试。</p>
<p>然而这个模式太常用了Rust 为此内置了一个语言结构,它被称为 <code>while</code> 循环。示例 3-3 使用了 <code>while</code>:程序循环三次,每次数字都减一。接着,在循环结束后,打印出另一个信息并退出。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
}</code></pre></pre>
<p><span class="caption">示例 3-3: 当条件为真时,使用 <code>while</code> 循环运行代码</span></p>
<p>这种结构消除了很多使用 <code>loop</code><code>if</code><code>else</code><code>break</code> 时所必须的嵌套,这样更加清晰。当条件为 <code>true</code> 就执行,否则退出循环。</p>
<h4 id="使用-for-遍历集合"><a class="header" href="#使用-for-遍历集合">使用 <code>for</code> 遍历集合</a></h4>
<p>可以使用 <code>while</code> 结构来遍历集合中的元素,比如数组。例如,看看示例 3-4。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index &lt; 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}</code></pre></pre>
<p><span class="caption">示例 3-4使用 <code>while</code> 循环遍历集合中的元素</span></p>
<p>这里,代码对数组中的元素进行计数。它从索引 <code>0</code> 开始,并接着循环直到遇到数组的最后一个索引(这时,<code>index &lt; 5</code> 不再为真)。运行这段代码会打印出数组中的每一个元素:</p>
<pre><code class="language-console">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.32s
Running `target/debug/loops`
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
</code></pre>
<p>数组中的所有五个元素都如期被打印出来。尽管 <code>index</code> 在某一时刻会到达值 <code>5</code>,不过循环在其尝试从数组获取第六个值(会越界)之前就停止了。</p>
<p>但这个过程很容易出错;如果索引长度或测试条件不正确会导致程序 panic。例如如果将 <code>a</code> 数组的定义改为包含 4 个元素而忘记了更新条件 <code>while index &lt; 4</code>,则代码会 panic。这也使程序更慢因为编译器增加了运行时代码来对每次循环进行条件检查以确定在循环的每次迭代中索引是否在数组的边界内。</p>
<p>作为更简洁的替代方案,可以使用 <code>for</code> 循环来对一个集合的每个元素执行一些代码。<code>for</code> 循环看起来如示例 3-5 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}</code></pre></pre>
<p><span class="caption">示例 3-5使用 <code>for</code> 循环遍历集合中的元素</span></p>
<p>当运行这段代码时,将看到与示例 3-4 一样的输出。更为重要的是,我们增强了代码安全性,并消除了可能由于超出数组的结尾或遍历长度不够而缺少一些元素而导致的 bug。</p>
<p>例如,在示例 3-4 的代码中,如果你将 <code>a</code> 数组的定义改为有四个元素,但忘记将条件更新为 <code>while index &lt; 4</code>,代码将会 panic。使用 <code>for</code> 循环的话,就不需要惦记着在改变数组元素个数时修改其他的代码了。</p>
<p><code>for</code> 循环的安全性和简洁性使得它成为 Rust 中使用最多的循环结构。即使是在想要循环执行代码特定次数时,例如示例 3-3 中使用 <code>while</code> 循环的倒计时例子,大部分 Rustacean 也会使用 <code>for</code> 循环。这么做的方式是使用 <code>Range</code>,它是标准库提供的类型,用来生成从一个数字开始到另一个数字之前结束的所有数字的序列。</p>
<p>下面是一个使用 <code>for</code> 循环来倒计时的例子,它还使用了一个我们还未讲到的方法,<code>rev</code>,用来反转 range。</p>
<p>注意:以下代码不会踏足到数字 4仅从一个数字开始到另一个数字之前。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}</code></pre></pre>
<p>这段代码看起来更帅气不是吗?</p>
<h2 id="总结-2"><a class="header" href="#总结-2">总结</a></h2>
<p>你做到了!这是一个大章节:你学习了变量、标量和复合数据类型、函数、注释、 <code>if</code> 表达式和循环!如果你想要实践本章讨论的概念,尝试构建如下程序:</p>
<ul>
<li>相互转换摄氏与华氏温度。</li>
<li>生成第 n 个斐波那契数。</li>
<li>打印圣诞颂歌 “The Twelve Days of Christmas” 的歌词,并利用歌曲中的重复部分(编写循环)。</li>
</ul>
<p>当你准备好继续的时候,让我们讨论一个其他语言中 <strong>并不</strong> 常见的概念所有权ownership</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="认识所有权"><a class="header" href="#认识所有权">认识所有权</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch04-00-understanding-ownership.md">ch04-00-understanding-ownership.md</a>
<br>
commit a5e0c5b2c5f9054be3b961aea2c7edfeea591de8</p>
</blockquote>
<p>所有权(系统)是 Rust 最为与众不同的特性,对语言的其他部分有着深刻含义。它让 Rust 无需垃圾回收garbage collector即可保障内存安全因此理解 Rust 中所有权如何工作是十分重要的。本章我们将讲到所有权以及相关功能借用borrowing、slice 以及 Rust 如何在内存中布局数据。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="什么是所有权"><a class="header" href="#什么是所有权">什么是所有权?</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch04-01-what-is-ownership.md">ch04-01-what-is-ownership.md</a>
<br>
commit 3d51f70c78162faaebcab0da0de2ddd333e7a8ed</p>
</blockquote>
<p><strong>所有权</strong><em>ownership</em>)是 Rust 用于如何管理内存的一组规则。所有程序都必须管理其运行时使用计算机内存的方式。一些语言中具有垃圾回收机制在程序运行时有规律地寻找不再使用的内存在另一些语言中程序员必须亲自分配和释放内存。Rust 则选择了第三种方式:通过所有权系统管理内存,编译器在编译时会根据一系列的规则进行检查。如果违反了任何这些规则,程序都不能编译。在运行时,所有权系统的任何功能都不会减慢程序。</p>
<p>因为所有权对很多程序员来说都是一个新概念,需要一些时间来适应。好消息是随着你对 Rust 和所有权系统的规则越来越有经验,你就越能自然地编写出安全和高效的代码。持之以恒!</p>
<p>当你理解了所有权,你将有一个坚实的基础来理解那些使 Rust 独特的功能。在本章中,你将通过完成一些示例来学习所有权,这些示例基于一个常用的数据结构:字符串。</p>
<blockquote>
<h3 id="栈stack与堆heap"><a class="header" href="#栈stack与堆heap">Stack与堆Heap</a></h3>
<p>在很多语言中,你并不需要经常考虑到栈与堆。不过在像 Rust 这样的系统编程语言中,值是位于栈上还是堆上在更大程度上影响了语言的行为以及为何必须做出这样的抉择。我们会在本章的稍后部分描述所有权与栈和堆相关的内容,所以这里只是一个用来预热的简要解释。</p>
<p>栈和堆都是代码在运行时可供使用的内存,但是它们的结构不同。栈以放入值的顺序存储值并以相反顺序取出值。这也被称作 <strong>后进先出</strong><em>last in, first out</em>)。想象一下一叠盘子:当增加更多盘子时,把它们放在盘子堆的顶部,当需要盘子时,也从顶部拿走。不能从中间也不能从底部增加或拿走盘子!增加数据叫做 <strong>进栈</strong><em>pushing onto the stack</em>),而移出数据叫做 <strong>出栈</strong><em>popping off the stack</em>)。栈中的所有数据都必须占用已知且固定的大小。在编译时大小未知或大小可能变化的数据,要改为存储在堆上。
堆是缺乏组织的当向堆放入数据时你要请求一定大小的空间。内存分配器memory allocator在堆的某处找到一块足够大的空位把它标记为已使用并返回一个表示该位置地址的 <strong>指针</strong><em>pointer</em>)。这个过程称作 <strong>在堆上分配内存</strong><em>allocating on the heap</em>),有时简称为 “分配”allocating将数据推入栈中并不被认为是分配。因为指向放入堆中数据的指针是已知的并且大小是固定的你可以将该指针存储在栈上不过当需要实际数据时必须访问指针。想象一下去餐馆就座吃饭。当进入时你说明有几个人餐馆员工会找到一个够大的空桌子并领你们过去。如果有人来迟了他们也可以通过询问来找到你们坐在哪。</p>
<p>入栈比在堆上分配内存要快,因为(入栈时)分配器无需为存储新数据去搜索内存空间;其位置总是在栈顶。相比之下,在堆上分配内存则需要更多的工作,这是因为分配器必须首先找到一块足够存放数据的内存空间,并接着做一些记录为下一次分配做准备。</p>
<p>访问堆上的数据比访问栈上的数据慢,因为必须通过指针来访问。现代处理器在内存中跳转越少就越快(缓存)。继续类比,假设有一个服务员在餐厅里处理多个桌子的点菜。在一个桌子报完所有菜后再移动到下一个桌子是最有效率的。从桌子 A 听一个菜,接着桌子 B 听一个菜,然后再桌子 A然后再桌子 B 这样的流程会更加缓慢。出于同样原因,处理器在处理的数据彼此较近的时候(比如在栈上)比较远的时候(比如可能在堆上)能更好的工作。</p>
<p>当你的代码调用一个函数时,传递给函数的值(包括可能指向堆上数据的指针)和函数的局部变量被压入栈中。当函数结束时,这些值被移出栈。</p>
<p>跟踪哪部分代码正在使用堆上的哪些数据,最大限度的减少堆上的重复数据的数量,以及清理堆上不再使用的数据确保不会耗尽空间,这些问题正是所有权系统要处理的。一旦理解了所有权,你就不需要经常考虑栈和堆了,不过明白了所有权的主要目的就是管理堆数据,能够帮助解释为什么所有权要以这种方式工作。</p>
</blockquote>
<h3 id="所有权规则"><a class="header" href="#所有权规则">所有权规则</a></h3>
<p>首先,让我们看一下所有权的规则。当我们通过举例说明时,请谨记这些规则:</p>
<blockquote>
<ol>
<li>Rust 中的每一个值都有一个 <strong>所有者</strong><em>owner</em>)。</li>
<li>值在任一时刻有且只有一个所有者。</li>
<li>当所有者(变量)离开作用域,这个值将被丢弃。</li>
</ol>
</blockquote>
<h3 id="变量作用域"><a class="header" href="#变量作用域">变量作用域</a></h3>
<p>既然我们已经掌握了基本语法,将不会在之后的例子中包含 <code>fn main() {</code> 代码,所以如果你是一路跟过来的,必须手动将之后例子的代码放入一个 <code>main</code> 函数中。这样,例子将显得更加简明,使我们可以关注实际细节而不是样板代码。</p>
<p>在所有权的第一个例子中,我们看看一些变量的 <strong>作用域</strong><em>scope</em>。作用域是一个项item在程序中有效的范围。假设有这样一个变量</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = "hello";
<span class="boring">}</span></code></pre></pre>
<p>变量 <code>s</code> 绑定到了一个字符串字面值,这个字符串值是硬编码进程序代码中的。这个变量从声明的点开始直到当前 <strong>作用域</strong> 结束时都是有效的。示例 4-1 中的注释标明了变量 <code>s</code> 在何处是有效的。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> { // s 在这里无效,它尚未声明
let s = "hello"; // 从此处起s 是有效的
// 使用 s
} // 此作用域已结束s 不再有效
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 4-1一个变量和其有效的作用域</span></p>
<p>换句话说,这里有两个重要的时间点:</p>
<ul>
<li><code>s</code> <strong>进入作用域</strong> 时,它就是有效的。</li>
<li>这一直持续到它 <strong>离开作用域</strong> 为止。</li>
</ul>
<p>目前为止,变量是否有效与作用域的关系跟其他编程语言是类似的。现在我们在此基础上介绍 <code>String</code> 类型。</p>
<h3 id="string-类型"><a class="header" href="#string-类型"><code>String</code> 类型</a></h3>
<p>为了演示所有权的规则,我们需要一个比第三章 <a href="ch03-02-data-types.html#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">“数据类型”</a> 中讲到的都要复杂的数据类型。前面介绍的类型都是已知大小的,可以存储在栈中,并且当离开作用域时被移出栈,如果代码的另一部分需要在不同的作用域中使用相同的值,可以快速简单地复制它们来创建一个新的独立实例。不过我们需要寻找一个存储在堆上的数据来探索 Rust 是如何知道该在何时清理数据的。</p>
<p>我们会专注于 <code>String</code> 与所有权相关的部分。这些方面也同样适用于标准库提供的或你自己创建的其他复杂数据类型。在<a href="ch08-02-strings.html">第八章</a>会更深入地讲解 <code>String</code></p>
<p>我们已经见过字符串字面值即被硬编码进程序里的字符串值。字符串字面值是很方便的不过它们并不适合使用文本的每一种场景。原因之一就是它们是不可变的。另一个原因是并非所有字符串的值都能在编写代码时就知道例如要是想获取用户输入并存储该怎么办呢为此Rust 有另一种字符串类型,<code>String</code>。这个类型管理被分配到堆上的数据,所以能够存储在编译时未知大小的文本。可以使用 <code>from</code> 函数基于字符串字面值来创建 <code>String</code>,如下:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = String::from("hello");
<span class="boring">}</span></code></pre></pre>
<p>这两个冒号 <code>::</code> 是运算符,允许将特定的 <code>from</code> 函数置于 <code>String</code> 类型的命名空间namespace而不需要使用类似 <code>string_from</code> 这样的名字。在第五章的 <a href="ch05-03-method-syntax.html#%E6%96%B9%E6%B3%95%E8%AF%AD%E6%B3%95">“方法语法”“Method Syntax”</a> 部分会着重讲解这个语法,而且在第七章的 <a href="ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html">“路径用于引用模块树中的项”</a> 中会讲到模块的命名空间。</p>
<p><strong>可以</strong> 修改此类字符串:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
s.push_str(", world!"); // push_str() 在字符串后追加字面值
println!("{s}"); // 将打印 `hello, world!`
<span class="boring">}</span></code></pre></pre>
<p>那么这里有什么区别呢?为什么 <code>String</code> 可变而字面值却不行呢?区别在于两个类型对内存的处理上。</p>
<h3 id="内存与分配"><a class="header" href="#内存与分配">内存与分配</a></h3>
<p>就字符串字面值来说,我们在编译时就知道其内容,所以文本被直接硬编码进最终的可执行文件中。这使得字符串字面值快速且高效。不过这些特性都只得益于字符串字面值的不可变性。不幸的是,我们不能为了每一个在编译时大小未知的文本而将一块内存放入二进制文件中,并且它的大小还可能随着程序运行而改变。</p>
<p>对于 <code>String</code> 类型,为了支持一个可变,可增长的文本片段,需要在堆上分配一块在编译时未知大小的内存来存放内容。这意味着:</p>
<ul>
<li>必须在运行时向内存分配器memory allocator请求内存。</li>
<li>需要一个当我们处理完 <code>String</code> 时将内存返回给分配器的方法。</li>
</ul>
<p>第一部分由我们完成:当调用 <code>String::from</code> 时,它的实现 (<em>implementation</em>) 请求其所需的内存。这在编程语言中是非常通用的。</p>
<p>然而,第二部分实现起来就各有区别了。在有 <strong>垃圾回收</strong><em>garbage collector</em><em>GC</em>的语言中GC 记录并清除不再使用的内存,而我们并不需要关心它。在大部分没有 GC 的语言中,识别出不再使用的内存并调用代码显式释放就是我们的责任了,跟请求内存的时候一样。从历史的角度上说正确处理内存回收曾经是一个困难的编程问题。如果忘记回收了会浪费内存。如果过早回收了,将会出现无效变量。如果重复回收,这也是个 bug。我们需要精确的为一个 <code>allocate</code> 配对一个 <code>free</code></p>
<p>Rust 采取了一个不同的策略:内存在拥有它的变量离开作用域后就被自动释放。下面是示例 4-1 中作用域例子的一个使用 <code>String</code> 而不是字符串字面值的版本:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> {
let s = String::from("hello"); // 从此处起s 是有效的
// 使用 s
} // 此作用域已结束,
// s 不再有效
<span class="boring">}</span></code></pre></pre>
<p>这是一个将 <code>String</code> 需要的内存返回给分配器的很自然的位置:当 <code>s</code> 离开作用域的时候。当变量离开作用域Rust 为我们调用一个特殊的函数。这个函数叫做 <a href="https://doc.rust-lang.org/std/ops/trait.Drop.html#tymethod.drop"><code>drop</code></a>,在这里 <code>String</code> 的作者可以放置释放内存的代码。Rust 在结尾的 <code>}</code> 处自动调用 <code>drop</code></p>
<blockquote>
<p>注意:在 C++ 中,这种 item 在生命周期结束时释放资源的模式有时被称作 <strong>资源获取即初始化</strong><em>Resource Acquisition Is Initialization (RAII)</em>)。如果你使用过 RAII 模式的话应该对 Rust 的 <code>drop</code> 函数并不陌生。</p>
</blockquote>
<p>这个模式对编写 Rust 代码的方式有着深远的影响。现在它看起来很简单,不过在更复杂的场景下代码的行为可能是不可预测的,比如当有多个变量使用在堆上分配的内存时。现在让我们探索一些这样的场景。</p>
<p><a id="ways-variables-and-data-interact-move"></a></p>
<h4 id="变量与数据交互的方式一移动"><a class="header" href="#变量与数据交互的方式一移动">变量与数据交互的方式(一):移动</a></h4>
<p>在 Rust 中,多个变量可以采取不同的方式与同一数据进行交互。让我们看看示例 4-2 中一个使用整型的例子。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let x = 5;
let y = x;
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 4-2将变量 <code>x</code> 的整数值赋给 <code>y</code></span></p>
<p>我们大致可以猜到这在干什么:“将 <code>5</code> 绑定到 <code>x</code>;接着生成一个值 <code>x</code> 的拷贝并绑定到 <code>y</code>”。现在有了两个变量,<code>x</code><code>y</code>,都等于 <code>5</code>。这也正是事实上发生了的,因为整数是有已知固定大小的简单值,所以这两个 <code>5</code> 被放入了栈中。</p>
<p>现在看看这个 <code>String</code> 版本:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let s2 = s1;
<span class="boring">}</span></code></pre></pre>
<p>这看起来与上面的代码非常类似,所以我们可能会假设它们的运行方式也是类似的:也就是说,第二行可能会生成一个 <code>s1</code> 的拷贝并绑定到 <code>s2</code> 上。不过,事实上并不完全是这样。</p>
<p>看看图 4-1 以了解 <code>String</code> 的底层会发生什么。<code>String</code> 由三部分组成,如图左侧所示:一个指向存放字符串内容内存的指针,一个长度,和一个容量。这一组数据存储在栈上。右侧则是堆上存放内容的内存部分。</p>
<p><img alt="Two tables: the first table contains the representation of s1 on the
stack, consisting of its length (5), capacity (5), and a pointer to the first
value in the second table. The second table contains the representation of the
string data on the heap, byte by byte." src="img/trpl04-01.svg" class="center"
style="width: 50%;" /></p>
<p><span class="caption">图 4-1将值 <code>"hello"</code> 绑定给 <code>s1</code><code>String</code> 在内存中的表现形式</span></p>
<p>长度表示 <code>String</code> 的内容当前使用了多少字节的内存。容量是 <code>String</code> 从分配器总共获取了多少字节的内存。长度与容量的区别是很重要的,不过在当前上下文中并不重要,所以现在可以忽略容量。</p>
<p>当我们将 <code>s1</code> 赋值给 <code>s2</code><code>String</code> 的数据被复制了,这意味着我们从栈上拷贝了它的指针、长度和容量。我们并没有复制指针指向的堆上数据。换句话说,内存中数据的表现如图 4-2 所示。</p>
<p><img alt="Three tables: tables s1 and s2 representing those strings on the
stack, respectively, and both pointing to the same string data on the heap."
src="img/trpl04-02.svg" class="center" style="width: 50%;" /></p>
<p><span class="caption">图 4-2变量 <code>s2</code> 的内存表现,它有一份 <code>s1</code> 指针、长度和容量的拷贝</span></p>
<p>这个表现形式看起来 <strong>并不像</strong> 图 4-3 中的那样,如果 Rust 也拷贝了堆上的数据,那么内存看起来就是这样的。如果 Rust 这么做了,那么操作 <code>s2 = s1</code> 在堆上数据比较大的时候会对运行时性能造成非常大的影响。</p>
<p><img alt="Four tables: two tables representing the stack data for s1 and s2,
and each points to its own copy of string data on the heap."
src="img/trpl04-03.svg" class="center" style="width: 50%;" /></p>
<p><span class="caption">图 4-3另一个 <code>s2 = s1</code> 时可能的内存表现,如果 Rust 同时也拷贝了堆上的数据的话</span></p>
<p>之前我们提到过当变量离开作用域后Rust 自动调用 <code>drop</code> 函数并清理变量的堆内存。不过图 4-2 展示了两个数据指针指向了同一位置。这就有了一个问题:当 <code>s2</code><code>s1</code> 离开作用域,它们都会尝试释放相同的内存。这是一个叫做 <strong>二次释放</strong><em>double free</em>)的错误,也是之前提到过的内存安全性 bug 之一。两次释放(相同)内存会导致内存污染,它可能会导致潜在的安全漏洞。</p>
<p>为了确保内存安全,在 <code>let s2 = s1;</code> 之后Rust 认为 <code>s1</code> 不再有效,因此 Rust 不需要在 <code>s1</code> 离开作用域后清理任何东西。看看在 <code>s2</code> 被创建之后尝试使用 <code>s1</code> 会发生什么;这段代码不能运行:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let s2 = s1;
println!("{s1}, world!");
<span class="boring">}</span></code></pre>
<p>你会得到一个类似如下的错误,因为 Rust 禁止你使用无效的引用。</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0382]: borrow of moved value: `s1`
--&gt; src/main.rs:5:15
|
2 | let s1 = String::from("hello");
| -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 | let s2 = s1;
| -- value moved here
4 |
5 | println!("{s1}, world!");
| ^^^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
|
3 | let s2 = s1.clone();
| ++++++++
For more information about this error, try `rustc --explain E0382`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>如果你在其他语言中听说过术语 <strong>浅拷贝</strong><em>shallow copy</em>)和 <strong>深拷贝</strong><em>deep copy</em>),那么拷贝指针、长度和容量而不拷贝数据可能听起来像浅拷贝。不过因为 Rust 同时使第一个变量无效了,这个操作被称为 <strong>移动</strong><em>move</em>),而不是叫做浅拷贝。上面的例子可以解读为 <code>s1</code><strong>移动</strong> 到了 <code>s2</code> 中。那么具体发生了什么,如图 4-4 所示。</p>
<p><img alt="Three tables: tables s1 and s2 representing those strings on the
stack, respectively, and both pointing to the same string data on the heap.
Table s1 is grayed out be-cause s1 is no longer valid; only s2 can be used to
access the heap data." src="img/trpl04-04.svg" class="center" style="width:
50%;" /></p>
<p><span class="caption">图 4-4<code>s1</code> 无效之后的内存表现</span></p>
<p>这样就解决了我们的问题!因为只有 <code>s2</code> 是有效的,当其离开作用域,它就释放自己的内存,完毕。</p>
<p>另外这里还隐含了一个设计选择Rust 永远也不会自动创建数据的 “深拷贝”。因此,任何 <strong>自动</strong> 的复制都可以被认为是对运行时性能影响较小的。</p>
<p><a id="ways-variables-and-data-interact-clone"></a></p>
<h4 id="变量与数据交互的方式二克隆"><a class="header" href="#变量与数据交互的方式二克隆">变量与数据交互的方式(二):克隆</a></h4>
<p>如果我们 <strong>确实</strong> 需要深度复制 <code>String</code> 中堆上的数据,而不仅仅是栈上的数据,可以使用一个叫做 <code>clone</code> 的通用函数。第五章会讨论方法语法,不过因为方法在很多语言中是一个常见功能,所以之前你可能已经见过了。</p>
<p>这是一个实际使用 <code>clone</code> 方法的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {s1}, s2 = {s2}");
<span class="boring">}</span></code></pre></pre>
<p>这段代码能正常运行,并且明确产生图 4-3 中行为,这里堆上的数据 <strong>确实</strong> 被复制了。</p>
<p>当出现 <code>clone</code> 调用时,你知道一些特定的代码被执行而且这些代码可能相当消耗资源。你很容易察觉到一些不寻常的事情正在发生。</p>
<h4 id="只在栈上的数据拷贝"><a class="header" href="#只在栈上的数据拷贝">只在栈上的数据:拷贝</a></h4>
<p>这里还有一个没有提到的小窍门。这些代码使用了整型并且是有效的,它们是示例 4-2 中的一部分:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let x = 5;
let y = x;
println!("x = {x}, y = {y}");
<span class="boring">}</span></code></pre></pre>
<p>但这段代码似乎与我们刚刚学到的内容相矛盾:没有调用 <code>clone</code>,不过 <code>x</code> 依然有效且没有被移动到 <code>y</code> 中。</p>
<p>原因是像整型这样的在编译时已知大小的类型被整个存储在栈上,所以拷贝其实际的值是快速的。这意味着没有理由在创建变量 <code>y</code> 后使 <code>x</code> 无效。换句话说,这里没有深浅拷贝的区别,所以这里调用 <code>clone</code> 并不会与通常的浅拷贝有什么不同,我们可以不用管它。</p>
<p>Rust 有一个叫做 <code>Copy</code> trait 的特殊注解,可以用在类似整型这样的存储在栈上的类型上(<a href="ch10-00-generics.html">第十章</a>将会详细讲解 trait。如果一个类型实现了 <code>Copy</code> trait那么一个旧的变量在将其赋值给其他变量后仍然可用。</p>
<p>Rust 不允许自身或其任何部分实现了 <code>Drop</code> trait 的类型使用 <code>Copy</code> trait。如果我们对其值离开作用域时需要特殊处理的类型使用 <code>Copy</code> 注解,将会出现一个编译时错误。要学习如何为你的类型添加 <code>Copy</code> 注解以实现该 trait请阅读附录 C 中的 <a href="appendix-03-derivable-traits.html">“可派生的 trait”</a></p>
<p>那么哪些类型实现了 <code>Copy</code> trait 呢?你可以查看给定类型的文档来确认,不过作为一个通用的规则,任何一组简单标量值的组合都可以实现 <code>Copy</code>,任何不需要分配内存或某种形式资源的类型都可以实现 <code>Copy</code> 。如下是一些 <code>Copy</code> 的类型:</p>
<ul>
<li>所有整数类型,比如 <code>u32</code></li>
<li>布尔类型,<code>bool</code>,它的值是 <code>true</code><code>false</code></li>
<li>所有浮点数类型,比如 <code>f64</code></li>
<li>字符类型,<code>char</code></li>
<li>元组,当且仅当其包含的类型也都实现 <code>Copy</code> 的时候。比如,<code>(i32, i32)</code> 实现了 <code>Copy</code>,但 <code>(i32, String)</code> 就没有。</li>
</ul>
<h3 id="所有权与函数"><a class="header" href="#所有权与函数">所有权与函数</a></h3>
<p>将值传递给函数与给变量赋值的原理相似。向函数传递值可能会移动或者复制,就像赋值语句一样。示例 4-3 使用注释展示变量何时进入和离开作用域:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let s = String::from("hello"); // s 进入作用域
takes_ownership(s); // s 的值移动到函数里 ...
// ... 所以到这里不再有效
let x = 5; // x 进入作用域
makes_copy(x); // x 应该移动函数里,
// 但 i32 是 Copy 的,
// 所以在后面可继续使用 x
} // 这里x 先移出了作用域,然后是 s。但因为 s 的值已被移走,
// 没有特殊之处
fn takes_ownership(some_string: String) { // some_string 进入作用域
println!("{some_string}");
} // 这里some_string 移出作用域并调用 `drop` 方法。
// 占用的内存被释放
fn makes_copy(some_integer: i32) { // some_integer 进入作用域
println!("{some_integer}");
} // 这里some_integer 移出作用域。没有特殊之处</code></pre></pre>
<p><span class="caption">示例 4-3带有所有权和作用域注释的函数</span></p>
<p>当尝试在调用 <code>takes_ownership</code> 后使用 <code>s</code>Rust 会抛出一个编译时错误。这些静态检查使我们免于犯错。试试在 <code>main</code> 函数中添加使用 <code>s</code><code>x</code> 的代码来看看哪里能使用它们,以及所有权规则会在哪里阻止我们这么做。</p>
<h3 id="返回值与作用域"><a class="header" href="#返回值与作用域">返回值与作用域</a></h3>
<p>返回值也可以转移所有权。示例 4-4 展示了一个返回了某些值的示例,与示例 4-3 一样带有类似的注释。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let s1 = gives_ownership(); // gives_ownership 将返回值
// 转移给 s1
let s2 = String::from("hello"); // s2 进入作用域
let s3 = takes_and_gives_back(s2); // s2 被移动到
// takes_and_gives_back 中,
// 它也将返回值移给 s3
} // 这里s3 移出作用域并被丢弃。s2 也移出作用域,但已被移走,
// 所以什么也不会发生。s1 离开作用域并被丢弃
fn gives_ownership() -&gt; String { // gives_ownership 会将
// 返回值移动给
// 调用它的函数
let some_string = String::from("yours"); // some_string 进入作用域。
some_string // 返回 some_string
// 并移出给调用的函数
//
}
// takes_and_gives_back 将传入字符串并返回该值
fn takes_and_gives_back(a_string: String) -&gt; String { // a_string 进入作用域
//
a_string // 返回 a_string 并移出给调用的函数
}</code></pre></pre>
<p><span class="caption">示例 4-4: 转移返回值的所有权</span></p>
<p>变量的所有权总是遵循相同的模式:将值赋给另一个变量时移动它。当持有堆中数据值的变量离开作用域时,其值将通过 <code>drop</code> 被清理掉,除非数据被移动为另一个变量所有。</p>
<p>虽然这样是可以的,但是在每一个函数中都获取所有权并接着返回所有权有些啰嗦。如果我们想要函数使用一个值但不获取所有权该怎么办呢?如果我们还要接着使用它的话,每次都传进去再返回来就有点烦人了,除此之外,我们也可能想返回函数体中产生的一些数据。</p>
<p>我们可以使用元组来返回多个值,如示例 4-5 所示。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{s2}' is {len}.");
}
fn calculate_length(s: String) -&gt; (String, usize) {
let length = s.len(); // len() 返回字符串的长度
(s, length)
}</code></pre></pre>
<p><span class="caption">示例 4-5: 返回参数的所有权</span></p>
<p>但是这未免有些形式主义而且这种场景应该很常见。幸运的是Rust 对此提供了一个不用获取所有权就可以使用值的功能,叫做 <strong>引用</strong><em>references</em>)。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="引用与借用"><a class="header" href="#引用与借用">引用与借用</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch04-02-references-and-borrowing.md">ch04-02-references-and-borrowing.md</a>
<br>
commit 3d51f70c78162faaebcab0da0de2ddd333e7a8ed</p>
</blockquote>
<p>示例 4-5 中的元组代码有这样一个问题:我们必须将 <code>String</code> 返回给调用函数,以便在调用 <code>calculate_length</code> 后仍能使用 <code>String</code>,因为 <code>String</code> 被移动到了 <code>calculate_length</code> 内。相反我们可以提供一个 <code>String</code> 值的引用reference<strong>引用</strong><em>reference</em>)像一个指针,因为它是一个地址,我们可以由此访问储存于该地址的属于其他变量的数据。
与指针不同,引用确保指向某个特定类型的有效值。</p>
<p>下面是如何定义并使用一个(新的)<code>calculate_length</code> 函数,它以一个对象的引用作为参数而不是获取值的所有权:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let s1 = String::from("hello");
let len = calculate_length(&amp;s1);
println!("The length of '{s1}' is {len}.");
}
fn calculate_length(s: &amp;String) -&gt; usize {
s.len()
}</code></pre></pre>
<p>首先,注意变量声明和函数返回值中的所有元组代码都消失了。其次,注意我们传递 <code>&amp;s1</code><code>calculate_length</code>,同时在函数定义中,我们获取 <code>&amp;String</code> 而不是 <code>String</code>。这些 &amp; 符号就是 <strong>引用</strong>,它们允许你使用值但不获取其所有权。图 4-5 展示了一张示意图。</p>
<p><img alt="Three tables: the table for s contains only a pointer to the table
for s1. The table for s1 contains the stack data for s1 and points to the
string data on the heap." src="img/trpl04-05.svg" class="center" /></p>
<p><span class="caption">图 4-5<code>&amp;String s</code> 指向 <code>String s1</code> 示意图</span></p>
<blockquote>
<p>注意:与使用 <code>&amp;</code> 引用相反的操作是 <strong>解引用</strong><em>dereferencing</em>),它使用解引用运算符,<code>*</code>。我们将会在第八章遇到一些解引用运算符,并在第十五章详细讨论解引用。</p>
</blockquote>
<p>仔细看看这个函数调用:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let len = calculate_length(&amp;s1);
<span class="boring">
</span><span class="boring"> println!("The length of '{s1}' is {len}.");
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn calculate_length(s: &amp;String) -&gt; usize {
</span><span class="boring"> s.len()
</span><span class="boring">}</span></code></pre></pre>
<p><code>&amp;s1</code> 语法让我们创建一个 <strong>指向</strong><code>s1</code> 的引用,但是并不拥有它。因为并不拥有这个值,所以当引用停止使用时,它所指向的值也不会被丢弃。</p>
<p>同理,函数签名使用 <code>&amp;</code> 来表明参数 <code>s</code> 的类型是一个引用。让我们增加一些解释性的注释:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> let s1 = String::from("hello");
</span><span class="boring">
</span><span class="boring"> let len = calculate_length(&amp;s1);
</span><span class="boring">
</span><span class="boring"> println!("The length of '{s1}' is {len}.");
</span><span class="boring">}
</span><span class="boring">
</span>fn calculate_length(s: &amp;String) -&gt; usize { // s 是 String 的引用
s.len()
} // 这里s 离开了作用域。但因为它并不拥有引用值的所有权,
// 所以什么也不会发生</code></pre></pre>
<p>变量 <code>s</code> 有效的作用域与函数参数的作用域一样,不过当 <code>s</code> 停止使用时并不丢弃引用指向的数据,因为 <code>s</code> 并没有所有权。当函数使用引用而不是实际值作为参数,无需返回值来交还所有权,因为就不曾拥有所有权。</p>
<p>我们将创建一个引用的行为称为 <strong>借用</strong><em>borrowing</em>)。正如现实生活中,如果一个人拥有某样东西,你可以从他那里借来。当你使用完毕,必须还回去。我们并不拥有它。</p>
<p>如果我们尝试修改借用的变量呢?尝试示例 4-6 中的代码。剧透:这行不通!</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let s = String::from("hello");
change(&amp;s);
}
fn change(some_string: &amp;String) {
some_string.push_str(", world");
}</code></pre>
<p><span class="caption">示例 4-6尝试修改借用的值</span></p>
<p>这里是错误:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&amp;` reference
--&gt; src/main.rs:8:5
|
8 | some_string.push_str(", world");
| ^^^^^^^^^^^ `some_string` is a `&amp;` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference
|
7 | fn change(some_string: &amp;mut String) {
| +++
For more information about this error, try `rustc --explain E0596`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>正如变量默认是不可变的,引用也一样。(默认)不允许修改引用的值。</p>
<h3 id="可变引用"><a class="header" href="#可变引用">可变引用</a></h3>
<p>我们通过一个小调整就能修复示例 4-6 代码中的错误,允许我们修改一个借用的值,这就是 <strong>可变引用</strong><em>mutable reference</em></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let mut s = String::from("hello");
change(&amp;mut s);
}
fn change(some_string: &amp;mut String) {
some_string.push_str(", world");
}</code></pre></pre>
<p>首先,我们必须将 <code>s</code> 改为 <code>mut</code>。然后在调用 <code>change</code> 函数的地方创建一个可变引用 <code>&amp;mut s</code>,并更新函数签名以接受一个可变引用 <code>some_string: &amp;mut String</code>。这就非常清楚地表明,<code>change</code> 函数将改变它所借用的值。</p>
<p>可变引用有一个很大的限制:如果你有一个对该变量的可变引用,你就不能再创建对该变量的引用。这些尝试创建两个 <code>s</code> 的可变引用的代码会失败:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
let r1 = &amp;mut s;
let r2 = &amp;mut s;
println!("{}, {}", r1, r2);
<span class="boring">}</span></code></pre>
<p>错误如下:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0499]: cannot borrow `s` as mutable more than once at a time
--&gt; src/main.rs:5:14
|
4 | let r1 = &amp;mut s;
| ------ first mutable borrow occurs here
5 | let r2 = &amp;mut s;
| ^^^^^^ second mutable borrow occurs here
6 |
7 | println!("{}, {}", r1, r2);
| -- first borrow later used here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>这个报错说这段代码是无效的,因为我们不能在同一时间多次将 <code>s</code> 作为可变变量借用。第一个可变的借入在 <code>r1</code> 中,并且必须持续到在 <code>println!</code> 中使用它,但是在那个可变引用的创建和它的使用之间,我们又尝试在 <code>r2</code> 中创建另一个可变引用,该引用借用与 <code>r1</code> 相同的数据。</p>
<p>这一限制以一种非常小心谨慎的方式允许可变性,防止同一时间对同一数据存在多个可变引用。新 Rustacean 们经常难以适应这一点,因为大部分语言中变量任何时候都是可变的。这个限制的好处是 Rust 可以在编译时就避免数据竞争。<strong>数据竞争</strong><em>data race</em>)类似于竞态条件,它可由这三个行为造成:</p>
<ul>
<li>两个或更多指针同时访问同一数据。</li>
<li>至少有一个指针被用来写入数据。</li>
<li>没有同步数据访问的机制。</li>
</ul>
<p>数据竞争会导致未定义行为难以在运行时追踪并且难以诊断和修复Rust 避免了这种情况的发生,因为它甚至不会编译存在数据竞争的代码!</p>
<p>一如既往,可以使用大括号来创建一个新的作用域,以允许拥有多个可变引用,只是不能 <strong>同时</strong> 拥有:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
{
let r1 = &amp;mut s;
} // r1 在这里离开了作用域,所以我们完全可以创建一个新的引用
let r2 = &amp;mut s;
<span class="boring">}</span></code></pre></pre>
<p>Rust 在同时使用可变与不可变引用时也采用的类似的规则。这些代码会导致一个错误:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
let r1 = &amp;s; // 没问题
let r2 = &amp;s; // 没问题
let r3 = &amp;mut s; // 大问题
println!("{}, {}, and {}", r1, r2, r3);
<span class="boring">}</span></code></pre>
<p>错误如下:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--&gt; src/main.rs:6:14
|
4 | let r1 = &amp;s; // no problem
| -- immutable borrow occurs here
5 | let r2 = &amp;s; // no problem
6 | let r3 = &amp;mut s; // BIG PROBLEM
| ^^^^^^ mutable borrow occurs here
7 |
8 | println!("{}, {}, and {}", r1, r2, r3);
| -- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>哇哦!我们 <strong></strong> 不能在拥有不可变引用的同时拥有可变引用。</p>
<p>不可变引用的用户可不希望在他们的眼皮底下值就被意外的改变了!然而,多个不可变引用是可以的,因为没有哪个只能读取数据的人有能力影响其他人读取到的数据。</p>
<p>注意一个引用的作用域从声明的地方开始一直持续到最后一次使用为止。例如,因为最后一次使用不可变引用(<code>println!</code>),发生在声明可变引用之前,所以如下代码是可以编译的:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
let r1 = &amp;s; // 没问题
let r2 = &amp;s; // 没问题
println!("{r1} and {r2}");
// 此位置之后 r1 和 r2 不再使用
let r3 = &amp;mut s; // 没问题
println!("{r3}");
<span class="boring">}</span></code></pre></pre>
<p>不可变引用 <code>r1</code><code>r2</code> 的作用域在 <code>println!</code> 最后一次使用之后结束,这也是创建可变引用 <code>r3</code> 的地方。它们的作用域没有重叠,所以代码是可以编译的。编译器可以在作用域结束之前判断不再使用的引用。</p>
<p>尽管这些错误有时使人沮丧,但请牢记这是 Rust 编译器在提前指出一个潜在的 bug在编译时而不是在运行时并精准显示问题所在。这样你就不必去跟踪为何数据并不是你想象中的那样。</p>
<h3 id="悬垂引用dangling-references"><a class="header" href="#悬垂引用dangling-references">悬垂引用Dangling References</a></h3>
<p>在具有指针的语言中,很容易通过释放内存时保留指向它的指针而错误地生成一个 <strong>悬垂指针</strong><em>dangling pointer</em>),所谓悬垂指针是其指向的内存可能已经被分配给其它持有者。相比之下,在 Rust 中编译器确保引用永远也不会变成悬垂状态:当你拥有一些数据的引用,编译器确保数据不会在其引用之前离开作用域。</p>
<p>让我们尝试创建一个悬垂引用Rust 会通过一个编译时错误来避免:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -&gt; &amp;String {
let s = String::from("hello");
&amp;s
}</code></pre>
<p>这里是错误:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0106]: missing lifetime specifier
--&gt; src/main.rs:5:16
|
5 | fn dangle() -&gt; &amp;String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
5 | fn dangle() -&gt; &amp;'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
5 - fn dangle() -&gt; &amp;String {
5 + fn dangle() -&gt; String {
|
error[E0515]: cannot return reference to local variable `s`
--&gt; src/main.rs:8:5
|
8 | &amp;s
| ^^ returns a reference to data owned by the current function
Some errors have detailed explanations: E0106, E0515.
For more information about an error, try `rustc --explain E0106`.
error: could not compile `ownership` (bin "ownership") due to 2 previous errors
</code></pre>
<p>错误信息引用了一个我们还未介绍的功能生命周期lifetimes。第十章会详细介绍生命周期。不过如果你不理会生命周期部分错误信息中确实包含了为什么这段代码有问题的关键信息</p>
<pre><code class="language-text">this function's return type contains a borrowed value, but there is no value
for it to be borrowed from
</code></pre>
<p>让我们仔细看看我们的 <code>dangle</code> 代码的每一步到底发生了什么:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span><span class="boring"> let reference_to_nothing = dangle();
</span><span class="boring">}
</span><span class="boring">
</span>fn dangle() -&gt; &amp;String { // dangle 返回一个字符串的引用
let s = String::from("hello"); // s 是一个新字符串
&amp;s // 返回字符串 s 的引用
} // 这里 s 离开作用域并被丢弃。其内存被释放。
// 危险!</code></pre>
<p>因为 <code>s</code> 是在 <code>dangle</code> 函数内创建的,当 <code>dangle</code> 的代码执行完毕后,<code>s</code> 将被释放。不过我们尝试返回它的引用。这意味着这个引用会指向一个无效的 <code>String</code>这可不对Rust 不会允许我们这么做。</p>
<p>这里的解决方法是直接返回 <code>String</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> let string = no_dangle();
</span><span class="boring">}
</span><span class="boring">
</span>fn no_dangle() -&gt; String {
let s = String::from("hello");
s
}</code></pre></pre>
<p>这样就没有任何错误了。所有权被移动出去,所以没有值被释放。</p>
<h3 id="引用的规则"><a class="header" href="#引用的规则">引用的规则</a></h3>
<p>让我们概括一下之前对引用的讨论:</p>
<ul>
<li>在任意给定时间,<strong>要么</strong> 只能有一个可变引用,<strong>要么</strong> 只能有多个不可变引用。</li>
<li>引用必须总是有效的。</li>
</ul>
<p>接下来我们来看看另一种不同类型的引用slice。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="slice-类型"><a class="header" href="#slice-类型">Slice 类型</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch04-03-slices.md">ch04-03-slices.md</a>
<br>
commit 3d51f70c78162faaebcab0da0de2ddd333e7a8ed</p>
</blockquote>
<p><em>slice</em> 允许你引用集合中一段连续的元素序列而不用引用整个集合。slice 是一种引用,所以它没有所有权。</p>
<p>这里有一个编程小习题:编写一个函数,该函数接收一个用空格分隔单词的字符串,并返回在该字符串中找到的第一个单词。如果函数在该字符串中并未找到空格,则整个字符串就是一个单词,所以应该返回整个字符串。</p>
<p>让我们推敲下如何不用 slice 编写这个函数的签名,来理解 slice 能解决的问题:</p>
<pre><code class="language-rust ignore">fn first_word(s: &amp;String) -&gt; ?</code></pre>
<p><code>first_word</code> 函数有一个参数 <code>&amp;String</code>。因为我们不需要所有权,所以这没有问题。不过应该返回什么呢?我们并没有一个真正获取 <strong>部分</strong> 字符串的办法。不过,我们可以返回单词结尾的索引,结尾由一个空格表示。试试如示例 4-7 中的代码。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn first_word(s: &amp;String) -&gt; usize {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 4-7<code>first_word</code> 函数返回 <code>String</code> 参数的一个字节索引值</span></p>
<p>因为需要逐个元素的检查 <code>String</code> 中的值是否为空格,需要用 <code>as_bytes</code> 方法将 <code>String</code> 转化为字节数组。</p>
<pre><code class="language-rust ignore"><span class="boring">fn first_word(s: &amp;String) -&gt; usize {
</span> let bytes = s.as_bytes();
<span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return i;
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> s.len()
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p>接下来,使用 <code>iter</code> 方法在字节数组上创建一个迭代器:</p>
<pre><code class="language-rust ignore"><span class="boring">fn first_word(s: &amp;String) -&gt; usize {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span> for (i, &amp;item) in bytes.iter().enumerate() {
<span class="boring"> if item == b' ' {
</span><span class="boring"> return i;
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> s.len()
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p>我们将在<a href="ch13-02-iterators.html">第十三章</a>详细讨论迭代器。现在,只需知道 <code>iter</code> 方法返回集合中的每一个元素,而 <code>enumerate</code> 包装了 <code>iter</code> 的结果,将这些元素作为元组的一部分来返回。<code>enumerate</code> 返回的元组中,第一个元素是索引,第二个元素是集合中元素的引用。这比我们自己计算索引要方便一些。</p>
<p>因为 <code>enumerate</code> 方法返回一个元组,我们可以使用模式来解构,我们将在<a href="ch06-02-match.html#%E7%BB%91%E5%AE%9A%E5%80%BC%E7%9A%84%E6%A8%A1%E5%BC%8F">第六章</a>中进一步讨论有关模式的问题。所以在 <code>for</code> 循环中,我们指定了一个模式,其中元组中的 <code>i</code> 是索引而元组中的 <code>&amp;item</code> 是单个字节。因为我们从 <code>.iter().enumerate()</code> 中获取了集合元素的引用,所以模式中使用了 <code>&amp;</code></p>
<p><code>for</code> 循环中,我们通过字节的字面值语法来寻找代表空格的字节。如果找到了一个空格,返回它的位置。否则,使用 <code>s.len()</code> 返回字符串的长度:</p>
<pre><code class="language-rust ignore"><span class="boring">fn first_word(s: &amp;String) -&gt; usize {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span> if item == b' ' {
return i;
}
}
s.len()
<span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p>现在有了一个找到字符串中第一个单词结尾索引的方法,不过这有一个问题。我们返回了一个独立的 <code>usize</code>,不过它只在 <code>&amp;String</code> 的上下文中才是一个有意义的数字。换句话说,因为它是一个与 <code>String</code> 相分离的值,无法保证将来它仍然有效。考虑一下示例 4-8 中使用了示例 4-7 中 <code>first_word</code> 函数的程序。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn first_word(s: &amp;String) -&gt; usize {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return i;
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> s.len()
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let mut s = String::from("hello world");
let word = first_word(&amp;s); // word 的值为 5
s.clear(); // 这清空了字符串,使其等于 ""
// word 在此处的值仍然是 5
// 但是没有更多的字符串让我们可以有效地应用数值 5。word 的值现在完全无效!
}</code></pre></pre>
<p><span class="caption">示例 4-8存储 <code>first_word</code> 函数调用的返回值并接着改变 <code>String</code> 的内容</span></p>
<p>这个程序编译时没有任何错误,而且在调用 <code>s.clear()</code> 之后使用 <code>word</code> 也不会出错。因为 <code>word</code><code>s</code> 状态完全没有联系,所以 <code>word </code> 仍然包含值 <code>5</code>。可以尝试用值 <code>5</code> 来提取变量 <code>s</code> 的第一个单词,不过这是有 bug 的,因为在我们将 <code>5</code> 保存到 <code>word</code> 之后 <code>s</code> 的内容已经改变。</p>
<p>我们不得不时刻担心 <code>word</code> 的索引与 <code>s</code> 中的数据不再同步,这很啰嗦且易出错!如果编写这么一个 <code>second_word</code> 函数的话,管理索引这件事将更加容易出问题。它的签名看起来像这样:</p>
<pre><code class="language-rust ignore">fn second_word(s: &amp;String) -&gt; (usize, usize) {</code></pre>
<p>现在我们要跟踪一个开始索引 <strong></strong> 一个结尾索引,同时有了更多从数据的某个特定状态计算而来的值,但都完全没有与这个状态相关联。现在有三个飘忽不定的不相关变量需要保持同步。</p>
<p>幸运的是Rust 为这个问题提供了一个解决方法:字符串 slice。</p>
<h3 id="字符串-slice"><a class="header" href="#字符串-slice">字符串 slice</a></h3>
<p><strong>字符串 slice</strong><em>string slice</em>)是 <code>String</code> 中一部分值的引用,它看起来像这样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s = String::from("hello world");
let hello = &amp;s[0..5];
let world = &amp;s[6..11];
<span class="boring">}</span></code></pre></pre>
<p>不同于整个 <code>String</code> 的引用,<code>hello</code> 是一个部分 <code>String</code> 的引用,由一个额外的 <code>[0..5]</code> 部分指定。可以使用一个由中括号中的 <code>[starting_index..ending_index]</code> 指定的 range 创建一个 slice其中 <code>starting_index</code> 是 slice 的第一个位置,<code>ending_index</code> 则是 slice 最后一个位置的后一个值。在其内部slice 的数据结构存储了 slice 的开始位置和长度,长度对应于 <code>ending_index</code> 减去 <code>starting_index</code> 的值。所以对于 <code>let world = &amp;s[6..11];</code> 的情况,<code>world</code> 将是一个包含指向 <code>s</code> 索引 6 的指针和长度值 5 的 slice。</p>
<p>图 4-7 展示了一个图例。</p>
<p><img alt="Three tables: a table representing the stack data of s, which points
to the byte at index 0 in a table of the string data &quot;hello world&quot; on
the heap. The third table rep-resents the stack data of the slice world, which
has a length value of 5 and points to byte 6 of the heap data table."
src="img/trpl04-07.svg" class="center" style="width: 50%;" /></p>
<p><span class="caption">图 4-7引用了部分 <code>String</code> 的字符串 slice</span></p>
<p>对于 Rust 的 <code>..</code> range 语法,如果想要从索引 0 开始,可以不写两个点号之前的值。换句话说,如下两个语句是相同的:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = String::from("hello");
let slice = &amp;s[0..2];
let slice = &amp;s[..2];
<span class="boring">}</span></code></pre></pre>
<p>依此类推,如果 slice 包含 <code>String</code> 的最后一个字节,也可以舍弃尾部的数字。这意味着如下也是相同的:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = String::from("hello");
let len = s.len();
let slice = &amp;s[3..len];
let slice = &amp;s[3..];
<span class="boring">}</span></code></pre></pre>
<p>也可以同时舍弃这两个值来获取整个字符串的 slice。所以如下亦是相同的</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = String::from("hello");
let len = s.len();
let slice = &amp;s[0..len];
let slice = &amp;s[..];
<span class="boring">}</span></code></pre></pre>
<blockquote>
<p>注意:字符串 slice range 的索引必须位于有效的 UTF-8 字符边界内,如果尝试从一个多字节字符的中间位置创建字符串 slice则程序将会因错误而退出。出于介绍字符串 slice 的目的,本部分假设只使用 ASCII 字符集;第八章的 <a href="ch08-02-strings.html#%E4%BD%BF%E7%94%A8%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%82%A8%E5%AD%98-utf-8-%E7%BC%96%E7%A0%81%E7%9A%84%E6%96%87%E6%9C%AC">“使用字符串储存 UTF-8 编码的文本”</a> 部分会更加全面的讨论 UTF-8 处理问题。</p>
</blockquote>
<p>在记住所有这些知识后,让我们重写 <code>first_word</code> 来返回一个 slice。“字符串 slice” 的类型声明写作 <code>&amp;str</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn first_word(s: &amp;String) -&gt; &amp;str {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return &amp;s[0..i];
}
}
&amp;s[..]
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p>我们使用跟示例 4-7 相同的方式获取单词结尾的索引,通过寻找第一个出现的空格。当找到一个空格,我们返回一个字符串 slice它使用字符串的开始和空格的索引作为开始和结束的索引。</p>
<p>现在当调用 <code>first_word</code> 时,会返回与底层数据关联的单个值。这个值由一个 slice 开始位置的引用和 slice 中元素的数量组成。</p>
<p><code>second_word</code> 函数也可以改为返回一个 slice</p>
<pre><code class="language-rust ignore">fn second_word(s: &amp;String) -&gt; &amp;str {</code></pre>
<p>现在我们有了一个不易混淆且直观的 API 了,因为编译器会确保指向 <code>String</code> 的引用持续有效。还记得示例 4-8 程序中,那个当我们获取第一个单词结尾的索引后,接着就清除了字符串导致索引就无效的 bug 吗那些代码在逻辑上是不正确的但却没有显示任何直接的错误。问题会在之后尝试对空字符串使用第一个单词的索引时出现。slice 就不可能出现这种 bug 并让我们更早的知道出问题了。使用 slice 版本的 <code>first_word</code> 会抛出一个编译时错误:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn first_word(s: &amp;String) -&gt; &amp;str {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return &amp;s[0..i];
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> &amp;s[..]
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let mut s = String::from("hello world");
let word = first_word(&amp;s);
s.clear(); // 错误!
println!("the first word is: {word}");
}</code></pre>
<p>这里是编译错误:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--&gt; src/main.rs:18:5
|
16 | let word = first_word(&amp;s);
| -- immutable borrow occurs here
17 |
18 | s.clear(); // error!
| ^^^^^^^^^ mutable borrow occurs here
19 |
20 | println!("the first word is: {word}");
| ------ immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>回忆一下借用规则,当拥有某值的不可变引用时,就不能再获取一个可变引用。因为 <code>clear</code> 需要清空 <code>String</code>,它尝试获取一个可变引用。在调用 <code>clear</code> 之后的 <code>println!</code> 使用了 <code>word</code> 中的引用所以这个不可变的引用在此时必须仍然有效。Rust 不允许 <code>clear</code> 中的可变引用和 <code>word</code> 中的不可变引用同时存在因此编译失败。Rust 不仅使得我们的 API 简单易用,也在编译时就消除了一整类的错误!</p>
<p><a id="string-literals-are-slices"></a></p>
<h4 id="字符串字面值就是-slice"><a class="header" href="#字符串字面值就是-slice">字符串字面值就是 slice</a></h4>
<p>还记得我们讲到过字符串字面值被储存在二进制文件中吗?现在知道 slice 了,我们就可以正确地理解字符串字面值了:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = "Hello, world!";
<span class="boring">}</span></code></pre></pre>
<p>这里 <code>s</code> 的类型是 <code>&amp;str</code>:它是一个指向二进制程序特定位置的 slice。这也就是为什么字符串字面值是不可变的<code>&amp;str</code> 是一个不可变引用。</p>
<h4 id="字符串-slice-作为参数"><a class="header" href="#字符串-slice-作为参数">字符串 slice 作为参数</a></h4>
<p>在知道了能够获取字面值和 <code>String</code> 的 slice 后,我们对 <code>first_word</code> 做了改进,这是它的签名:</p>
<pre><code class="language-rust ignore">fn first_word(s: &amp;String) -&gt; &amp;str {</code></pre>
<p>而更有经验的 Rustacean 会编写出示例 4-9 中的签名,因为它使得可以对 <code>&amp;String</code> 值和 <code>&amp;str</code> 值使用相同的函数:</p>
<pre><code class="language-rust ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
<span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return &amp;s[0..i];
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> &amp;s[..]
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let my_string = String::from("hello world");
</span><span class="boring">
</span><span class="boring"> // `first_word` 适用于 `String`(的 slice部分或全部
</span><span class="boring"> let word = first_word(&amp;my_string[0..6]);
</span><span class="boring"> let word = first_word(&amp;my_string[..]);
</span><span class="boring"> // `first_word` 也适用于 `String` 的引用,
</span><span class="boring"> // 这等价于整个 `String` 的 slice
</span><span class="boring"> let word = first_word(&amp;my_string);
</span><span class="boring">
</span><span class="boring"> let my_string_literal = "hello world";
</span><span class="boring">
</span><span class="boring"> // `first_word` 适用于字符串字面值,部分或全部
</span><span class="boring"> let word = first_word(&amp;my_string_literal[0..6]);
</span><span class="boring"> let word = first_word(&amp;my_string_literal[..]);
</span><span class="boring">
</span><span class="boring"> // 因为字符串字面值已经 **是** 字符串 slice 了,
</span><span class="boring"> // 这也是适用的,无需 slice 语法!
</span><span class="boring"> let word = first_word(my_string_literal);
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 4-9: 通过将 <code>s</code> 参数的类型改为字符串 slice 来改进 <code>first_word</code> 函数</span></p>
<p>如果有一个字符串 slice可以直接传递它。如果有一个 <code>String</code>,则可以传递整个 <code>String</code> 的 slice 或对 <code>String</code> 的引用。这种灵活性利用了 <em>deref coercions</em> 的优势,这个特性我们将在<a href="ch15-02-deref.html#%E5%87%BD%E6%95%B0%E5%92%8C%E6%96%B9%E6%B3%95%E7%9A%84%E9%9A%90%E5%BC%8F-deref-%E5%BC%BA%E5%88%B6%E8%BD%AC%E6%8D%A2">“函数和方法的隐式 Deref 强制转换”</a>章节中介绍。定义一个获取字符串 slice 而不是 <code>String</code> 引用的函数使得我们的 API 更加通用并且不会丢失任何功能:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn first_word(s: &amp;str) -&gt; &amp;str {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return &amp;s[0..i];
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> &amp;s[..]
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let my_string = String::from("hello world");
// `first_word` 适用于 `String`(的 slice部分或全部
let word = first_word(&amp;my_string[0..6]);
let word = first_word(&amp;my_string[..]);
// `first_word` 也适用于 `String` 的引用,
// 这等价于整个 `String` 的 slice
let word = first_word(&amp;my_string);
let my_string_literal = "hello world";
// `first_word` 适用于字符串字面值,部分或全部
let word = first_word(&amp;my_string_literal[0..6]);
let word = first_word(&amp;my_string_literal[..]);
// 因为字符串字面值已经 **是** 字符串 slice 了,
// 这也是适用的,无需 slice 语法!
let word = first_word(my_string_literal);
}</code></pre></pre>
<h3 id="其他类型的-slice"><a class="header" href="#其他类型的-slice">其他类型的 slice</a></h3>
<p>字符串 slice正如你想象的那样是针对字符串的。不过也有更通用的 slice 类型。考虑一下这个数组:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let a = [1, 2, 3, 4, 5];
<span class="boring">}</span></code></pre></pre>
<p>就跟我们想要获取字符串的一部分那样,我们也会想要引用数组的一部分。我们可以这样做:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let a = [1, 2, 3, 4, 5];
let slice = &amp;a[1..3];
assert_eq!(slice, &amp;[2, 3]);
<span class="boring">}</span></code></pre></pre>
<p>这个 slice 的类型是 <code>&amp;[i32]</code>。它跟字符串 slice 的工作方式一样,通过存储第一个集合元素的引用和一个集合总长度。你可以对其他所有集合使用这类 slice。第八章讲到 vector 时会详细讨论这些集合。</p>
<h2 id="总结-3"><a class="header" href="#总结-3">总结</a></h2>
<p>所有权、借用和 slice 这些概念让 Rust 程序在编译时确保内存安全。Rust 语言提供了跟其他系统编程语言相同的方式来控制你使用的内存,但拥有数据所有者在离开作用域后自动清除其数据的功能意味着你无须额外编写和调试相关的控制代码。</p>
<p>所有权系统影响了 Rust 中很多其他部分的工作方式,所以我们还会继续讲到这些概念,这将贯穿本书的余下内容。让我们开始第五章,来看看如何将多份数据组合进一个 <code>struct</code> 中。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="使用结构体组织相关联的数据"><a class="header" href="#使用结构体组织相关联的数据">使用结构体组织相关联的数据</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch05-00-structs.md">ch05-00-structs.md</a>
<br>
commit 8612c4a5801b61f8d2e952f8bbbb444692ff1ec2</p>
</blockquote>
<p><em>struct</em>,或者 <em>structure</em>,是一个自定义数据类型,允许你包装和命名多个相关的值,从而形成一个有意义的组合。如果你熟悉一门面向对象语言,<em>struct</em> 就像对象中的数据属性。在本章中,我们会对元组和结构体进行比较和对比。</p>
<p>我们还将演示如何定义和实例化结构体,并讨论如何定义关联函数,特别是被称为 <em>方法</em> 的那种关联函数,以指定与结构体类型相关的行为。你可以在程序中基于结构体和枚举(<em>enum</em>)(在第六章介绍)创建新类型,以充分利用 Rust 的编译时类型检查。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="结构体的定义和实例化"><a class="header" href="#结构体的定义和实例化">结构体的定义和实例化</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch05-01-defining-structs.md">ch05-01-defining-structs.md</a>
<br>
commit a371f82b0916cf21de2d56bd386ca5d72f7699b0</p>
</blockquote>
<p>结构体和我们在<a href="ch03-02-data-types.html#%E5%85%83%E7%BB%84%E7%B1%BB%E5%9E%8B">“元组类型”</a>部分论过的元组类似,它们都包含多个相关的值。和元组一样,结构体的每一部分可以是不同类型。但不同于元组,结构体需要命名各部分数据以便能清楚的表明其值的意义。由于有了这些名字,结构体比元组更灵活:不需要依赖顺序来指定或访问实例中的值。</p>
<p>定义结构体,需要使用 <code>struct</code> 关键字并为整个结构体提供一个名字。结构体的名字需要描述它所组合的数据的意义。接着,在大括号中,定义每一部分数据的名字和类型,我们称为 <strong>字段</strong><em>field</em>)。例如,示例 5-1 展示了一个存储用户账号信息的结构体:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 5-1<code>User</code> 结构体定义</span></p>
<p>一旦定义了结构体后,为了使用它,通过为每个字段指定具体值来创建这个结构体的 <strong>实例</strong>。创建一个实例需要以结构体的名字开头,接着在大括号中使用 <code>key: value</code> 键 - 值对的形式提供字段,其中 key 是字段的名字value 是需要存储在字段中的数据值。实例中字段的顺序不需要和它们在结构体中声明的顺序一致。换句话说,结构体的定义就像一个类型的通用模板,而实例则会在这个模板中放入特定数据来创建这个类型的值。例如,可以像示例 5-2 这样来声明一个特定的用户:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct User {
</span><span class="boring"> active: bool,
</span><span class="boring"> username: String,
</span><span class="boring"> email: String,
</span><span class="boring"> sign_in_count: u64,
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let user1 = User {
active: true,
username: String::from("someusername123"),
email: String::from("someone@example.com"),
sign_in_count: 1,
};
}</code></pre></pre>
<p><span class="caption">示例 5-2创建 <code>User</code> 结构体的实例</span></p>
<p>为了从结构体中获取某个特定的值,可以使用点号。举个例子,想要用户的邮箱地址,可以用 <code>user1.email</code>。如果结构体的实例是可变的,我们可以使用点号并为对应的字段赋值。示例 5-3 展示了如何改变一个可变的 <code>User</code> 实例中 <code>email</code> 字段的值:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct User {
</span><span class="boring"> active: bool,
</span><span class="boring"> username: String,
</span><span class="boring"> email: String,
</span><span class="boring"> sign_in_count: u64,
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let mut user1 = User {
active: true,
username: String::from("someusername123"),
email: String::from("someone@example.com"),
sign_in_count: 1,
};
user1.email = String::from("anotheremail@example.com");
}</code></pre></pre>
<p><span class="caption">示例 5-3改变 <code>User</code> 实例 <code>email</code> 字段的值</span></p>
<p>注意整个实例必须是可变的Rust 并不允许只将某个字段标记为可变。另外需要注意同其他任何表达式一样,我们可以在函数体的最后一个表达式中构造一个结构体的新实例,来隐式地返回这个实例。</p>
<p>示例 5-4 显示了一个 <code>build_user</code> 函数,它返回一个带有给定的 email 和用户名的 <code>User</code> 结构体实例。<code>active</code> 字段的值为 <code>true</code>,并且 <code>sign_in_count</code> 的值为 <code>1</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct User {
</span><span class="boring"> active: bool,
</span><span class="boring"> username: String,
</span><span class="boring"> email: String,
</span><span class="boring"> sign_in_count: u64,
</span><span class="boring">}
</span><span class="boring">
</span>fn build_user(email: String, username: String) -&gt; User {
User {
active: true,
username: username,
email: email,
sign_in_count: 1,
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let user1 = build_user(
</span><span class="boring"> String::from("someone@example.com"),
</span><span class="boring"> String::from("someusername123"),
</span><span class="boring"> );
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 5-4<code>build_user</code> 函数获取 email 和用户名并返回 <code>User</code> 实例</span></p>
<p>为函数参数起与结构体字段相同的名字是可以理解的,但是不得不重复 <code>email</code><code>username</code> 字段名称与变量有些啰嗦。如果结构体有更多字段,重复每个名称就更加烦人了。幸运的是,有一个方便的简写语法!</p>
<h3 id="使用字段初始化简写语法"><a class="header" href="#使用字段初始化简写语法">使用字段初始化简写语法</a></h3>
<p>因为示例 5-4 中的参数名与字段名都完全相同,我们可以使用 <strong>字段初始化简写语法</strong><em>field init shorthand</em>)来重写 <code>build_user</code>,这样其行为与之前完全相同,不过无需重复 <code>username</code><code>email</code> 了,如示例 5-5 所示。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct User {
</span><span class="boring"> active: bool,
</span><span class="boring"> username: String,
</span><span class="boring"> email: String,
</span><span class="boring"> sign_in_count: u64,
</span><span class="boring">}
</span><span class="boring">
</span>fn build_user(email: String, username: String) -&gt; User {
User {
active: true,
username,
email,
sign_in_count: 1,
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let user1 = build_user(
</span><span class="boring"> String::from("someone@example.com"),
</span><span class="boring"> String::from("someusername123"),
</span><span class="boring"> );
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 5-5<code>build_user</code> 函数使用了字段初始化简写语法,因为 <code>username</code><code>email</code> 参数与结构体字段同名</span></p>
<p>这里我们创建了一个新的 <code>User</code> 结构体实例,它有一个叫做 <code>email</code> 的字段。我们想要将 <code>email</code> 字段的值设置为 <code>build_user</code> 函数 <code>email</code> 参数的值。因为 <code>email</code> 字段与 <code>email</code> 参数有着相同的名称,则只需编写 <code>email</code> 而不是 <code>email: email</code></p>
<h3 id="使用结构体更新语法从其他实例创建实例"><a class="header" href="#使用结构体更新语法从其他实例创建实例">使用结构体更新语法从其他实例创建实例</a></h3>
<p>使用旧实例的大部分值但改变其部分值来创建一个新的结构体实例通常是很有用的。这可以通过 <strong>结构体更新语法</strong><em>struct update syntax</em>)实现。</p>
<p>首先,示例 5-6 展示了不使用更新语法时,如何在 <code>user2</code> 中创建一个新 <code>User</code> 实例。我们为 <code>email</code> 设置了新的值,其他值则使用了实例 5-2 中创建的 <code>user1</code> 中的同名值:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct User {
</span><span class="boring"> active: bool,
</span><span class="boring"> username: String,
</span><span class="boring"> email: String,
</span><span class="boring"> sign_in_count: u64,
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
// --snip--
<span class="boring">
</span><span class="boring"> let user1 = User {
</span><span class="boring"> email: String::from("someone@example.com"),
</span><span class="boring"> username: String::from("someusername123"),
</span><span class="boring"> active: true,
</span><span class="boring"> sign_in_count: 1,
</span><span class="boring"> };
</span>
let user2 = User {
active: user1.active,
username: user1.username,
email: String::from("another@example.com"),
sign_in_count: user1.sign_in_count,
};
}</code></pre></pre>
<p><span class="caption">示例 5-6使用 <code>user1</code> 中的一个值创建一个新的 <code>User</code> 实例</span></p>
<p>使用结构体更新语法,我们可以通过更少的代码来达到相同的效果,如示例 5-7 所示。<code>..</code> 语法指定了剩余未显式设置值的字段应有与给定实例对应字段相同的值。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct User {
</span><span class="boring"> active: bool,
</span><span class="boring"> username: String,
</span><span class="boring"> email: String,
</span><span class="boring"> sign_in_count: u64,
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
// --snip--
<span class="boring">
</span><span class="boring"> let user1 = User {
</span><span class="boring"> email: String::from("someone@example.com"),
</span><span class="boring"> username: String::from("someusername123"),
</span><span class="boring"> active: true,
</span><span class="boring"> sign_in_count: 1,
</span><span class="boring"> };
</span>
let user2 = User {
email: String::from("another@example.com"),
..user1
};
}</code></pre></pre>
<p><span class="caption">示例 5-7使用结构体更新语法为一个 <code>User</code> 实例设置一个新的 <code>email</code> 值,不过其余值来自 <code>user1</code> 变量中实例的字段</span></p>
<p>示例 5-7 中的代码也在 <code>user2</code> 中创建了一个新实例,但该实例中 <code>email</code> 字段的值与 <code>user1</code> 不同,而 <code>username</code><code>active</code><code>sign_in_count</code> 字段的值与 <code>user1</code> 相同。<code>..user1</code> 必须放在最后,以指定其余的字段应从 <code>user1</code> 的相应字段中获取其值,但我们可以选择以任何顺序为任意字段指定值,而不用考虑结构体定义中字段的顺序。</p>
<p>请注意,结构更新语法就像带有 <code>=</code> 的赋值,因为它移动了数据,就像我们在<a href="ch04-01-what-is-ownership.html#%E5%8F%98%E9%87%8F%E4%B8%8E%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%9A%84%E6%96%B9%E5%BC%8F%E4%B8%80%E7%A7%BB%E5%8A%A8">“变量与数据交互的方式(一):移动”</a>部分讲到的一样。在这个例子中,总体上说我们在创建 <code>user2</code> 后不能就再使用 <code>user1</code> 了,因为 <code>user1</code><code>username</code> 字段中的 <code>String</code> 被移到 <code>user2</code> 中。如果我们给 <code>user2</code><code>email</code><code>username</code> 都赋予新的 <code>String</code> 值,从而只使用 <code>user1</code><code>active</code><code>sign_in_count</code> 值,那么 <code>user1</code> 在创建 <code>user2</code> 后仍然有效。<code>active</code><code>sign_in_count</code> 的类型是实现 <code>Copy</code> trait 的类型,所以我们在<a href="ch04-01-what-is-ownership.html#%E5%8F%98%E9%87%8F%E4%B8%8E%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%9A%84%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%85%8B%E9%9A%86">“变量与数据交互的方式(二):克隆”</a> 部分讨论的行为同样适用。</p>
<h3 id="使用没有命名字段的元组结构体来创建不同的类型"><a class="header" href="#使用没有命名字段的元组结构体来创建不同的类型">使用没有命名字段的元组结构体来创建不同的类型</a></h3>
<p>也可以定义与元组(在第三章讨论过)类似的结构体,称为 <strong>元组结构体</strong><em>tuple structs</em>)。元组结构体有着结构体名称提供的含义,但没有具体的字段名,只有字段的类型。当你想给整个元组取一个名字,并使元组成为与其他元组不同的类型时,元组结构体是很有用的,这时像常规结构体那样为每个字段命名就显得多余和形式化了。</p>
<p>要定义元组结构体,以 <code>struct</code> 关键字和结构体名开头并后跟元组中的类型。例如,下面是两个分别叫做 <code>Color</code><code>Point</code> 元组结构体的定义和用法:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
fn main() {
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
}</code></pre></pre>
<p>注意 <code>black</code><code>origin</code> 值的类型不同,因为它们是不同的元组结构体的实例。你定义的每一个结构体有其自己的类型,即使结构体中的字段可能有着相同的类型。例如,一个获取 <code>Color</code> 类型参数的函数不能接受 <code>Point</code> 作为参数,即便这两个类型都由三个 <code>i32</code> 值组成。在其他方面,元组结构体实例类似于元组,你可以将它们解构为单独的部分,也可以使用 <code>.</code> 后跟索引来访问单独的值,等等。</p>
<h3 id="没有任何字段的类单元结构体"><a class="header" href="#没有任何字段的类单元结构体">没有任何字段的类单元结构体</a></h3>
<p>我们也可以定义一个没有任何字段的结构体!它们被称为 <strong>类单元结构体</strong><em>unit-like structs</em>)因为它们类似于 <code>()</code>,即<a href="ch03-02-data-types.html#%E5%85%83%E7%BB%84%E7%B1%BB%E5%9E%8B">“元组类型”</a>一节中提到的 unit 类型。类单元结构体常常在你想要在某个类型上实现 trait 但不需要在类型中存储数据的时候发挥作用。我们将在第十章介绍 trait。下面是一个声明和实例化一个名为 <code>AlwaysEqual</code> 的 unit 结构的例子。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct AlwaysEqual;
fn main() {
let subject = AlwaysEqual;
}</code></pre></pre>
<p>为了定义 <code>AlwaysEqual</code>,我们使用 <code>struct</code> 关键字,接着是我们想要的名称,然后是一个分号。不需要花括号或圆括号!然后,我们可以以类似的方式在 <code>subject</code> 变量中创建 <code>AlwaysEqual</code> 的实例:只需使用我们定义的名称,无需任何花括号或圆括号。设想我们稍后将为这个类型实现某种行为,使得每个 <code>AlwaysEqual</code> 的实例始终等于任何其它类型的实例,也许是为了获得一个已知的结果以便进行测试。我们无需要任何数据来实现这种行为!在第十章中,你会看到如何定义特征并在任何类型上实现它们,包括类单元结构体。</p>
<blockquote>
<h3 id="结构体数据的所有权"><a class="header" href="#结构体数据的所有权">结构体数据的所有权</a></h3>
<p>在示例 5-1 中的 <code>User</code> 结构体的定义中,我们使用了自身拥有所有权的 <code>String</code> 类型而不是 <code>&amp;str</code> 字符串 slice 类型。这是一个有意而为之的选择,因为我们想要这个结构体拥有它所有的数据,为此只要整个结构体是有效的话其数据也是有效的。</p>
<p>可以使结构体存储被其他对象拥有的数据的引用,不过这么做的话需要用上 <strong>生命周期</strong><em>lifetimes</em>),这是一个第十章会讨论的 Rust 功能。生命周期确保结构体引用的数据有效性跟结构体本身保持一致。如果你尝试在结构体中存储一个引用而不指定生命周期将是无效的,比如这样:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">struct User {
active: bool,
username: &amp;str,
email: &amp;str,
sign_in_count: u64,
}
fn main() {
let user1 = User {
active: true,
username: "someusername123",
email: "someone@example.com",
sign_in_count: 1,
};
}</code></pre>
<p>编译器会抱怨它需要生命周期标识符:</p>
<pre><code class="language-console">$ cargo run
Compiling structs v0.1.0 (file:///projects/structs)
error[E0106]: missing lifetime specifier
--&gt; src/main.rs:3:15
|
3 | username: &amp;str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct User&lt;'a&gt; {
2 | active: bool,
3 ~ username: &amp;'a str,
|
error[E0106]: missing lifetime specifier
--&gt; src/main.rs:4:12
|
4 | email: &amp;str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct User&lt;'a&gt; {
2 | active: bool,
3 | username: &amp;str,
4 ~ email: &amp;'a str,
|
For more information about this error, try `rustc --explain E0106`.
error: could not compile `structs` due to 2 previous errors
</code></pre>
<p>第十章会讲到如何修复这个问题以便在结构体中存储引用,不过现在,我们会使用像 <code>String</code> 这类拥有所有权的类型来替代 <code>&amp;str</code> 这样的引用以修正这个错误。</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h2 id="结构体示例程序"><a class="header" href="#结构体示例程序">结构体示例程序</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch05-02-example-structs.md">ch05-02-example-structs.md</a>
<br>
commit 8612c4a5801b61f8d2e952f8bbbb444692ff1ec2</p>
</blockquote>
<p>为了理解何时会需要使用结构体,让我们编写一个计算长方形面积的程序。我们会从单独的变量开始,接着重构程序直到使用结构体替代它们为止。</p>
<p>使用 Cargo 新建一个叫做 <em>rectangles</em> 的二进制程序,它获取以像素为单位的长方形的宽度和高度,并计算出长方形的面积。示例 5-8 显示了位于项目的 <em>src/main.rs</em> 中的小程序,它刚刚好实现此功能:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let width1 = 30;
let height1 = 50;
println!(
"The area of the rectangle is {} square pixels.",
area(width1, height1)
);
}
fn area(width: u32, height: u32) -&gt; u32 {
width * height
}</code></pre></pre>
<p><span class="caption">示例 5-8通过分别指定长方形的宽和高的变量来计算长方形面积</span></p>
<p>现在使用 <code>cargo run</code> 运行程序:</p>
<pre><code class="language-console">$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s
Running `target/debug/rectangles`
The area of the rectangle is 1500 square pixels.
</code></pre>
<p>这个示例代码在调用 <code>area</code> 函数时传入每个维度,虽然可以正确计算出长方形的面积,但我们仍然可以修改这段代码来使它的意义更加明确,并且增加可读性。</p>
<p>这些代码的问题突显在 <code>area</code> 的签名上:</p>
<pre><code class="language-rust ignore"><span class="boring">fn main() {
</span><span class="boring"> let width1 = 30;
</span><span class="boring"> let height1 = 50;
</span><span class="boring">
</span><span class="boring"> println!(
</span><span class="boring"> "The area of the rectangle is {} square pixels.",
</span><span class="boring"> area(width1, height1)
</span><span class="boring"> );
</span><span class="boring">}
</span><span class="boring">
</span>fn area(width: u32, height: u32) -&gt; u32 {
<span class="boring"> width * height
</span><span class="boring">}</span></code></pre>
<p>函数 <code>area</code> 本应该计算一个长方形的面积,不过函数却有两个参数。这两个参数是相关联的,不过程序本身却没有表现出这一点。将长度和宽度组合在一起将更易懂也更易处理。第三章的 <a href="ch03-02-data-types.html#%E5%85%83%E7%BB%84%E7%B1%BB%E5%9E%8B">“元组类型”</a> 部分已经讨论过了一种可行的方法:元组。</p>
<h3 id="使用元组重构"><a class="header" href="#使用元组重构">使用元组重构</a></h3>
<p>示例 5-9 展示了使用元组的另一个程序版本。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let rect1 = (30, 50);
println!(
"The area of the rectangle is {} square pixels.",
area(rect1)
);
}
fn area(dimensions: (u32, u32)) -&gt; u32 {
dimensions.0 * dimensions.1
}</code></pre></pre>
<p><span class="caption">示例 5-9使用元组来指定长方形的宽高</span></p>
<p>在某种程度上说,这个程序更好一点了。元组帮助我们增加了一些结构性,并且现在只需传一个参数。不过在另一方面,这个版本却有一点不明确了:元组并没有给出元素的名称,所以计算变得更费解了,因为不得不使用索引来获取元组的每一部分:</p>
<p>在计算面积时将宽和高弄混倒无关紧要,不过当在屏幕上绘制长方形时就有问题了!我们必须牢记 <code>width</code> 的元组索引是 <code>0</code><code>height</code> 的元组索引是 <code>1</code>。如果其他人要使用这些代码,他们必须要搞清楚这一点,并也要牢记于心。很容易忘记或者混淆这些值而造成错误,因为我们没有在代码中传达数据的意图。</p>
<h3 id="使用结构体重构赋予更多意义"><a class="header" href="#使用结构体重构赋予更多意义">使用结构体重构:赋予更多意义</a></h3>
<p>我们使用结构体为数据命名来为其赋予意义。我们可以将我们正在使用的元组转换成一个有整体名称而且每个部分也有对应名字的结构体,如示例 5-10 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
area(&amp;rect1)
);
}
fn area(rectangle: &amp;Rectangle) -&gt; u32 {
rectangle.width * rectangle.height
}</code></pre></pre>
<p><span class="caption">示例 5-10定义 <code>Rectangle</code> 结构体</span></p>
<p>这里我们定义了一个结构体并称其为 <code>Rectangle</code>。在大括号中定义了字段 <code>width</code><code>height</code>,类型都是 <code>u32</code>。接着在 <code>main</code> 中,我们创建了一个具体的 <code>Rectangle</code> 实例,它的宽是 <code>30</code>,高是 <code>50</code></p>
<p>函数 <code>area</code> 现在被定义为接收一个名叫 <code>rectangle</code> 的参数,其类型是一个结构体 <code>Rectangle</code> 实例的不可变借用。第四章讲到过,我们希望借用结构体而不是获取它的所有权,这样 <code>main</code> 函数就可以保持 <code>rect1</code> 的所有权并继续使用它,所以这就是为什么在函数签名和调用的地方会有 <code>&amp;</code></p>
<p><code>area</code> 函数访问 <code>Rectangle</code> 实例的 <code>width</code><code>height</code> 字段(注意,访问对结构体的引用的字段不会移动字段的所有权,这就是为什么你经常看到对结构体的引用)。<code>area</code> 的函数签名现在明确的阐述了我们的意图:使用 <code>Rectangle</code><code>width</code><code>height</code> 字段,计算 <code>Rectangle</code> 的面积。这表明宽高是相互联系的,并为这些值提供了描述性的名称而不是使用元组的索引值 <code>0</code><code>1</code> 。结构体胜在更清晰明了。</p>
<h3 id="通过派生-trait-增加实用功能"><a class="header" href="#通过派生-trait-增加实用功能">通过派生 trait 增加实用功能</a></h3>
<p>在调试程序时打印出 <code>Rectangle</code> 实例来查看其所有字段的值非常有用。示例 5-11 像前面章节那样尝试使用 <a href="https://doc.rust-lang.org/std/macro.println.html"><code>println!</code></a>。但这并不行。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {}", rect1);
}</code></pre>
<p><span class="caption">示例 5-11尝试打印出 <code>Rectangle</code> 实例</span></p>
<p>当我们运行这个代码时,会出现带有如下核心信息的错误:</p>
<pre><code class="language-text">error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`
</code></pre>
<p><code>println!</code> 宏能处理很多类型的格式,不过,<code>{}</code> 默认告诉 <code>println!</code> 使用被称为 <code>Display</code> 的格式:意在提供给直接终端用户查看的输出。目前为止见过的基本类型都默认实现了 <code>Display</code>,因为它就是向用户展示 <code>1</code> 或其他任何基本类型的唯一方式。不过对于结构体,<code>println!</code> 应该用来输出的格式是不明确的因为这有更多显示的可能性是否需要逗号需要打印出大括号吗所有字段都应该显示吗由于这种不确定性Rust 不会尝试猜测我们的意图,所以结构体并没有提供一个 <code>Display</code> 实现来使用 <code>println!</code><code>{}</code> 占位符。</p>
<p>但是如果我们继续阅读错误,将会发现这个有帮助的信息:</p>
<pre><code class="language-text"> = help: the trait `std::fmt::Display` is not implemented for `Rectangle`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
</code></pre>
<p>让我们来试试!现在 <code>println!</code> 宏调用看起来像 <code>println!("rect1 is {:?}", rect1);</code> 这样。在 <code>{}</code> 中加入 <code>:?</code> 指示符告诉 <code>println!</code> 我们想要使用叫做 <code>Debug</code> 的输出格式。<code>Debug</code> 是一个 trait它允许我们以一种对开发者有帮助的方式打印结构体以便当我们调试代码时能看到它的值。</p>
<p>这样调整后再次运行程序。见鬼了!仍然能看到一个错误:</p>
<pre><code class="language-text">error[E0277]: `Rectangle` doesn't implement `Debug`
</code></pre>
<p>不过编译器又一次给出了一个有帮助的信息:</p>
<pre><code class="language-text"> = help: the trait `Debug` is not implemented for `Rectangle`
= note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle`
</code></pre>
<p>Rust <strong>确实</strong> 包含了打印出调试信息的功能,不过我们必须为结构体显式选择这个功能。为此,在结构体定义之前加上外部属性 <code>#[derive(Debug)]</code>,如示例 5-12 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {rect1:?}");
}</code></pre></pre>
<p><span class="caption">示例 5-12增加属性来派生 <code>Debug</code> trait并使用调试格式打印 <code>Rectangle</code> 实例</span></p>
<p>现在我们再运行这个程序时,就不会有任何错误,并会出现如下输出:</p>
<pre><code class="language-console">$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/rectangles`
rect1 is Rectangle { width: 30, height: 50 }
</code></pre>
<p>好极了!这并不是最漂亮的输出,不过它显示这个实例的所有字段,毫无疑问这对调试有帮助。当我们有一个更大的结构体时,能有更易读一点的输出就好了,为此可以使用 <code>{:#?}</code> 替换 <code>println!</code> 字符串中的 <code>{:?}</code>。在这个例子中使用 <code>{:#?}</code> 风格将会输出如下:</p>
<pre><code class="language-console">$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/rectangles`
rect1 is Rectangle {
width: 30,
height: 50,
}
</code></pre>
<p>另一种使用 <code>Debug</code> 格式打印数值的方法是使用 <a href="https://doc.rust-lang.org/std/macro.dbg.html"><code>dbg!</code></a><code>dbg!</code> 宏接收一个表达式的所有权(与 <code>println!</code> 宏相反,后者接收的是引用),打印出代码中调用 dbg! 宏时所在的文件和行号,以及该表达式的结果值,并返回该值的所有权。</p>
<blockquote>
<p>注意:调用 <code>dbg!</code> 宏会打印到标准错误控制台流(<code>stderr</code>),与 <code>println!</code> 不同,后者会打印到标准输出控制台流(<code>stdout</code>)。我们将在<a href="ch12-06-writing-to-stderr-instead-of-stdout.html">第十二章 “将错误信息写入标准错误而不是标准输出” 一节</a>中更多地讨论 <code>stderr</code><code>stdout</code></p>
</blockquote>
<p>下面是一个例子,我们对分配给 <code>width</code> 字段的值以及 <code>rect1</code> 中整个结构的值感兴趣。</p>
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let scale = 2;
let rect1 = Rectangle {
width: dbg!(30 * scale),
height: 50,
};
dbg!(&amp;rect1);
}</code></pre></pre>
<p>我们可以把 <code>dbg!</code> 放在表达式 <code>30 * scale</code> 周围,因为 <code>dbg!</code> 返回表达式的值的所有权,所以 <code>width</code> 字段将获得相同的值,就像我们在那里没有 <code>dbg!</code> 调用一样。我们不希望 <code>dbg!</code> 拥有 <code>rect1</code> 的所有权,所以我们在下一次调用 <code>dbg!</code> 时传递一个引用。下面是这个例子的输出结果:</p>
<pre><code class="language-console">$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.61s
Running `target/debug/rectangles`
[src/main.rs:10:16] 30 * scale = 60
[src/main.rs:14:5] &amp;rect1 = Rectangle {
width: 60,
height: 50,
}
</code></pre>
<p>我们可以看到第一点输出来自 <em>src/main.rs</em> 第 10 行,我们正在调试表达式 <code>30 * scale</code>,其结果值是 <code>60</code>(为整数实现的 <code>Debug</code> 格式化是只打印它们的值)。在 <em>src/main.rs</em> 第 14 行 的 <code>dbg!</code> 调用输出 <code>&amp;rect1</code> 的值,即 <code>Rectangle</code> 结构。这个输出使用了更为易读的 <code>Debug</code> 格式。当你试图弄清楚你的代码在做什么时,<code>dbg!</code> 宏可能真的很有帮助!</p>
<p>除了 <code>Debug</code> traitRust 还为我们提供了很多可以通过 <code>derive</code> 属性来使用的 trait它们可以为我们的自定义类型增加实用的行为。<a href="appendix-03-derivable-traits.html">附录 C</a> 中列出了这些 trait 和行为。第十章会介绍如何通过自定义行为来实现这些 trait同时还有如何创建你自己的 trait。除了 <code>derive</code> 之外,还有很多属性;更多信息请参见 <a href="https://doc.rust-lang.org/stable/reference/attributes.html">Rust Reference</a> 的 Attributes 部分。</p>
<p>我们的 <code>area</code> 函数是非常特殊的,它只计算长方形的面积。如果这个行为与 <code>Rectangle</code> 结构体再结合得更紧密一些就更好了,因为它不能用于其他类型。现在让我们看看如何继续重构这些代码,来将 <code>area</code> 函数协调进 <code>Rectangle</code> 类型定义的 <code>area</code> <strong>方法</strong> 中。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="方法语法"><a class="header" href="#方法语法">方法语法</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch05-03-method-syntax.md">ch05-03-method-syntax.md</a>
<br>
commit d339373a838fd312a8a9bcc9487e1ffbc9e1582f</p>
</blockquote>
<p><strong>方法</strong>method与函数类似它们使用 <code>fn</code> 关键字和名称声明,可以拥有参数和返回值,同时包含在某处调用该方法时会执行的代码。不过方法与函数是不同的,因为它们在结构体的上下文中被定义(或者是枚举或 trait 对象的上下文,将分别在<a href="ch06-00-enums.html">第六章</a><a href="ch18-02-trait-objects.html">第十八章</a>讲解),并且它们第一个参数总是 <code>self</code>,它代表调用该方法的结构体实例。</p>
<h3 id="定义方法"><a class="header" href="#定义方法">定义方法</a></h3>
<p>让我们把前面实现的获取一个 <code>Rectangle</code> 实例作为参数的 <code>area</code> 函数,改写成一个定义于 <code>Rectangle</code> 结构体上的 <code>area</code> 方法,如示例 5-13 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
}</code></pre></pre>
<p><span class="caption">示例 5-13<code>Rectangle</code> 结构体上定义 <code>area</code> 方法</span></p>
<p>为了使函数定义于 <code>Rectangle</code> 的上下文中,我们开始了一个 <code>impl</code> 块(<code>impl</code><em>implementation</em> 的缩写),这个 <code>impl</code> 块中的所有内容都将与 <code>Rectangle</code> 类型相关联。接着将 <code>area</code> 函数移动到 <code>impl</code> 大括号中,并将签名中的第一个(在这里也是唯一一个)参数和函数体中其他地方的对应参数改成 <code>self</code>。然后在 <code>main</code> 中将我们先前调用 <code>area</code> 方法并传递 <code>rect1</code> 作为参数的地方,改成使用 <strong>方法语法</strong><em>method syntax</em>)在 <code>Rectangle</code> 实例上调用 <code>area</code> 方法。方法语法获取一个实例并加上一个点号,后跟方法名、圆括号以及任何参数。</p>
<p><code>area</code> 的签名中,使用 <code>&amp;self</code> 来替代 <code>rectangle: &amp;Rectangle</code><code>&amp;self</code> 实际上是 <code>self: &amp;Self</code> 的缩写。在一个 <code>impl</code> 块中,<code>Self</code> 类型是 <code>impl</code> 块的类型的别名。方法的第一个参数必须有一个名为 <code>self</code><code>Self</code> 类型的参数,所以 Rust 让你在第一个参数位置上只用 <code>self</code> 这个名字来简化。注意,我们仍然需要在 <code>self</code> 前面使用 <code>&amp;</code> 来表示这个方法借用了 <code>Self</code> 实例,就像我们在 <code>rectangle: &amp;Rectangle</code> 中做的那样。方法可以选择获得 <code>self</code> 的所有权,或者像我们这里一样不可变地借用 <code>self</code>,或者可变地借用 <code>self</code>,就跟其他参数一样。</p>
<p>这里选择 <code>&amp;self</code> 的理由跟在函数版本中使用 <code>&amp;Rectangle</code> 是相同的:我们并不想获取所有权,只希望能够读取结构体中的数据,而不是写入。如果想要在方法中改变调用方法的实例,需要将第一个参数改为 <code>&amp;mut self</code>。通过仅仅使用 <code>self</code> 作为第一个参数来使方法获取实例的所有权是很少见的;这种技术通常用在当方法将 <code>self</code> 转换成别的实例的时候,这时我们想要防止调用者在转换之后使用原始的实例。</p>
<p>使用方法替代函数,除了可使用方法语法和不需要在每个函数签名中重复 <code>self</code> 的类型之外,其主要好处在于组织性。我们将某个类型实例能做的所有事情都一起放入 <code>impl</code> 块中,而不是让将来的用户在我们的库中到处寻找 <code>Rectangle</code> 的功能。</p>
<p>请注意,我们可以选择将方法的名称与结构中的一个字段相同。例如,我们可以在 <code>Rectangle</code> 上定义一个方法,并命名为 <code>width</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>impl Rectangle {
fn width(&amp;self) -&gt; bool {
self.width &gt; 0
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
if rect1.width() {
println!("The rectangle has a nonzero width; it is {}", rect1.width);
}
}</code></pre></pre>
<p>在这里,我们选择让 <code>width</code> 方法在实例的 <code>width</code> 字段的值大于 <code>0</code> 时返回 <code>true</code>,等于 <code>0</code> 时则返回 <code>false</code>:我们可以出于任何目的,在同名的方法中使用同名的字段。在 <code>main</code> 中,当我们在 <code>rect1.width</code> 后面加上括号时。Rust 知道我们指的是方法 <code>width</code>。当我们不使用圆括号时Rust 知道我们指的是字段 <code>width</code></p>
<p>通常,但并不总是如此,与字段同名的方法将被定义为只返回字段中的值,而不做其他事情。这样的方法被称为 <em>getters</em>Rust 并不像其他一些语言那样为结构字段自动实现它们。Getters 很有用,因为你可以把字段变成私有的,但方法是公共的,这样就可以把对字段的只读访问作为该类型公共 API 的一部分。我们将在<a href="ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#%E4%BD%BF%E7%94%A8-pub-%E5%85%B3%E9%94%AE%E5%AD%97%E6%9A%B4%E9%9C%B2%E8%B7%AF%E5%BE%84">第七章</a>中讨论什么是公有和私有,以及如何将一个字段或方法指定为公有或私有。</p>
<blockquote>
<h3 id="--运算符到哪去了"><a class="header" href="#--运算符到哪去了"><code>-&gt;</code> 运算符到哪去了?</a></h3>
<p>在 C/C++ 语言中,有两个不同的运算符来调用方法:<code>.</code> 直接在对象上调用方法,而 <code>-&gt;</code> 在一个对象的指针上调用方法这时需要先解引用dereference指针。换句话说如果 <code>object</code> 是一个指针,那么 <code>object-&gt;something()</code> 就像 <code>(*object).something()</code> 一样。</p>
<p>Rust 并没有一个与 <code>-&gt;</code> 等效的运算符相反Rust 有一个叫 <strong>自动引用和解引用</strong><em>automatic referencing and dereferencing</em>)的功能。方法调用是 Rust 中少数几个拥有这种行为的地方。</p>
<p>它是这样工作的:当使用 <code>object.something()</code> 调用方法时Rust 会自动为 <code>object</code> 添加 <code>&amp;</code><code>&amp;mut</code><code>*</code> 以便使 <code>object</code> 与方法签名匹配。也就是说,这些代码是等价的:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">#[derive(Debug,Copy,Clone)]
</span><span class="boring">struct Point {
</span><span class="boring"> x: f64,
</span><span class="boring"> y: f64,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Point {
</span><span class="boring"> fn distance(&amp;self, other: &amp;Point) -&gt; f64 {
</span><span class="boring"> let x_squared = f64::powi(other.x - self.x, 2);
</span><span class="boring"> let y_squared = f64::powi(other.y - self.y, 2);
</span><span class="boring">
</span><span class="boring"> f64::sqrt(x_squared + y_squared)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">let p1 = Point { x: 0.0, y: 0.0 };
</span><span class="boring">let p2 = Point { x: 5.0, y: 6.5 };
</span>p1.distance(&amp;p2);
(&amp;p1).distance(&amp;p2);
<span class="boring">}</span></code></pre></pre>
<p>第一行看起来简洁的多。这种自动引用的行为之所以有效,是因为方法有一个明确的接收者———— <code>self</code> 的类型。在给出接收者和方法名的前提下Rust 可以明确地计算出方法是仅仅读取(<code>&amp;self</code>),做出修改(<code>&amp;mut self</code>)或者是获取所有权(<code>self</code>。事实上Rust 对方法接收者的隐式借用让所有权在实践中更友好。</p>
</blockquote>
<h3 id="带有更多参数的方法"><a class="header" href="#带有更多参数的方法">带有更多参数的方法</a></h3>
<p>让我们通过实现 <code>Rectangle</code> 结构体上的另一方法来练习使用方法。这回,我们让一个 <code>Rectangle</code> 的实例获取另一个 <code>Rectangle</code> 实例,如果 <code>self</code> (第一个 <code>Rectangle</code>)能完全包含第二个长方形则返回 <code>true</code>;否则返回 <code>false</code>。一旦我们定义了 <code>can_hold</code> 方法,就可以编写示例 5-14 中的代码。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&amp;rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&amp;rect3));
}</code></pre>
<p><span class="caption">示例 5-14使用还未实现的 <code>can_hold</code> 方法</span></p>
<p>同时我们希望看到如下输出,因为 <code>rect2</code> 的两个维度都小于 <code>rect1</code>,而 <code>rect3</code><code>rect1</code> 要宽:</p>
<pre><code class="language-text">Can rect1 hold rect2? true
Can rect1 hold rect3? false
</code></pre>
<p>因为我们想定义一个方法,所以它应该位于 <code>impl Rectangle</code> 块中。方法名是 <code>can_hold</code>,并且它会获取另一个 <code>Rectangle</code> 的不可变借用作为参数。通过观察调用方法的代码可以看出参数是什么类型的:<code>rect1.can_hold(&amp;rect2)</code> 传入了 <code>&amp;rect2</code>,它是一个 <code>Rectangle</code> 的实例 <code>rect2</code> 的不可变借用。这是可以理解的,因为我们只需要读取 <code>rect2</code>(而不是写入,这意味着我们需要一个不可变借用),而且希望 <code>main</code> 保持 <code>rect2</code> 的所有权,这样就可以在调用这个方法后继续使用它。<code>can_hold</code> 的返回值是一个布尔值,其实现会分别检查 <code>self</code> 的宽高是否都大于另一个 <code>Rectangle</code>。让我们在示例 5-13 的 <code>impl</code> 块中增加这个新的 <code>can_hold</code> 方法,如示例 5-15 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.width * self.height
}
fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.width &gt; other.width &amp;&amp; self.height &gt; other.height
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let rect1 = Rectangle {
</span><span class="boring"> width: 30,
</span><span class="boring"> height: 50,
</span><span class="boring"> };
</span><span class="boring"> let rect2 = Rectangle {
</span><span class="boring"> width: 10,
</span><span class="boring"> height: 40,
</span><span class="boring"> };
</span><span class="boring"> let rect3 = Rectangle {
</span><span class="boring"> width: 60,
</span><span class="boring"> height: 45,
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> println!("Can rect1 hold rect2? {}", rect1.can_hold(&amp;rect2));
</span><span class="boring"> println!("Can rect1 hold rect3? {}", rect1.can_hold(&amp;rect3));
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 5-15<code>Rectangle</code> 上实现 <code>can_hold</code> 方法,它获取另一个 <code>Rectangle</code> 实例作为参数</span></p>
<p>如果结合示例 5-14 的 <code>main</code> 函数来运行,就会看到期望的输出。在方法签名中,可以在 <code>self</code> 后增加多个参数,而且这些参数就像函数中的参数一样工作。</p>
<h3 id="关联函数"><a class="header" href="#关联函数">关联函数</a></h3>
<p>所有在 <code>impl</code> 块中定义的函数被称为 <strong>关联函数</strong><em>associated functions</em>),因为它们与 <code>impl</code> 后面命名的类型相关。我们可以定义不以 <code>self</code> 为第一参数的关联函数(因此不是方法),因为它们并不作用于一个结构体的实例。我们已经使用了一个这样的函数:在 <code>String</code> 类型上定义的 <code>String::from</code> 函数。</p>
<p>不是方法的关联函数经常被用作返回一个结构体新实例的构造函数。这些函数的名称通常为 <code>new</code> ,但 <code>new</code> 并不是一个关键字。例如我们可以提供一个叫做 <code>square</code> 关联函数,它接受一个维度参数并且同时作为宽和高,这样可以更轻松的创建一个正方形 <code>Rectangle</code> 而不必指定两次同样的值:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>impl Rectangle {
fn square(size: u32) -&gt; Self {
Self {
width: size,
height: size,
}
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let sq = Rectangle::square(3);
</span><span class="boring">}</span></code></pre></pre>
<p>关键字 <code>Self</code> 在函数的返回类型中代指在 <code>impl</code> 关键字后出现的类型,在这里是 <code>Rectangle</code></p>
<p>使用结构体名和 <code>::</code> 语法来调用这个关联函数:比如 <code>let sq = Rectangle::square(3);</code>。这个函数位于结构体的命名空间中:<code>::</code> 语法用于关联函数和模块创建的命名空间。<a href="ch07-02-defining-modules-to-control-scope-and-privacy.html">第七章</a>会讲到模块。</p>
<h3 id="多个-impl-块"><a class="header" href="#多个-impl-块">多个 <code>impl</code></a></h3>
<p>每个结构体都允许拥有多个 <code>impl</code> 块。例如,示例 5-16 中的代码等同于示例 5-15但每个方法有其自己的 <code>impl</code> 块。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.width * self.height
}
}
impl Rectangle {
fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.width &gt; other.width &amp;&amp; self.height &gt; other.height
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let rect1 = Rectangle {
</span><span class="boring"> width: 30,
</span><span class="boring"> height: 50,
</span><span class="boring"> };
</span><span class="boring"> let rect2 = Rectangle {
</span><span class="boring"> width: 10,
</span><span class="boring"> height: 40,
</span><span class="boring"> };
</span><span class="boring"> let rect3 = Rectangle {
</span><span class="boring"> width: 60,
</span><span class="boring"> height: 45,
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> println!("Can rect1 hold rect2? {}", rect1.can_hold(&amp;rect2));
</span><span class="boring"> println!("Can rect1 hold rect3? {}", rect1.can_hold(&amp;rect3));
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 5-16使用多个 <code>impl</code> 块重写示例 5-15</span></p>
<p>这里没有理由将这些方法分散在多个 <code>impl</code> 块中,不过这是有效的语法。第十章讨论泛型和 trait 时会看到实用的多 <code>impl</code> 块的用例。</p>
<h2 id="总结-4"><a class="header" href="#总结-4">总结</a></h2>
<p>结构体让你可以创建出在你的领域中有意义的自定义类型。通过结构体,我们可以将相关联的数据片段联系起来并命名它们,这样可以使得代码更加清晰。在 <code>impl</code> 块中,你可以定义与你的类型相关联的函数,而方法是一种相关联的函数,让你指定结构体的实例所具有的行为。</p>
<p>但结构体并不是创建自定义类型的唯一方法:让我们转向 Rust 的枚举功能,为你的工具箱再添一个工具。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="枚举和模式匹配"><a class="header" href="#枚举和模式匹配">枚举和模式匹配</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch06-00-enums.md">ch06-00-enums.md</a>
<br>
commit bb7e429ad6b59d9a0c37db7434976364cbb9c6da</p>
</blockquote>
<p>本章介绍 <strong>枚举</strong><em>enumerations</em>),也被称作 <em>enums</em>。枚举允许你通过列举可能的 <strong>成员</strong><em>variants</em>)来定义一个类型。首先,我们会定义并使用一个枚举来展示它是如何连同数据一起编码信息的。接下来,我们会探索一个特别有用的枚举,叫做 <code>Option</code>,它代表一个值要么是某个值要么什么都不是。然后会讲到在 <code>match</code> 表达式中用模式匹配,针对不同的枚举值编写相应要执行的代码。最后会介绍 <code>if let</code>,另一个简洁方便处理代码中枚举的结构。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="枚举的定义"><a class="header" href="#枚举的定义">枚举的定义</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch06-01-defining-an-enum.md">ch06-01-defining-an-enum.md</a>
<br>
commit bb7e429ad6b59d9a0c37db7434976364cbb9c6da</p>
</blockquote>
<p>结构体给予你将字段和数据聚合在一起的方法,像 <code>Rectangle</code> 结构体有 <code>width</code><code>height</code> 两个字段。而枚举给予你一个途径去声明某个值是一个集合中的一员。比如,我们想让 <code>Rectangle</code> 是一些形状的集合,包含 <code>Circle</code><code>Triangle</code> 。为了做到这个Rust 提供了枚举类型。</p>
<p>让我们看看一个需要诉诸于代码的场景,来考虑为何此时使用枚举更为合适且实用。假设我们要处理 IP 地址。目前被广泛使用的两个主要 IP 标准IPv4version four和 IPv6version six。这是我们的程序可能会遇到的所有可能的 IP 地址类型:所以可以 <strong>枚举</strong> 出所有可能的值,这也正是此枚举名字的由来。</p>
<p>任何一个 IP 地址要么是 IPv4 的要么是 IPv6 的而且不能两者都是。IP 地址的这个特性使得枚举数据结构非常适合这个场景因为枚举值只可能是其中一个成员。IPv4 和 IPv6 从根本上讲仍是 IP 地址,所以当代码在处理适用于任何类型的 IP 地址的场景时应该把它们当作相同的类型。</p>
<p>可以通过在代码中定义一个 <code>IpAddrKind</code> 枚举来表现这个概念并列出可能的 IP 地址类型,<code>V4</code><code>V6</code>。这被称为枚举的 <strong>成员</strong><em>variants</em></p>
<pre><pre class="playground"><code class="language-rust edition2021">enum IpAddrKind {
V4,
V6,
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let four = IpAddrKind::V4;
</span><span class="boring"> let six = IpAddrKind::V6;
</span><span class="boring">
</span><span class="boring"> route(IpAddrKind::V4);
</span><span class="boring"> route(IpAddrKind::V6);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn route(ip_kind: IpAddrKind) {}</span></code></pre></pre>
<p>现在 <code>IpAddrKind</code> 就是一个可以在代码中使用的自定义数据类型了。</p>
<h3 id="枚举值"><a class="header" href="#枚举值">枚举值</a></h3>
<p>可以像这样创建 <code>IpAddrKind</code> 两个不同成员的实例:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">enum IpAddrKind {
</span><span class="boring"> V4,
</span><span class="boring"> V6,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span> let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
<span class="boring">
</span><span class="boring"> route(IpAddrKind::V4);
</span><span class="boring"> route(IpAddrKind::V6);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn route(ip_kind: IpAddrKind) {}</span></code></pre></pre>
<p>注意枚举的成员位于其标识符的命名空间中,并使用两个冒号分开。这么设计的益处是现在 <code>IpAddrKind::V4</code><code>IpAddrKind::V6</code> 都是 <code>IpAddrKind</code> 类型的。例如,接着可以定义一个函数来接收任何 <code>IpAddrKind</code>类型的参数:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">enum IpAddrKind {
</span><span class="boring"> V4,
</span><span class="boring"> V6,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let four = IpAddrKind::V4;
</span><span class="boring"> let six = IpAddrKind::V6;
</span><span class="boring">
</span><span class="boring"> route(IpAddrKind::V4);
</span><span class="boring"> route(IpAddrKind::V6);
</span><span class="boring">}
</span><span class="boring">
</span>fn route(ip_kind: IpAddrKind) {}</code></pre></pre>
<p>现在可以使用任一成员来调用这个函数:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">enum IpAddrKind {
</span><span class="boring"> V4,
</span><span class="boring"> V6,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let four = IpAddrKind::V4;
</span><span class="boring"> let six = IpAddrKind::V6;
</span><span class="boring">
</span> route(IpAddrKind::V4);
route(IpAddrKind::V6);
<span class="boring">}
</span><span class="boring">
</span><span class="boring">fn route(ip_kind: IpAddrKind) {}</span></code></pre></pre>
<p>使用枚举甚至还有更多优势。进一步考虑一下我们的 IP 地址类型,目前没有一个存储实际 IP 地址 <strong>数据</strong> 的方法;只知道它是什么 <strong>类型</strong> 的。考虑到已经在第五章学习过结构体了,你可能会像示例 6-1 那样处理这个问题:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> enum IpAddrKind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrKind,
address: String,
}
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 6-1将 IP 地址的数据和 <code>IpAddrKind</code> 成员存储在一个 <code>struct</code></span></p>
<p>这里我们定义了一个有两个字段的结构体 <code>IpAddr</code><code>IpAddrKind</code>(之前定义的枚举)类型的 <code>kind</code> 字段和 <code>String</code> 类型 <code>address</code> 字段。我们有这个结构体的两个实例。第一个,<code>home</code>,它的 <code>kind</code> 的值是 <code>IpAddrKind::V4</code> 与之相关联的地址数据是 <code>127.0.0.1</code>。第二个实例,<code>loopback</code><code>kind</code> 的值是 <code>IpAddrKind</code> 的另一个成员,<code>V6</code>,关联的地址是 <code>::1</code>。我们使用了一个结构体来将 <code>kind</code><code>address</code> 打包在一起,现在枚举成员就与值相关联了。</p>
<p>我们可以使用一种更简洁的方式来表达相同的概念,仅仅使用枚举并将数据直接放进每一个枚举成员而不是将枚举作为结构体的一部分。<code>IpAddr</code> 枚举的新定义表明了 <code>V4</code><code>V6</code> 成员都关联了 <code>String</code> 值:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));
<span class="boring">}</span></code></pre></pre>
<p>我们直接将数据附加到枚举的每个成员上,这样就不需要一个额外的结构体了。这里也很容易看出枚举工作的另一个细节:每一个我们定义的枚举成员的名字也变成了一个构建枚举的实例的函数。也就是说,<code>IpAddr::V4()</code> 是一个获取 <code>String</code> 参数并返回 <code>IpAddr</code> 类型实例的函数调用。作为定义枚举的结果,这些构造函数会自动被定义。</p>
<p>用枚举替代结构体还有另一个优势每个成员可以处理不同类型和数量的数据。IPv4 版本的 IP 地址总是含有四个值在 0 和 255 之间的数字部分。如果我们想要将 <code>V4</code> 地址存储为四个 <code>u8</code> 值而 <code>V6</code> 地址仍然表现为一个 <code>String</code>,这就不能使用结构体了。枚举则可以轻易的处理这个情况:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
<span class="boring">}</span></code></pre></pre>
<p>这些代码展示了使用枚举来存储两种不同 IP 地址的几种可能的选择。然而,事实证明存储和编码 IP 地址实在是太常见了<a href="https://doc.rust-lang.org/std/net/enum.IpAddr.html">以致标准库提供了一个开箱即用的定义!</a><!-- ignore -->让我们看看标准库是如何定义 <code>IpAddr</code> 的:它正有着跟我们定义和使用的一样的枚举和成员,不过它将成员中的地址数据嵌入到了两个不同形式的结构体中,它们对不同的成员的定义是不同的:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct Ipv4Addr {
// --snip--
}
struct Ipv6Addr {
// --snip--
}
enum IpAddr {
V4(Ipv4Addr),
V6(Ipv6Addr),
}
<span class="boring">}</span></code></pre></pre>
<p>这些代码展示了可以将任意类型的数据放入枚举成员中:例如字符串、数字类型或者结构体。甚至可以包含另一个枚举!另外,标准库中的类型通常并不比你设想出来的要复杂多少。</p>
<p>注意虽然标准库中包含一个 <code>IpAddr</code> 的定义,仍然可以创建和使用我们自己的定义而不会有冲突,因为我们并没有将标准库中的定义引入作用域。第七章会讲到如何导入类型。</p>
<p>来看看示例 6-2 中的另一个枚举的例子:它的成员中内嵌了多种多样的类型:</p>
<pre><pre class="playground"><code class="language-rust edition2021">enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 6-2一个 <code>Message</code> 枚举,其每个成员都存储了不同数量和类型的值</span></p>
<p>这个枚举有四个含有不同类型的成员:</p>
<ul>
<li><code>Quit</code> 没有关联任何数据。</li>
<li><code>Move</code> 类似结构体包含命名字段。</li>
<li><code>Write</code> 包含单独一个 <code>String</code></li>
<li><code>ChangeColor</code> 包含三个 <code>i32</code></li>
</ul>
<p>定义一个如示例 6-2 中所示那样的有关联值的枚举的方式和定义多个不同类型的结构体的方式很相像,除了枚举不使用 <code>struct</code> 关键字以及其所有成员都被组合在一起位于 <code>Message</code> 类型下。如下这些结构体可以包含与之前枚举成员中相同的数据:</p>
<pre><pre class="playground"><code class="language-rust edition2021">struct QuitMessage; // 类单元结构体
struct MoveMessage {
x: i32,
y: i32,
}
struct WriteMessage(String); // 元组结构体
struct ChangeColorMessage(i32, i32, i32); // 元组结构体
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p>不过,如果我们使用不同的结构体,由于它们都有不同的类型,我们将不能像使用示例 6-2 中定义的 <code>Message</code> 枚举那样,轻易的定义一个能够处理这些不同类型的结构体的函数,因为枚举是单独一个类型。</p>
<p>结构体和枚举还有另一个相似点:就像可以使用 <code>impl</code> 来为结构体定义方法那样,也可以在枚举上定义方法。这是一个定义于我们 <code>Message</code> 枚举上的叫做 <code>call</code> 的方法:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> enum Message {
</span><span class="boring"> Quit,
</span><span class="boring"> Move { x: i32, y: i32 },
</span><span class="boring"> Write(String),
</span><span class="boring"> ChangeColor(i32, i32, i32),
</span><span class="boring"> }
</span><span class="boring">
</span> impl Message {
fn call(&amp;self) {
// 在这里定义方法体
}
}
let m = Message::Write(String::from("hello"));
m.call();
<span class="boring">}</span></code></pre></pre>
<p>方法体使用了 <code>self</code> 来获取调用方法的值。这个例子中,创建了一个值为 <code>Message::Write(String::from("hello"))</code> 的变量 <code>m</code>,而且这就是当 <code>m.call()</code> 运行时 <code>call</code> 方法中的 <code>self</code> 的值。</p>
<p>让我们看看标准库中的另一个非常常见且实用的枚举:<code>Option</code></p>
<h3 id="option-枚举和其相对于空值的优势"><a class="header" href="#option-枚举和其相对于空值的优势"><code>Option</code> 枚举和其相对于空值的优势</a></h3>
<p>这一部分会分析一个 <code>Option</code> 的案例,<code>Option</code> 是标准库定义的另一个枚举。<code>Option</code> 类型应用广泛因为它编码了一个非常普遍的场景,即一个值要么有值要么没值。</p>
<p>例如,如果请求一个非空列表的第一项,会得到一个值,如果请求一个空的列表,就什么也不会得到。从类型系统的角度来表达这个概念就意味着编译器需要检查是否处理了所有应该处理的情况,这样就可以避免在其他编程语言中非常常见的 bug。</p>
<p>编程语言的设计经常要考虑包含哪些功能但考虑排除哪些功能也很重要。Rust 并没有很多其他语言中有的空值功能。<strong>空值</strong><em>Null</em> )是一个值,它代表没有值。在有空值的语言中,变量总是这两种状态之一:空值和非空值。</p>
<p>Tony Hoarenull 的发明者,在他 2009 年的演讲 “Null References: The Billion Dollar Mistake” 中曾经说到:</p>
<blockquote>
<p>I call it my billion-dollar mistake. At that time, I was designing the first
comprehensive type system for references in an object-oriented language. My
goal was to ensure that all use of references should be absolutely safe, with
checking performed automatically by the compiler. But I couldn't resist the
temptation to put in a null reference, simply because it was so easy to
implement. This has led to innumerable errors, vulnerabilities, and system
crashes, which have probably caused a billion dollars of pain and damage in
the last forty years.</p>
<p>我称之为我十亿美元的错误。当时,我在为一个面向对象语言设计第一个综合性的面向引用的类型系统。我的目标是通过编译器的自动检查来保证所有引用的使用都应该是绝对安全的。不过我未能抵抗住引入一个空引用的诱惑,仅仅是因为它是这么的容易实现。这引发了无数错误、漏洞和系统崩溃,在之后的四十多年中造成了数十亿美元的苦痛和伤害。</p>
</blockquote>
<p>空值的问题在于当你尝试像一个非空值那样使用一个空值,会出现某种形式的错误。因为空和非空的属性无处不在,非常容易出现这类错误。</p>
<p>然而,空值尝试表达的概念仍然是有意义的:空值是一个因为某种原因目前无效或缺失的值。</p>
<p>问题不在于概念而在于具体的实现。为此Rust 并没有空值,不过它确实拥有一个可以编码存在或不存在概念的枚举。这个枚举是 <code>Option&lt;T&gt;</code>,而且它<a href="https://doc.rust-lang.org/std/option/enum.Option.html">定义于标准库中</a><!-- ignore -->,如下:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>enum Option&lt;T&gt; {
None,
Some(T),
}
<span class="boring">}</span></code></pre></pre>
<p><code>Option&lt;T&gt;</code> 枚举是如此有用以至于它甚至被包含在了 prelude 之中,你不需要将其显式引入作用域。另外,它的成员也是如此,可以不需要 <code>Option::</code> 前缀来直接使用 <code>Some</code><code>None</code>。即便如此 <code>Option&lt;T&gt;</code> 也仍是常规的枚举,<code>Some(T)</code><code>None</code> 仍是 <code>Option&lt;T&gt;</code> 的成员。</p>
<p><code>&lt;T&gt;</code> 语法是一个我们还未讲到的 Rust 功能。它是一个泛型类型参数,第十章会更详细的讲解泛型。目前,所有你需要知道的就是 <code>&lt;T&gt;</code> 意味着 <code>Option</code> 枚举的 <code>Some</code> 成员可以包含任意类型的数据,同时每一个用于 <code>T</code> 位置的具体类型使得 <code>Option&lt;T&gt;</code> 整体作为不同的类型。这里是一些包含数字类型和字符串类型 <code>Option</code> 值的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let some_number = Some(5);
let some_char = Some('e');
let absent_number: Option&lt;i32&gt; = None;
<span class="boring">}</span></code></pre></pre>
<p><code>some_number</code> 的类型是 <code>Option&lt;i32&gt;</code><code>some_char</code> 的类型是 <code>Option&lt;char&gt;</code>,这(与 <code>some_number</code>)是一个不同的类型。因为我们在 <code>Some</code> 成员中指定了值Rust 可以推断其类型。对于 <code>absent_number</code>Rust 需要我们指定 <code>Option</code> 整体的类型,因为编译器只通过 <code>None</code> 值无法推断出 <code>Some</code> 成员保存的值的类型。这里我们告诉 Rust 希望 <code>absent_number</code><code>Option&lt;i32&gt;</code> 类型的。</p>
<p>当有一个 <code>Some</code> 值时,我们就知道存在一个值,而这个值保存在 <code>Some</code> 中。当有个 <code>None</code> 值时,在某种意义上,它跟空值具有相同的意义:并没有一个有效的值。那么,<code>Option&lt;T&gt;</code> 为什么就比空值要好呢?</p>
<p>简而言之,因为 <code>Option&lt;T&gt;</code><code>T</code>(这里 <code>T</code> 可以是任何类型)是不同的类型,编译器不允许像一个肯定有效的值那样使用 <code>Option&lt;T&gt;</code>。例如,这段代码不能编译,因为它尝试将 <code>Option&lt;i8&gt;</code><code>i8</code> 相加:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let x: i8 = 5;
let y: Option&lt;i8&gt; = Some(5);
let sum = x + y;
<span class="boring">}</span></code></pre>
<p>如果运行这些代码,将得到类似这样的错误信息:</p>
<pre><code class="language-console">$ cargo run
Compiling enums v0.1.0 (file:///projects/enums)
error[E0277]: cannot add `Option&lt;i8&gt;` to `i8`
--&gt; src/main.rs:5:17
|
5 | let sum = x + y;
| ^ no implementation for `i8 + Option&lt;i8&gt;`
|
= help: the trait `Add&lt;Option&lt;i8&gt;&gt;` is not implemented for `i8`
= help: the following other types implement trait `Add&lt;Rhs&gt;`:
`&amp;'a i8` implements `Add&lt;i8&gt;`
`&amp;i8` implements `Add&lt;&amp;i8&gt;`
`i8` implements `Add&lt;&amp;i8&gt;`
`i8` implements `Add`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `enums` (bin "enums") due to 1 previous error
</code></pre>
<p>很好!事实上,错误信息意味着 Rust 不知道该如何将 <code>Option&lt;i8&gt;</code><code>i8</code> 相加,因为它们的类型不同。当在 Rust 中拥有一个像 <code>i8</code> 这样类型的值时,编译器确保它总是有一个有效的值。我们可以自信使用而无需做空值检查。只有当使用 <code>Option&lt;i8&gt;</code>(或者任何用到的类型)的时候需要担心可能没有值,而编译器会确保我们在使用值之前处理了为空的情况。</p>
<p>换句话说,在对 <code>Option&lt;T&gt;</code> 进行运算之前必须将其转换为 <code>T</code>。通常这能帮助我们捕获到空值最常见的问题之一:假设某值不为空但实际上为空的情况。</p>
<p>消除了错误地假设一个非空值的风险,会让你对代码更加有信心。为了拥有一个可能为空的值,你必须要显式的将其放入对应类型的 <code>Option&lt;T&gt;</code> 中。接着,当使用这个值时,必须明确的处理值为空的情况。只要一个值不是 <code>Option&lt;T&gt;</code> 类型,你就 <strong>可以</strong> 安全的认定它的值不为空。这是 Rust 的一个经过深思熟虑的设计决策,来限制空值的泛滥以增加 Rust 代码的安全性。</p>
<p>那么当有一个 <code>Option&lt;T&gt;</code> 的值时,如何从 <code>Some</code> 成员中取出 <code>T</code> 的值来使用它呢?<code>Option&lt;T&gt;</code> 枚举拥有大量用于各种情况的方法:你可以查看<a href="https://doc.rust-lang.org/std/option/enum.Option.html">它的文档</a><!-- ignore -->。熟悉 <code>Option&lt;T&gt;</code> 的方法将对你的 Rust 之旅非常有用。</p>
<p>总的来说,为了使用 <code>Option&lt;T&gt;</code> 值,需要编写处理每个成员的代码。你想要一些代码只当拥有 <code>Some(T)</code> 值时运行,允许这些代码使用其中的 <code>T</code>。也希望一些代码只在值为 <code>None</code> 时运行,这些代码并没有一个可用的 <code>T</code> 值。<code>match</code> 表达式就是这么一个处理枚举的控制流结构:它会根据枚举的成员运行不同的代码,这些代码可以使用匹配到的值中的数据。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="match-控制流结构"><a class="header" href="#match-控制流结构"><code>match</code> 控制流结构</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch06-02-match.md">ch06-02-match.md</a>
<br>
commit 3962c0224b274e2358e0acf06443af64df115359</p>
</blockquote>
<p>Rust 有一个叫做 <code>match</code> 的极为强大的控制流运算符,它允许我们将一个值与一系列的模式相比较,并根据相匹配的模式执行相应代码。模式可由字面值、变量、通配符和许多其他内容构成;<a href="ch19-00-patterns.html">第十九章</a>会涉及到所有不同种类的模式以及它们的作用。<code>match</code> 的力量来源于模式的表现力以及编译器检查,它确保了所有可能的情况都得到处理。</p>
<p>可以把 <code>match</code> 表达式想象成某种硬币分类器:硬币滑入有着不同大小孔洞的轨道,每一个硬币都会掉入符合它大小的孔洞。同样地,值也会通过 <code>match</code> 的每一个模式,并且在遇到第一个 “符合” 的模式时,值会进入相关联的代码块并在执行中被使用。</p>
<p>因为刚刚提到了硬币,让我们用它们来作为一个使用 <code>match</code> 的例子!我们可以编写一个函数来获取一个未知的硬币,并以一种类似验钞机的方式,确定它是何种硬币并返回它的美分值,如示例 6-3 中所示。</p>
<pre><pre class="playground"><code class="language-rust edition2021">enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -&gt; u8 {
match coin {
Coin::Penny =&gt; 1,
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter =&gt; 25,
}
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 6-3一个枚举和一个以枚举成员作为模式的 <code>match</code> 表达式</span></p>
<p>拆开 <code>value_in_cents</code> 函数中的 <code>match</code> 来看。首先,我们列出 <code>match</code> 关键字后跟一个表达式,在这个例子中是 <code>coin</code> 的值。这看起来非常像 <code>if</code> 所使用的条件表达式,不过这里有一个非常大的区别:对于 <code>if</code>,表达式必须返回一个布尔值,而这里它可以是任何类型的。例子中的 <code>coin</code> 的类型是示例 6-3 中定义的 <code>Coin</code> 枚举。</p>
<p>接下来是 <code>match</code> 的分支。一个分支有两个部分:一个模式和一些代码。第一个分支的模式是值 <code>Coin::Penny</code> 而之后的 <code>=&gt;</code> 运算符将模式和将要运行的代码分开。这里的代码就仅仅是值 <code>1</code>。每一个分支之间使用逗号分隔。</p>
<p><code>match</code> 表达式执行时,它将结果值按顺序与每一个分支的模式相比较。如果模式匹配了这个值,这个模式相关联的代码将被执行。如果模式并不匹配这个值,将继续执行下一个分支,非常类似一个硬币分类器。可以拥有任意多的分支:示例 6-3 中的 <code>match</code> 有四个分支。</p>
<p>每个分支相关联的代码是一个表达式,而表达式的结果值将作为整个 <code>match</code> 表达式的返回值。</p>
<p>如果分支代码较短的话通常不使用大括号,正如示例 6-3 中的每个分支都只是返回一个值。如果想要在分支中运行多行代码,可以使用大括号,而分支后的逗号是可选的。例如,如下代码在每次使用<code>Coin::Penny</code> 调用时都会打印出 “Lucky penny!”,同时仍然返回代码块最后的值,<code>1</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">enum Coin {
</span><span class="boring"> Penny,
</span><span class="boring"> Nickel,
</span><span class="boring"> Dime,
</span><span class="boring"> Quarter,
</span><span class="boring">}
</span><span class="boring">
</span>fn value_in_cents(coin: Coin) -&gt; u8 {
match coin {
Coin::Penny =&gt; {
println!("Lucky penny!");
1
}
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter =&gt; 25,
}
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<h3 id="绑定值的模式"><a class="header" href="#绑定值的模式">绑定值的模式</a></h3>
<p>匹配分支的另一个有用的功能是可以绑定匹配的模式的部分值。这也就是如何从枚举成员中提取值的。</p>
<p>作为一个例子让我们修改枚举的一个成员来存放数据。1999 年到 2008 年间,美国在 25 美分的硬币的一侧为 50 个州的每一个都印刷了不同的设计。其他的硬币都没有这种区分州的设计,所以只有这些 25 美分硬币有特殊的价值。可以将这些信息加入我们的 <code>enum</code>,通过改变 <code>Quarter</code> 成员来包含一个 <code>State</code> 值,示例 6-4 中完成了这些修改:</p>
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)] // 这样可以立刻看到州的名称
enum UsState {
Alabama,
Alaska,
// --snip--
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 6-4<code>Quarter</code> 成员也存放了一个 <code>UsState</code> 值的 <code>Coin</code> 枚举</span></p>
<p>想象一下我们的一个朋友尝试收集所有 50 个州的 25 美分硬币。在根据硬币类型分类零钱的同时,也可以报告出每个 25 美分硬币所对应的州名称,这样如果我们的朋友没有的话,他可以将其加入收藏。</p>
<p>在这些代码的匹配表达式中,我们在匹配 <code>Coin::Quarter</code> 成员的分支的模式中增加了一个叫做 <code>state</code> 的变量。当匹配到 <code>Coin::Quarter</code> 时,变量 <code>state</code> 将会绑定 25 美分硬币所对应州的值。接着在那个分支的代码中使用 <code>state</code>,如下:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#[derive(Debug)]
</span><span class="boring">enum UsState {
</span><span class="boring"> Alabama,
</span><span class="boring"> Alaska,
</span><span class="boring"> // --snip--
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">enum Coin {
</span><span class="boring"> Penny,
</span><span class="boring"> Nickel,
</span><span class="boring"> Dime,
</span><span class="boring"> Quarter(UsState),
</span><span class="boring">}
</span><span class="boring">
</span>fn value_in_cents(coin: Coin) -&gt; u8 {
match coin {
Coin::Penny =&gt; 1,
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter(state) =&gt; {
println!("State quarter from {state:?}!");
25
}
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> value_in_cents(Coin::Quarter(UsState::Alaska));
</span><span class="boring">}</span></code></pre></pre>
<p>如果调用 <code>value_in_cents(Coin::Quarter(UsState::Alaska))</code><code>coin</code> 将是 <code>Coin::Quarter(UsState::Alaska)</code>。当将值与每个分支相比较时,没有分支会匹配,直到遇到 <code>Coin::Quarter(state)</code>。这时,<code>state</code> 绑定的将会是值 <code>UsState::Alaska</code>。接着就可以在 <code>println!</code> 表达式中使用这个绑定了,像这样就可以获取 <code>Coin</code> 枚举的 <code>Quarter</code> 成员中内部的州的值。</p>
<h3 id="匹配-optiont"><a class="header" href="#匹配-optiont">匹配 <code>Option&lt;T&gt;</code></a></h3>
<p>我们在之前的部分中使用 <code>Option&lt;T&gt;</code> 时,是为了从 <code>Some</code> 中取出其内部的 <code>T</code> 值;我们还可以像处理 <code>Coin</code> 枚举那样使用 <code>match</code> 处理 <code>Option&lt;T&gt;</code>!只不过这回比较的不再是硬币,而是 <code>Option&lt;T&gt;</code> 的成员,但 <code>match</code> 表达式的工作方式保持不变。</p>
<p>比如我们想要编写一个函数,它获取一个 <code>Option&lt;i32&gt;</code> ,如果其中含有一个值,将其加一。如果其中没有值,函数应该返回 <code>None</code> 值,而不尝试执行任何操作。</p>
<p>得益于 <code>match</code>,编写这个函数非常简单,它将看起来像示例 6-5 中这样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
match x {
None =&gt; None,
Some(i) =&gt; Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 6-5一个在 <code>Option&lt;i32&gt;</code> 上使用 <code>match</code> 表达式的函数</span></p>
<h4 id="匹配-somet"><a class="header" href="#匹配-somet">匹配 <code>Some(T)</code></a></h4>
<p>让我们更仔细地检查 <code>plus_one</code> 的第一行操作。当调用 <code>plus_one(five)</code> 时,<code>plus_one</code> 函数体中的 <code>x</code> 将会是值 <code>Some(5)</code>。接着将其与每个分支比较。</p>
<pre><code class="language-rust ignore"><span class="boring">fn main() {
</span><span class="boring"> fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
</span><span class="boring"> match x {
</span> None =&gt; None,
<span class="boring"> Some(i) =&gt; Some(i + 1),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let five = Some(5);
</span><span class="boring"> let six = plus_one(five);
</span><span class="boring"> let none = plus_one(None);
</span><span class="boring">}</span></code></pre>
<p><code>Some(5)</code> 并不匹配模式 <code>None</code>,所以继续进行下一个分支。</p>
<pre><code class="language-rust ignore"><span class="boring">fn main() {
</span><span class="boring"> fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
</span><span class="boring"> match x {
</span><span class="boring"> None =&gt; None,
</span> Some(i) =&gt; Some(i + 1),
<span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let five = Some(5);
</span><span class="boring"> let six = plus_one(five);
</span><span class="boring"> let none = plus_one(None);
</span><span class="boring">}</span></code></pre>
<p><code>Some(5)</code><code>Some(i)</code> 匹配吗?当然匹配!它们是相同的成员。<code>i</code> 绑定了 <code>Some</code> 中包含的值,所以 <code>i</code> 的值是 <code>5</code>。接着匹配分支的代码被执行,所以我们将 <code>i</code> 的值加一并返回一个含有值 <code>6</code> 的新 <code>Some</code></p>
<p>接着考虑下示例 6-5 中 <code>plus_one</code> 的第二个调用,这里 <code>x</code><code>None</code>。我们进入 <code>match</code> 并与第一个分支相比较。</p>
<pre><code class="language-rust ignore"><span class="boring">fn main() {
</span><span class="boring"> fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
</span><span class="boring"> match x {
</span> None =&gt; None,
<span class="boring"> Some(i) =&gt; Some(i + 1),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let five = Some(5);
</span><span class="boring"> let six = plus_one(five);
</span><span class="boring"> let none = plus_one(None);
</span><span class="boring">}</span></code></pre>
<p>匹配上了!这里没有值来加一,所以程序结束并返回 <code>=&gt;</code> 右侧的值 <code>None</code>,因为第一个分支就匹配到了,其他的分支将不再比较。</p>
<p><code>match</code> 与枚举相结合在很多场景中都是有用的。你会在 Rust 代码中看到很多这样的模式:<code>match</code> 一个枚举,绑定其中的值到一个变量,接着根据其值执行代码。这在一开始有点复杂,不过一旦习惯了,你会希望所有语言都拥有它!这一直是用户的最爱。</p>
<h3 id="匹配是穷尽的"><a class="header" href="#匹配是穷尽的">匹配是穷尽的</a></h3>
<p><code>match</code> 还有另一方面需要讨论:这些分支必须覆盖了所有的可能性。考虑一下 <code>plus_one</code> 函数的这个版本,它有一个 bug 并不能编译:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
match x {
Some(i) =&gt; Some(i + 1),
}
}
<span class="boring">
</span><span class="boring"> let five = Some(5);
</span><span class="boring"> let six = plus_one(five);
</span><span class="boring"> let none = plus_one(None);
</span><span class="boring">}</span></code></pre>
<p>我们没有处理 <code>None</code> 的情况,所以这些代码会造成一个 bug。幸运的是这是一个 Rust 知道如何处理的 bug。如果尝试编译这段代码会得到这个错误</p>
<pre><code class="language-console">$ cargo run
Compiling enums v0.1.0 (file:///projects/enums)
error[E0004]: non-exhaustive patterns: `None` not covered
--&gt; src/main.rs:3:15
|
3 | match x {
| ^ pattern `None` not covered
|
note: `Option&lt;i32&gt;` defined here
--&gt; /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/core/src/option.rs:574:1
::: /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/core/src/option.rs:578:5
|
= note: not covered
= note: the matched value is of type `Option&lt;i32&gt;`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
4 ~ Some(i) =&gt; Some(i + 1),
5 ~ None =&gt; todo!(),
|
For more information about this error, try `rustc --explain E0004`.
error: could not compile `enums` (bin "enums") due to 1 previous error
</code></pre>
<p>Rust 知道我们没有覆盖所有可能的情况甚至知道哪些模式被忘记了Rust 中的匹配是 <strong>穷尽的</strong><em>exhaustive</em>):必须穷举到最后的可能性来使代码有效。特别的在这个 <code>Option&lt;T&gt;</code> 的例子中Rust 防止我们忘记明确的处理 <code>None</code> 的情况,这让我们免于假设拥有一个实际上为空的值,从而使之前提到的价值亿万的错误不可能发生。</p>
<h3 id="通配模式和-_-占位符"><a class="header" href="#通配模式和-_-占位符">通配模式和 <code>_</code> 占位符</a></h3>
<p>让我们看一个例子,我们希望对一些特定的值采取特殊操作,而对其他的值采取默认操作。想象我们正在玩一个游戏,如果你掷出骰子的值为 3角色不会移动而是会得到一顶新奇的帽子。如果你掷出了 7你的角色将失去新奇的帽子。对于其他的数值你的角色会在棋盘上移动相应的格子。这是一个实现了上述逻辑的 <code>match</code>,骰子的结果是硬编码而不是一个随机值,其他的逻辑部分使用了没有函数体的函数来表示,实现它们超出了本例的范围:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let dice_roll = 9;
match dice_roll {
3 =&gt; add_fancy_hat(),
7 =&gt; remove_fancy_hat(),
other =&gt; move_player(other),
}
fn add_fancy_hat() {}
fn remove_fancy_hat() {}
fn move_player(num_spaces: u8) {}
<span class="boring">}</span></code></pre></pre>
<p>对于前两个分支,匹配模式是字面值 <code>3</code><code>7</code>,最后一个分支则涵盖了所有其他可能的值,模式是我们命名为 <code>other</code> 的一个变量。<code>other</code> 分支的代码通过将其传递给 <code>move_player</code> 函数来使用这个变量。</p>
<p>即使我们没有列出 <code>u8</code> 所有可能的值,这段代码依然能够编译,因为最后一个模式将匹配所有未被特殊列出的值。这种通配模式满足了 <code>match</code> 必须被穷尽的要求。请注意我们必须将通配分支放在最后因为模式是按顺序匹配的。如果我们在通配分支后添加其他分支Rust 将会警告我们,因为此后的分支永远不会被匹配到。</p>
<p>Rust 还提供了一个模式,当我们不想使用通配模式获取的值时,请使用 <code>_</code> ,这是一个特殊的模式,可以匹配任意值而不绑定到该值。这告诉 Rust 我们不会使用这个值,所以 Rust 也不会警告我们存在未使用的变量。</p>
<p>让我们改变游戏规则:现在,当你掷出的值不是 3 或 7 的时候,你必须再次掷出。这种情况下我们不需要使用这个值,所以我们改动代码使用 <code>_</code> 来替代变量 <code>other</code> </p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let dice_roll = 9;
match dice_roll {
3 =&gt; add_fancy_hat(),
7 =&gt; remove_fancy_hat(),
_ =&gt; reroll(),
}
fn add_fancy_hat() {}
fn remove_fancy_hat() {}
fn reroll() {}
<span class="boring">}</span></code></pre></pre>
<p>这个例子也满足穷举性要求,因为我们在最后一个分支中明确地忽略了其他的值。我们没有忘记处理任何东西。</p>
<p>最后,让我们再次改变游戏规则,如果你掷出 3 或 7 以外的值,你的回合将无事发生。我们可以使用单元值(在<a href="ch03-02-data-types.html#%E5%85%83%E7%BB%84%E7%B1%BB%E5%9E%8B">“元组类型”</a><!-- ignore -->一节中提到的空元组)作为 <code>_</code> 分支的代码:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let dice_roll = 9;
match dice_roll {
3 =&gt; add_fancy_hat(),
7 =&gt; remove_fancy_hat(),
_ =&gt; (),
}
fn add_fancy_hat() {}
fn remove_fancy_hat() {}
<span class="boring">}</span></code></pre></pre>
<p>在这里,我们明确告诉 Rust 我们不会使用与前面模式不匹配的值,并且这种情况下我们不想运行任何代码。</p>
<p>我们将在<a href="ch19-00-patterns.html">第十九章</a><!-- ignore -->中介绍更多关于模式和匹配的内容。现在,让我们继续讨论 <code>if let</code> 语法,这在 <code>match</code> 表达式有点啰嗦的情况下很有用。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="if-let-简洁控制流"><a class="header" href="#if-let-简洁控制流"><code>if let</code> 简洁控制流</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch06-03-if-let.md">ch06-03-if-let.md</a>
<br>
commit bb7e429ad6b59d9a0c37db7434976364cbb9c6da</p>
</blockquote>
<p><code>if let</code> 语法让我们以一种不那么冗长的方式结合 <code>if</code><code>let</code>,来处理只匹配一个模式的值而忽略其他模式的情况。考虑示例 6-6 中的程序,它匹配一个 <code>config_max</code> 变量中的 <code>Option&lt;u8&gt;</code> 值并只希望当值为 <code>Some</code> 成员时执行代码:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let config_max = Some(3u8);
match config_max {
Some(max) =&gt; println!("The maximum is configured to be {max}"),
_ =&gt; (),
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 6-6<code>match</code> 只关心当值为 <code>Some</code> 时执行代码</span></p>
<p>如果值是 <code>Some</code>,我们希望打印出 <code>Some</code> 成员中的值,这个值被绑定到模式中的 <code>max</code> 变量里。对于 <code>None</code> 值我们不希望做任何操作。为了满足 <code>match</code> 表达式(穷尽性)的要求,必须在处理完这唯一的成员后加上 <code>_ =&gt; ()</code>,这样也要增加很多烦人的样板代码。</p>
<p>不过我们可以使用 <code>if let</code> 这种更短的方式编写。如下代码与示例 6-6 中的 <code>match</code> 行为一致:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let config_max = Some(3u8);
if let Some(max) = config_max {
println!("The maximum is configured to be {max}");
}
<span class="boring">}</span></code></pre></pre>
<p><code>if let</code> 语法获取通过等号分隔的一个模式和一个表达式。它的工作方式与 <code>match</code> 相同,这里的表达式对应 <code>match</code> 而模式则对应第一个分支。在这个例子中,模式是 <code>Some(max)</code><code>max</code> 绑定为 <code>Some</code> 中的值。接着可以在 <code>if let</code> 代码块中使用 <code>max</code> 了,就跟在对应的 <code>match</code> 分支中一样。模式不匹配时 <code>if let</code> 块中的代码不会执行。</p>
<p>使用 <code>if let</code> 意味着编写更少代码,更少的缩进和更少的样板代码。然而,这样会失去 <code>match</code> 强制要求的穷尽性检查。<code>match</code><code>if let</code> 之间的选择依赖特定的环境以及增加简洁度和失去穷尽性检查的权衡取舍。</p>
<p>换句话说,可以认为 <code>if let</code><code>match</code> 的一个语法糖,它当值匹配某一模式时执行代码而忽略所有其他值。</p>
<p>可以在 <code>if let</code> 中包含一个 <code>else</code><code>else</code> 块中的代码与 <code>match</code> 表达式中的 <code>_</code> 分支块中的代码相同,这样的 <code>match</code> 表达式就等同于 <code>if let</code><code>else</code>。回忆一下示例 6-4 中 <code>Coin</code> 枚举的定义,其 <code>Quarter</code> 成员也包含一个 <code>UsState</code> 值。如果想要计数所有不是 25 美分的硬币的同时也报告 25 美分硬币所属的州,可以使用这样一个 <code>match</code> 表达式:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#[derive(Debug)]
</span><span class="boring">enum UsState {
</span><span class="boring"> Alabama,
</span><span class="boring"> Alaska,
</span><span class="boring"> // --snip--
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">enum Coin {
</span><span class="boring"> Penny,
</span><span class="boring"> Nickel,
</span><span class="boring"> Dime,
</span><span class="boring"> Quarter(UsState),
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let coin = Coin::Penny;
</span> let mut count = 0;
match coin {
Coin::Quarter(state) =&gt; println!("State quarter from {state:?}!"),
_ =&gt; count += 1,
}
<span class="boring">}</span></code></pre></pre>
<p>或者可以使用这样的 <code>if let</code><code>else</code> 表达式:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#[derive(Debug)]
</span><span class="boring">enum UsState {
</span><span class="boring"> Alabama,
</span><span class="boring"> Alaska,
</span><span class="boring"> // --snip--
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">enum Coin {
</span><span class="boring"> Penny,
</span><span class="boring"> Nickel,
</span><span class="boring"> Dime,
</span><span class="boring"> Quarter(UsState),
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let coin = Coin::Penny;
</span> let mut count = 0;
if let Coin::Quarter(state) = coin {
println!("State quarter from {state:?}!");
} else {
count += 1;
}
<span class="boring">}</span></code></pre></pre>
<p>如果你的程序遇到一个使用 <code>match</code> 表达起来过于啰嗦的逻辑,记住 <code>if let</code> 也在你的 Rust 工具箱中。</p>
<h2 id="总结-5"><a class="header" href="#总结-5">总结</a></h2>
<p>现在我们涉及到了如何使用枚举来创建有一系列可列举值的自定义类型。我们也展示了标准库的 <code>Option&lt;T&gt;</code> 类型是如何帮助你利用类型系统来避免出错的。当枚举值包含数据时,你可以根据需要处理多少情况来选择使用 <code>match</code><code>if let</code> 来获取并使用这些值。</p>
<p>你的 Rust 程序现在能够使用结构体和枚举在自己的作用域内表现其内容了。在你的 API 中使用自定义类型保证了类型安全:编译器会确保你的函数只会得到它期望的类型的值。</p>
<p>为了向你的用户提供一个组织良好的 API它使用起来很直观并且只向用户暴露他们确实需要的部分那么现在就让我们转向 Rust 的模块系统吧。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="使用包crate-和模块管理不断增长的项目"><a class="header" href="#使用包crate-和模块管理不断增长的项目">使用包、Crate 和模块管理不断增长的项目</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch07-00-managing-growing-projects-with-packages-crates-and-modules.md">ch07-00-managing-growing-projects-with-packages-crates-and-modules.md</a>
<br>
commit c77d7a1279dbc7a9d76e80c5ac9d742dd529538c</p>
</blockquote>
<p>当你编写大型程序时,组织你的代码显得尤为重要。通过对相关功能进行分组和划分不同功能的代码,你可以清楚在哪里可以找到实现了特定功能的代码,以及在哪里可以改变一个功能的工作方式。</p>
<p>到目前为止,我们编写的程序都在一个文件的一个模块中。伴随着项目的增长,你应该通过将代码分解为多个模块和多个文件来组织代码。一个包可以包含多个二进制 crate 项和一个可选的 crate 库。伴随着包的增长,你可以将包中的部分代码提取出来,做成独立的 crate这些 crate 则作为外部依赖项。本章将会涵盖所有这些概念。对于一个由一系列相互关联的包组成的超大型项目Cargo 提供了 “工作空间” 这一功能,我们将在第十四章的 <a href="ch14-03-cargo-workspaces.html">“Cargo Workspaces”</a> 对此进行讲解。</p>
<p>我们也会讨论封装来实现细节,这可以使你更高级地重用代码:你实现了一个操作后,其他的代码可以通过该代码的公共接口来进行调用,而不需要知道它是如何实现的。你在编写代码时可以定义哪些部分是其他代码可以使用的公共部分,以及哪些部分是你有权更改实现细节的私有部分。这是另一种减少你在脑海中记住项目内容数量的方法。</p>
<p>这里有一个需要说明的概念 “作用域scope代码所在的嵌套上下文有一组定义为 “in scope” 的名称。当阅读、编写和编译代码时,程序员和编译器需要知道特定位置的特定名称是否引用了变量、函数、结构体、枚举、模块、常量或者其他有意义的项。你可以创建作用域,以及改变哪些名称在作用域内还是作用域外。同一个作用域内不能拥有两个相同名称的项;可以使用一些工具来解决名称冲突。</p>
<p>Rust 有许多功能可以让你管理代码的组织,包括哪些内容可以被公开,哪些内容作为私有部分,以及程序每个作用域中的名字。这些功能,有时被统称为 “模块系统the module system包括</p>
<ul>
<li><strong></strong><em>Packages</em>Cargo 的一个功能,它允许你构建、测试和分享 crate。</li>
<li><strong>Crates</strong> :一个模块的树形结构,它形成了库或二进制项目。</li>
<li><strong>模块</strong><em>Modules</em>)和 <strong>use</strong>:允许你控制作用域和路径的私有性。</li>
<li><strong>路径</strong><em>path</em>):一个命名例如结构体、函数或模块等项的方式。</li>
</ul>
<p>本章将会涵盖所有这些概念,讨论它们如何交互,并说明如何使用它们来管理作用域。到最后,你会对模块系统有深入的了解,并且能够像专业人士一样使用作用域!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="包和-crate"><a class="header" href="#包和-crate">包和 Crate</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch07-01-packages-and-crates.md">ch07-01-packages-and-crates.md</a>
<br>
commit c77d7a1279dbc7a9d76e80c5ac9d742dd529538c</p>
</blockquote>
<p>模块系统的第一部分,我们将介绍包和 crate。</p>
<p>crate 是 Rust 在编译时最小的代码单位。如果你用 <code>rustc</code> 而不是 <code>cargo</code> 来编译一个文件(第一章我们这么做过),编译器还是会将那个文件认作一个 crate。crate 可以包含模块,模块可以定义在其他文件,然后和 crate 一起编译,我们会在接下来的章节中遇到。</p>
<p>crate 有两种形式:二进制项和库。<em>二进制项</em> 可以被编译为可执行程序,比如一个命令行程序或者一个 web server。它们必须有一个 <code>main</code> 函数来定义当程序被执行的时候所需要做的事情。目前我们所创建的 crate 都是二进制项。</p>
<p><em></em> 并没有 <code>main</code> 函数,它们也不会编译为可执行程序,它们提供一些诸如函数之类的东西,使其他项目也能使用这些东西。比如 <a href="ch02-00-guessing-game-tutorial.html#%E7%94%9F%E6%88%90%E4%B8%80%E4%B8%AA%E9%9A%8F%E6%9C%BA%E6%95%B0">第二章</a><code>rand</code> crate 就提供了生成随机数的东西。大多数时间 <code>Rustaceans</code> 说的 crate 指的都是库,这与其他编程语言中 library 概念一致。</p>
<p><em>crate root</em> 是一个源文件Rust 编译器以它为起始点,并构成你的 crate 的根模块(我们将在 <a href="ch07-02-defining-modules-to-control-scope-and-privacy.html">“定义模块来控制作用域与私有性”</a> 一节深入解读)。</p>
<p><em></em><em>package</em>)是提供一系列功能的一个或者多个 crate。一个包会包含一个 <em>Cargo.toml</em> 文件,阐述如何去构建这些 crate。Cargo 就是一个包含构建你代码的二进制项的包。Cargo 也包含这些二进制项所依赖的库。其他项目也能用 Cargo 库来实现与 Cargo 命令行程序一样的逻辑。</p>
<p>包中可以包含至多一个库 crate(library crate)。包中可以包含任意多个二进制 crate(binary crate),但是必须至少包含一个 crate无论是库的还是二进制的</p>
<p>让我们来看看创建包的时候会发生什么。首先,我们输入命令 <code>cargo new</code></p>
<pre><code class="language-console">$ cargo new my-project
Created binary (application) `my-project` package
$ ls my-project
Cargo.toml
src
$ ls my-project/src
main.rs
</code></pre>
<p>运行了这条命令后,我们先用 <code>ls</code> (译者注:此命令为 Linux 平台的指令Windows 下可用 dir来看看 Cargo 给我们创建了什么Cargo 会给我们的包创建一个 <em>Cargo.toml</em> 文件。查看 <em>Cargo.toml</em> 的内容,会发现并没有提到 <em>src/main.rs</em>,因为 Cargo 遵循的一个约定:<em>src/main.rs</em> 就是一个与包同名的二进制 crate 的 crate 根。同样的Cargo 知道如果包目录中包含 <em>src/lib.rs</em>,则包带有与其同名的库 crate<em>src/lib.rs</em> 是 crate 根。crate 根文件将由 Cargo 传递给 <code>rustc</code> 来实际构建库或者二进制项目。</p>
<p>在此,我们有了一个只包含 <em>src/main.rs</em> 的包,意味着它只含有一个名为 <code>my-project</code> 的二进制 crate。如果一个包同时含有 <em>src/main.rs</em><em>src/lib.rs</em>,则它有两个 crate一个二进制的和一个库的且名字都与包相同。通过将文件放在 <em>src/bin</em> 目录下,一个包可以拥有多个二进制 crate每个 <em>src/bin</em> 下的文件都会被编译成一个独立的二进制 crate。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="定义模块来控制作用域与私有性"><a class="header" href="#定义模块来控制作用域与私有性">定义模块来控制作用域与私有性</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch07-02-defining-modules-to-control-scope-and-privacy.md">ch07-02-defining-modules-to-control-scope-and-privacy.md</a>
<br>
commit 310ea6cb0dd855eaf510c9ba05648bc5836ead0c</p>
</blockquote>
<p>在本节,我们将讨论模块和其它一些关于模块系统的部分,如允许你命名项的 <em>路径</em><em>paths</em>);用来将路径引入作用域的 <code>use</code> 关键字;以及使项变为公有的 <code>pub</code> 关键字。我们还将讨论 <code>as</code> 关键字、外部包和 glob 运算符。现在,让我们把注意力放在模块上!</p>
<p>首先,我们将从一系列的规则开始,在你未来组织代码的时候,这些规则可被用作简单的参考。接下来我们将会详细的解释每条规则。</p>
<h2 id="模块小抄"><a class="header" href="#模块小抄">模块小抄</a></h2>
<p>这里我们提供一个简单的参考,用来解释模块、路径、<code>use</code>关键词和<code>pub</code>关键词如何在编译器中工作,以及大部分开发者如何组织他们的代码。我们将在本章节中举例说明每条规则,不过这是一个解释模块工作方式的良好参考。</p>
<ul>
<li><strong>从 crate 根节点开始</strong>: 当编译一个 crate, 编译器首先在 crate 根文件(通常,对于一个库 crate 而言是<em>src/lib.rs</em>,对于一个二进制 crate 而言是<em>src/main.rs</em>)中寻找需要被编译的代码。</li>
<li><strong>声明模块</strong>: 在 crate 根文件中,你可以声明一个新模块;比如,你用<code>mod garden;</code>声明了一个叫做<code>garden</code>的模块。编译器会在下列路径中寻找模块代码:
<ul>
<li>内联,在大括号中,当<code>mod garden</code>后方不是一个分号而是一个大括号</li>
<li>在文件 <em>src/garden.rs</em></li>
<li>在文件 <em>src/garden/mod.rs</em></li>
</ul>
</li>
<li><strong>声明子模块</strong>: 在除了 crate 根节点以外的其他文件中,你可以定义子模块。比如,你可能在<em>src/garden.rs</em>中定义了<code>mod vegetables;</code>。编译器会在以父模块命名的目录中寻找子模块代码:
<ul>
<li>内联,在大括号中,当<code>mod vegetables</code>后方不是一个分号而是一个大括号</li>
<li>在文件 <em>src/garden/vegetables.rs</em></li>
<li>在文件 <em>src/garden/vegetables/mod.rs</em></li>
</ul>
</li>
<li><strong>模块中的代码路径</strong>: 一旦一个模块是你 crate 的一部分,你可以在隐私规则允许的前提下,从同一个 crate 内的任意地方,通过代码路径引用该模块的代码。举例而言,一个 garden vegetables 模块下的<code>Asparagus</code>类型可以在<code>crate::garden::vegetables::Asparagus</code>被找到。</li>
<li><strong>私有 vs 公用</strong>: 一个模块里的代码默认对其父模块私有。为了使一个模块公用,应当在声明时使用<code>pub mod</code>替代<code>mod</code>。为了使一个公用模块内部的成员公用,应当在声明前使用<code>pub</code></li>
<li><strong><code>use</code> 关键字</strong>: 在一个作用域内,<code>use</code>关键字创建了一个成员的快捷方式,用来减少长路径的重复。在任何可以引用<code>crate::garden::vegetables::Asparagus</code>的作用域,你可以通过 <code>use crate::garden::vegetables::Asparagus;</code>创建一个快捷方式,然后你就可以在作用域中只写<code>Asparagus</code>来使用该类型。</li>
</ul>
<p>这里我们创建一个名为<code>backyard</code>的二进制 crate 来说明这些规则。该 crate 的路径同样命名为<code>backyard</code>,该路径包含了这些文件和目录:</p>
<pre><code class="language-text">backyard
├── Cargo.lock
├── Cargo.toml
└── src
├── garden
│   └── vegetables.rs
├── garden.rs
└── main.rs
</code></pre>
<p>这个例子中的 crate 根文件是<em>src/main.rs</em>,该文件包括了:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust noplayground ignore">use crate::garden::vegetables::Asparagus;
pub mod garden;
fn main() {
let plant = Asparagus {};
println!("I'm growing {plant:?}!");
}</code></pre>
<p><code>pub mod garden;</code>行告诉编译器应该包含在<em>src/garden.rs</em>文件中发现的代码:</p>
<p><span class="filename">文件名src/garden.rs</span></p>
<pre><code class="language-rust noplayground ignore">pub mod vegetables;</code></pre>
<p>在此处, <code>pub mod vegetables;</code>意味着在<em>src/garden/vegetables.rs</em>中的代码也应该被包括。这些代码是:</p>
<pre><code class="language-rust noplayground ignore">#[derive(Debug)]
pub struct Asparagus {}</code></pre>
<p>现在让我们深入了解这些规则的细节并在实际中演示它们!</p>
<h3 id="在模块中对相关代码进行分组"><a class="header" href="#在模块中对相关代码进行分组">在模块中对相关代码进行分组</a></h3>
<p><em>模块</em> 让我们可以将一个 crate 中的代码进行分组,以提高可读性与重用性。因为一个模块中的代码默认是私有的,所以还可以利用模块控制项的 <em>私有性</em>。私有项是不可为外部使用的内在详细实现。我们也可以将模块和它其中的项标记为公开的,这样,外部代码就可以使用并依赖与它们。</p>
<p>在餐饮业,餐馆中会有一些地方被称之为 <em>前台</em><em>front of house</em>),还有另外一些地方被称之为 <em>后台</em><em>back of house</em>)。前台是招待顾客的地方,在这里,店主可以为顾客安排座位,服务员接受顾客下单和付款,调酒师会制作饮品。后台则是由厨师工作的厨房,洗碗工的工作地点,以及经理做行政工作的地方组成。</p>
<p>我们可以将函数放置到嵌套的模块中,来使我们的 crate 结构与实际的餐厅结构相同。通过执行 <code>cargo new --lib restaurant</code>,来创建一个新的名为 <code>restaurant</code> 的库。然后将示例 7-1 中所罗列出来的代码放入 <em>src/lib.rs</em> 中,来定义一些模块和函数。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">mod front_of_house {
mod hosting {
fn add_to_waitlist() {}
fn seat_at_table() {}
}
mod serving {
fn take_order() {}
fn serve_order() {}
fn take_payment() {}
}
}</code></pre>
<p><span class="caption">示例 7-1一个包含了其他内置了函数的模块的 <code>front_of_house</code> 模块</span></p>
<p>我们定义一个模块,是以 <code>mod</code> 关键字为起始,然后指定模块的名字(本例中叫做 <code>front_of_house</code>),并且用花括号包围模块的主体。在模块内,我们还可以定义其他的模块,就像本例中的 <code>hosting</code><code>serving</code> 模块。模块还可以保存一些定义的其他项,比如结构体、枚举、常量、特性、或者函数。</p>
<p>通过使用模块,我们可以将相关的定义分组到一起,并指出它们为什么相关。程序员可以通过使用这段代码,更加容易地找到他们想要的定义,因为他们可以基于分组来对代码进行导航,而不需要阅读所有的定义。程序员向这段代码中添加一个新的功能时,他们也会知道代码应该放置在何处,可以保持程序的组织性。</p>
<p>在前面我们提到了,<code>src/main.rs</code><code>src/lib.rs</code> 叫做 crate 根。之所以这样叫它们是因为这两个文件的内容都分别在 crate 模块结构的根组成了一个名为 <code>crate</code> 的模块,该结构被称为 <em>模块树</em><em>module tree</em>)。</p>
<p>示例 7-2 展示了示例 7-1 中的模块树的结构。</p>
<pre><code class="language-text">crate
└── front_of_house
├── hosting
│ ├── add_to_waitlist
│ └── seat_at_table
└── serving
├── take_order
├── serve_order
└── take_payment
</code></pre>
<p><span class="caption">示例 7-2: 示例 7-1 中代码的模块树</span></p>
<p>这个树展示了一些模块是如何被嵌入到另一个模块的(例如,<code>hosting</code> 嵌套在 <code>front_of_house</code> 中)。这个树还展示了一些模块是互为 <em>兄弟</em><em>siblings</em>)的,这意味着它们定义在同一模块中(<code>hosting</code><code>serving</code> 被一起定义在 <code>front_of_house</code> 中)。继续沿用家庭关系的比喻,如果一个模块 A 被包含在模块 B 中,我们将模块 A 称为模块 B 的 <em></em><em>child</em>),模块 B 则是模块 A 的 <em></em><em>parent</em>)。注意,整个模块树都植根于名为 <code>crate</code> 的隐式模块下。</p>
<p>这个模块树可能会令你想起电脑上文件系统的目录树;这是一个非常恰当的类比!就像文件系统的目录,你可以使用模块来组织你的代码。并且,就像目录中的文件,我们需要一种方法来找到模块。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="引用模块项目的路径"><a class="header" href="#引用模块项目的路径">引用模块项目的路径</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md">ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md</a>
<br>
commit 2b4565662d1a7973d870744a923f58f8f7dcce91</p>
</blockquote>
<p>来看一下 Rust 如何在模块树中找到一个项的位置,我们使用路径的方式,就像在文件系统使用路径一样。为了调用一个函数,我们需要知道它的路径。</p>
<p>路径有两种形式:</p>
<ul>
<li><strong>绝对路径</strong><em>absolute path</em>)是以 crate 根root开头的全路径对于外部 crate 的代码,是以 crate 名开头的绝对路径,对于当前 crate 的代码,则以字面值 <code>crate</code> 开头。</li>
<li><strong>相对路径</strong><em>relative path</em>)从当前模块开始,以 <code>self</code><code>super</code> 或定义在当前模块中的标识符开头。</li>
</ul>
<p>绝对路径和相对路径都后跟一个或多个由双冒号(<code>::</code>)分割的标识符。</p>
<p>回到示例 7-1假设我们希望调用 <code>add_to_waitlist</code> 函数。还是同样的问题,<code>add_to_waitlist</code> 函数的路径是什么?在示例 7-3 中删除了一些模块和函数。</p>
<p>我们在 crate 根定义了一个新函数 <code>eat_at_restaurant</code>,并在其中展示调用 <code>add_to_waitlist</code> 函数的两种方法。<code>eat_at_restaurant</code> 函数是我们 crate 库的一个公共 API所以我们使用 <code>pub</code> 关键字来标记它。在 <a href="ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#%E4%BD%BF%E7%94%A8-pub-%E5%85%B3%E9%94%AE%E5%AD%97%E6%9A%B4%E9%9C%B2%E8%B7%AF%E5%BE%84">“使用 <code>pub</code> 关键字暴露路径”</a> 一节,我们将详细介绍 <code>pub</code>。注意,这个例子无法编译通过,我们稍后会解释原因。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">mod front_of_house {
mod hosting {
fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// 绝对路径
crate::front_of_house::hosting::add_to_waitlist();
// 相对路径
front_of_house::hosting::add_to_waitlist();
}</code></pre>
<p><span class="caption">示例 7-3: 使用绝对路径和相对路径来调用 <code>add_to_waitlist</code> 函数</span></p>
<p>第一种方式,我们在 <code>eat_at_restaurant</code> 中调用 <code>add_to_waitlist</code> 函数,使用的是绝对路径。<code>add_to_waitlist</code> 函数与 <code>eat_at_restaurant</code> 被定义在同一 crate 中,这意味着我们可以使用 <code>crate</code> 关键字为起始的绝对路径。</p>
<p><code>crate</code> 后面,我们持续地嵌入模块,直到我们找到 <code>add_to_waitlist</code>。你可以想象出一个相同结构的文件系统,我们通过指定路径 <code>/front_of_house/hosting/add_to_waitlist</code> 来执行 <code>add_to_waitlist</code> 程序。我们使用 <code>crate</code> 从 crate 根开始就类似于在 shell 中使用 <code>/</code> 从文件系统根开始。</p>
<p>第二种方式,我们在 <code>eat_at_restaurant</code> 中调用 <code>add_to_waitlist</code>,使用的是相对路径。这个路径以 <code>front_of_house</code> 为起始,这个模块在模块树中,与 <code>eat_at_restaurant</code> 定义在同一层级。与之等价的文件系统路径就是 <code>front_of_house/hosting/add_to_waitlist</code>。以模块名开头意味着该路径是相对路径。</p>
<p>选择使用相对路径还是绝对路径,要取决于你的项目,也取决于你是更倾向于将项的定义代码与使用该项的代码分开来移动,还是一起移动。举一个例子,如果我们要将 <code>front_of_house</code> 模块和 <code>eat_at_restaurant</code> 函数一起移动到一个名为 <code>customer_experience</code> 的模块中,我们需要更新 <code>add_to_waitlist</code> 的绝对路径,但是相对路径还是可用的。然而,如果我们要将 <code>eat_at_restaurant</code> 函数单独移到一个名为 <code>dining</code> 的模块中,还是可以使用原本的绝对路径来调用 <code>add_to_waitlist</code>,但是相对路径必须要更新。我们更倾向于使用绝对路径,因为把代码定义和项调用各自独立地移动是更常见的。</p>
<p>让我们试着编译一下示例 7-3并查明为何不能编译示例 7-4 展示了这个错误。</p>
<pre><code class="language-console">$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0603]: module `hosting` is private
--&gt; src/lib.rs:9:28
|
9 | crate::front_of_house::hosting::add_to_waitlist();
| ^^^^^^^ --------------- function `add_to_waitlist` is not publicly re-exported
| |
| private module
|
note: the module `hosting` is defined here
--&gt; src/lib.rs:2:5
|
2 | mod hosting {
| ^^^^^^^^^^^
error[E0603]: module `hosting` is private
--&gt; src/lib.rs:12:21
|
12 | front_of_house::hosting::add_to_waitlist();
| ^^^^^^^ --------------- function `add_to_waitlist` is not publicly re-exported
| |
| private module
|
note: the module `hosting` is defined here
--&gt; src/lib.rs:2:5
|
2 | mod hosting {
| ^^^^^^^^^^^
For more information about this error, try `rustc --explain E0603`.
error: could not compile `restaurant` (lib) due to 2 previous errors
</code></pre>
<p><span class="caption">示例 7-4: 构建示例 7-3 出现的编译器错误</span></p>
<p>错误信息说 <code>hosting</code> 模块是私有的。换句话说,我们拥有 <code>hosting</code> 模块和 <code>add_to_waitlist</code> 函数的正确路径,但是 Rust 不让我们使用,因为它不能访问私有片段。在 Rust 中,默认所有项(函数、方法、结构体、枚举、模块和常量)对父模块都是私有的。如果希望创建一个私有函数或结构体,你可以将其放入一个模块。</p>
<p>父模块中的项不能使用子模块中的私有项,但是子模块中的项可以使用它们父模块中的项。这是因为子模块封装并隐藏了它们的实现详情,但是子模块可以看到它们定义的上下文。继续拿餐馆作比喻,把私有性规则想象成餐馆的后台办公室:餐馆内的事务对餐厅顾客来说是不可知的,但办公室经理可以洞悉其经营的餐厅并在其中做任何事情。</p>
<p>Rust 选择以这种方式来实现模块系统功能,因此默认隐藏内部实现细节。这样一来,你就知道可以更改内部代码的哪些部分而不会破坏外部代码。不过 Rust 也确实提供了通过使用 <code>pub</code> 关键字来创建公共项,使子模块的内部部分暴露给上级模块。</p>
<h3 id="使用-pub-关键字暴露路径"><a class="header" href="#使用-pub-关键字暴露路径">使用 <code>pub</code> 关键字暴露路径</a></h3>
<p>让我们回头看一下示例 7-4 的错误,它告诉我们 <code>hosting</code> 模块是私有的。我们想让父模块中的 <code>eat_at_restaurant</code> 函数可以访问子模块中的 <code>add_to_waitlist</code> 函数,因此我们使用 <code>pub</code> 关键字来标记 <code>hosting</code> 模块,如示例 7-5 所示。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">mod front_of_house {
pub mod hosting {
fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// 绝对路径
crate::front_of_house::hosting::add_to_waitlist();
// 相对路径
front_of_house::hosting::add_to_waitlist();
}</code></pre>
<p><span class="caption">示例 7-5: 使用 <code>pub</code> 关键字声明 <code>hosting</code> 模块使其可在 <code>eat_at_restaurant</code> 使用</span></p>
<p>不幸的是,示例 7-5 的代码编译仍然有错误,如示例 7-6 所示。</p>
<pre><code class="language-console">$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0603]: function `add_to_waitlist` is private
--&gt; src/lib.rs:9:37
|
9 | crate::front_of_house::hosting::add_to_waitlist();
| ^^^^^^^^^^^^^^^ private function
|
note: the function `add_to_waitlist` is defined here
--&gt; src/lib.rs:3:9
|
3 | fn add_to_waitlist() {}
| ^^^^^^^^^^^^^^^^^^^^
error[E0603]: function `add_to_waitlist` is private
--&gt; src/lib.rs:12:30
|
12 | front_of_house::hosting::add_to_waitlist();
| ^^^^^^^^^^^^^^^ private function
|
note: the function `add_to_waitlist` is defined here
--&gt; src/lib.rs:3:9
|
3 | fn add_to_waitlist() {}
| ^^^^^^^^^^^^^^^^^^^^
For more information about this error, try `rustc --explain E0603`.
error: could not compile `restaurant` (lib) due to 2 previous errors
</code></pre>
<p><span class="caption">示例 7-6: 构建示例 7-5 出现的编译器错误</span></p>
<p>发生了什么?在 <code>mod hosting</code> 前添加了 <code>pub</code> 关键字,使其变成公有的。伴随着这种变化,如果我们可以访问 <code>front_of_house</code>,那我们也可以访问 <code>hosting</code>。但是 <code>hosting</code><em>内容</em><em>contents</em>)仍然是私有的;这表明使模块公有并不使其内容也是公有的。模块上的 <code>pub</code> 关键字只允许其父模块引用它,而不允许访问内部代码。因为模块是一个容器,只是将模块变为公有能做的其实并不太多;同时需要更深入地选择将一个或多个项变为公有。</p>
<p>示例 7-6 中的错误说,<code>add_to_waitlist</code> 函数是私有的。私有性规则不但应用于模块,还应用于结构体、枚举、函数和方法。</p>
<p>让我们继续将 <code>pub</code> 关键字放置在 <code>add_to_waitlist</code> 函数的定义之前,使其变成公有。如示例 7-7 所示。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground test_harness">mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// 绝对路径
crate::front_of_house::hosting::add_to_waitlist();
// 相对路径
front_of_house::hosting::add_to_waitlist();
}</code></pre>
<p><span class="caption">示例 7-7: 为 <code>mod hosting</code>
<code>fn add_to_waitlist</code> 添加 <code>pub</code> 关键字使它们可以在
<code>eat_at_restaurant</code> 函数中被调用</span></p>
<p>现在代码可以编译通过了!为了了解为何增加 <code>pub</code> 关键字使得我们可以在 <code>add_to_waitlist</code> 中调用这些路径与私有性规则有关,让我们看看绝对路径和相对路径。</p>
<p>在绝对路径,我们从 <code>crate</code> 也就是 crate 根开始。crate 根中定义了 <code>front_of_house</code> 模块。虽然 <code>front_of_house</code> 模块不是公有的,不过因为 <code>eat_at_restaurant</code> 函数与 <code>front_of_house</code> 定义于同一模块中(即,<code>eat_at_restaurant</code><code>front_of_house</code> 是兄弟),我们可以从 <code>eat_at_restaurant</code> 中引用 <code>front_of_house</code>。接下来是使用 <code>pub</code> 标记的 <code>hosting</code> 模块。我们可以访问 <code>hosting</code> 的父模块,所以可以访问 <code>hosting</code>。最后,<code>add_to_waitlist</code> 函数被标记为 <code>pub</code> ,我们可以访问其父模块,所以这个函数调用是有效的!</p>
<p>在相对路径,其逻辑与绝对路径相同,除了第一步:不同于从 crate 根开始,路径从 <code>front_of_house</code> 开始。<code>front_of_house</code> 模块与 <code>eat_at_restaurant</code> 定义于同一模块,所以从 <code>eat_at_restaurant</code> 中开始定义的该模块相对路径是有效的。接下来因为 <code>hosting</code><code>add_to_waitlist</code> 被标记为 <code>pub</code>,路径其余的部分也是有效的,因此函数调用也是有效的!</p>
<p>如果你计划共享你的库 crate 以便其它项目可以使用你的代码,公有 API 将是决定 crate 用户如何与你代码交互的契约。关于管理公有 API 的修改以便被人更容易依赖你的库有着很多考量。这些考量超出了本书的范畴;如果你对这些话题感兴趣,请查阅 <a href="https://rust-lang.github.io/api-guidelines/">The Rust API Guidelines</a></p>
<blockquote>
<h3 id="二进制和库-crate-包的最佳实践"><a class="header" href="#二进制和库-crate-包的最佳实践">二进制和库 crate 包的最佳实践</a></h3>
<p>我们提到过包package可以同时包含一个 <em>src/main.rs</em> 二进制 crate 根和一个 <em>src/lib.rs</em> 库 crate 根,并且这两个 crate 默认以包名来命名。通常,这种包含二进制 crate 和库 crate 的模式的包,在二进制 crate 中只保留足以生成一个可执行文件的代码,并由可执行文件调用库 crate 的代码。又因为库 crate 可以共享,这使得其它项目从包提供的大部分功能中受益。</p>
<p>模块树应该定义在 <em>src/lib.rs</em> 中。这样通过以包名开头的路径,公有项就可以在二进制 crate 中使用。二进制 crate 就变得同其它在该 crate 之外的、使用库 crate 的用户一样:二者都只能使用公有 API。这有助于你设计一个好的 API你不仅仅是作者也是用户</p>
<p><a href="ch12-00-an-io-project.html">第十二章</a>我们会通过一个同时包含二进制 crate 和库 crate 的命令行程序来展示这些包组织上的实践。</p>
</blockquote>
<h3 id="super-开始的相对路径"><a class="header" href="#super-开始的相对路径"><code>super</code> 开始的相对路径</a></h3>
<p>我们可以通过在路径的开头使用 <code>super</code> ,从父模块开始构建相对路径,而不是从当前模块或者 crate 根开始。这类似以 <code>..</code> 语法开始一个文件系统路径。使用 <code>super</code> 允许我们引用父模块中的已知项,这使得重新组织模块树变得更容易 —— 当模块与父模块关联的很紧密,但某天父模块可能要移动到模块树的其它位置。</p>
<p>考虑一下示例 7-8 中的代码,它模拟了厨师更正了一个错误订单,并亲自将其提供给客户的情况。<code>back_of_house</code> 模块中的定义的 <code>fix_incorrect_order</code> 函数通过指定的 <code>super</code> 起始的 <code>deliver_order</code> 路径,来调用父模块中的 <code>deliver_order</code> 函数:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground test_harness">fn deliver_order() {}
mod back_of_house {
fn fix_incorrect_order() {
cook_order();
super::deliver_order();
}
fn cook_order() {}
}</code></pre>
<p><span class="caption">示例 7-8: 使用以 <code>super</code> 开头的相对路径从父目录开始调用函数</span></p>
<p><code>fix_incorrect_order</code> 函数在 <code>back_of_house</code> 模块中,所以我们可以使用 <code>super</code> 进入 <code>back_of_house</code> 父模块,也就是本例中的 <code>crate</code> 根。在这里,我们可以找到 <code>deliver_order</code>。成功!我们认为 <code>back_of_house</code> 模块和 <code>deliver_order</code> 函数之间可能具有某种关联关系,并且,如果我们要重新组织这个 crate 的模块树,需要一起移动它们。因此,我们使用 <code>super</code>,这样一来,如果这些代码被移动到了其他模块,我们只需要更新很少的代码。</p>
<h3 id="创建公有的结构体和枚举"><a class="header" href="#创建公有的结构体和枚举">创建公有的结构体和枚举</a></h3>
<p>我们还可以使用 <code>pub</code> 来设计公有的结构体和枚举,不过关于在结构体和枚举上使用 <code>pub</code> 还有一些额外的细节需要注意。如果我们在一个结构体定义的前面使用了 <code>pub</code> ,这个结构体会变成公有的,但是这个结构体的字段仍然是私有的。我们可以根据情况决定每个字段是否公有。在示例 7-9 中,我们定义了一个公有结构体 <code>back_of_house:Breakfast</code>,其中有一个公有字段 <code>toast</code> 和私有字段 <code>seasonal_fruit</code>。这个例子模拟的情况是,在一家餐馆中,顾客可以选择随餐附赠的面包类型,但是厨师会根据季节和库存情况来决定随餐搭配的水果。餐馆可用的水果变化是很快的,所以顾客不能选择水果,甚至无法看到他们将会得到什么水果。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">mod back_of_house {
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
pub fn summer(toast: &amp;str) -&gt; Breakfast {
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peaches"),
}
}
}
}
pub fn eat_at_restaurant() {
// 在夏天订购一个黑麦土司作为早餐
let mut meal = back_of_house::Breakfast::summer("Rye");
// 改变主意更换想要面包的类型
meal.toast = String::from("Wheat");
println!("I'd like {} toast please", meal.toast);
// 如果取消下一行的注释代码不能编译;
// 不允许查看或修改早餐附带的季节水果
// meal.seasonal_fruit = String::from("blueberries");
}</code></pre>
<p><span class="caption">示例 7-9: 带有公有和私有字段的结构体</span></p>
<p>因为 <code>back_of_house::Breakfast</code> 结构体的 <code>toast</code> 字段是公有的,所以我们可以在 <code>eat_at_restaurant</code> 中使用点号来随意的读写 <code>toast</code> 字段。注意,我们不能在 <code>eat_at_restaurant</code> 中使用 <code>seasonal_fruit</code> 字段,因为 <code>seasonal_fruit</code> 是私有的。尝试去除那一行修改 <code>seasonal_fruit</code> 字段值的代码的注释,看看你会得到什么错误!</p>
<p>还请注意一点,因为 <code>back_of_house::Breakfast</code> 具有私有字段,所以这个结构体需要提供一个公共的关联函数来构造 <code>Breakfast</code> 的实例 (这里我们命名为 <code>summer</code>)。如果 <code>Breakfast</code> 没有这样的函数,我们将无法在 <code>eat_at_restaurant</code> 中创建 <code>Breakfast</code> 实例,因为我们不能在 <code>eat_at_restaurant</code> 中设置私有字段 <code>seasonal_fruit</code> 的值。</p>
<p>与之相反,如果我们将枚举设为公有,则它的所有成员都将变为公有。我们只需要在 <code>enum</code> 关键字前面加上 <code>pub</code>,就像示例 7-10 展示的那样。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">mod back_of_house {
pub enum Appetizer {
Soup,
Salad,
}
}
pub fn eat_at_restaurant() {
let order1 = back_of_house::Appetizer::Soup;
let order2 = back_of_house::Appetizer::Salad;
}</code></pre>
<p><span class="caption">示例 7-10: 设计公有枚举,使其所有成员公有</span></p>
<p>因为我们创建了名为 <code>Appetizer</code> 的公有枚举,所以我们可以在 <code>eat_at_restaurant</code> 中使用 <code>Soup</code><code>Salad</code> 成员。</p>
<p>如果枚举成员不是公有的,那么枚举会显得用处不大;给枚举的所有成员挨个添加 <code>pub</code> 是很令人恼火的,因此枚举成员默认就是公有的。结构体通常使用时,不必将它们的字段公有化,因此结构体遵循常规,内容全部是私有的,除非使用 <code>pub</code> 关键字。</p>
<p>还有一种使用 <code>pub</code> 的场景我们还没有涉及到,那就是我们最后要讲的模块功能:<code>use</code> 关键字。我们将先单独介绍 <code>use</code>,然后展示如何结合使用 <code>pub</code><code>use</code></p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用-use-关键字将路径引入作用域"><a class="header" href="#使用-use-关键字将路径引入作用域">使用 <code>use</code> 关键字将路径引入作用域</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md">ch07-04-bringing-paths-into-scope-with-the-use-keyword.md</a>
<br>
commit c77d7a1279dbc7a9d76e80c5ac9d742dd529538c</p>
</blockquote>
<p>不得不编写路径来调用函数显得不便且重复。在示例 7-7 中,无论我们选择 <code>add_to_waitlist</code> 函数的绝对路径还是相对路径,每次我们想要调用 <code>add_to_waitlist</code> 时,都必须指定<code>front_of_house</code><code>hosting</code>。幸运的是,有一种方法可以简化这个过程。我们可以使用 <code>use</code> 关键字创建一个短路径,然后就可以在作用域中的任何地方使用这个更短的名字。</p>
<p>在示例 7-11 中,我们将 <code>crate::front_of_house::hosting</code> 模块引入了 <code>eat_at_restaurant</code> 函数的作用域,而我们只需要指定 <code>hosting::add_to_waitlist</code> 即可在 <code>eat_at_restaurant</code> 中调用 <code>add_to_waitlist</code> 函数。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground test_harness">mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}</code></pre>
<p><span class="caption">示例 7-11: 使用 <code>use</code> 将模块引入作用域</span></p>
<p>在作用域中增加 <code>use</code> 和路径类似于在文件系统中创建软连接符号连接symbolic link。通过在 crate 根增加 <code>use crate::front_of_house::hosting</code>,现在 <code>hosting</code> 在作用域中就是有效的名称了,如同 <code>hosting</code> 模块被定义于 crate 根一样。通过 <code>use</code> 引入作用域的路径也会检查私有性,同其它路径一样。</p>
<p>注意 <code>use</code> 只能创建 <code>use</code> 所在的特定作用域内的短路径。示例 7-12 将 <code>eat_at_restaurant</code> 函数移动到了一个叫 <code>customer</code> 的子模块,这又是一个不同于 <code>use</code> 语句的作用域,所以函数体不能编译。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground test_harness does_not_compile ignore">mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting;
mod customer {
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
}</code></pre>
<p><span class="caption">示例 7-12: <code>use</code> 语句只适用于其所在的作用域</span></p>
<p>编译器错误显示短路径不再适用于 <code>customer</code> 模块中:</p>
<pre><code class="language-console">$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0433]: failed to resolve: use of undeclared crate or module `hosting`
--&gt; src/lib.rs:11:9
|
11 | hosting::add_to_waitlist();
| ^^^^^^^ use of undeclared crate or module `hosting`
|
help: consider importing this module through its public re-export
|
10 + use crate::hosting;
|
warning: unused import: `crate::front_of_house::hosting`
--&gt; src/lib.rs:7:5
|
7 | use crate::front_of_house::hosting;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
For more information about this error, try `rustc --explain E0433`.
warning: `restaurant` (lib) generated 1 warning
error: could not compile `restaurant` (lib) due to 1 previous error; 1 warning emitted
</code></pre>
<p>注意这里还有一个警告说 <code>use</code> 在其作用域内不再被使用!为了修复这个问题,可以将 <code>use</code> 移动到 <code>customer</code> 模块内,或者在子模块 <code>customer</code> 内通过 <code>super::hosting</code> 引用父模块中的这个短路径。</p>
<h3 id="创建惯用的-use-路径"><a class="header" href="#创建惯用的-use-路径">创建惯用的 <code>use</code> 路径</a></h3>
<p>在示例 7-11 中,你可能会比较疑惑,为什么我们是指定 <code>use crate::front_of_house::hosting</code> ,然后在 <code>eat_at_restaurant</code> 中调用 <code>hosting::add_to_waitlist</code> ,而不是通过指定一直到 <code>add_to_waitlist</code> 函数的 <code>use</code> 路径来得到相同的结果,如示例 7-13 所示。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground test_harness">mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting::add_to_waitlist;
pub fn eat_at_restaurant() {
add_to_waitlist();
}</code></pre>
<p><span class="caption">示例 7-13: 使用 <code>use</code><code>add_to_waitlist</code> 函数引入作用域,这并不符合习惯</span></p>
<p>虽然示例 7-11 和 7-13 都完成了相同的任务,但示例 7-11 是使用 <code>use</code> 将函数引入作用域的习惯用法。要想使用 <code>use</code> 将函数的父模块引入作用域,我们必须在调用函数时指定父模块,这样可以清晰地表明函数不是在本地定义的,同时使完整路径的重复度最小化。示例 7-13 中的代码不清楚 <code>add_to_waitlist</code> 是在哪里被定义的。</p>
<p>另一方面,使用 <code>use</code> 引入结构体、枚举和其他项时,习惯是指定它们的完整路径。示例 7-14 展示了将 <code>HashMap</code> 结构体引入二进制 crate 作用域的习惯用法。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert(1, 2);
}</code></pre></pre>
<p><span class="caption">示例 7-14: 将 <code>HashMap</code> 引入作用域的习惯用法</span></p>
<p>这种习惯用法背后没有什么硬性要求:它只是一种惯例,人们已经习惯了以这种方式阅读和编写 Rust 代码。</p>
<p>这个习惯用法有一个例外,那就是我们想使用 <code>use</code> 语句将两个具有相同名称的项带入作用域,因为 Rust 不允许这样做。示例 7-15 展示了如何将两个具有相同名称但不同父模块的 <code>Result</code> 类型引入作用域,以及如何引用它们。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::fmt;
use std::io;
fn function1() -&gt; fmt::Result {
// --snip--
<span class="boring"> Ok(())
</span>}
fn function2() -&gt; io::Result&lt;()&gt; {
// --snip--
<span class="boring"> Ok(())
</span>}</code></pre>
<p><span class="caption">示例 7-15: 使用父模块将两个具有相同名称的类型引入同一作用域</span></p>
<p>如你所见,使用父模块可以区分这两个 <code>Result</code> 类型。如果我们是指定 <code>use std::fmt::Result</code><code>use std::io::Result</code>,我们将在同一作用域拥有了两个 <code>Result</code> 类型,当我们使用 <code>Result</code>Rust 则不知道我们要用的是哪个。</p>
<h3 id="使用-as-关键字提供新的名称"><a class="header" href="#使用-as-关键字提供新的名称">使用 <code>as</code> 关键字提供新的名称</a></h3>
<p>使用 <code>use</code> 将两个同名类型引入同一作用域这个问题还有另一个解决办法:在这个类型的路径后面,我们使用 <code>as</code> 指定一个新的本地名称或者别名。示例 7-16 展示了另一个编写示例 7-15 中代码的方法,通过 <code>as</code> 重命名其中一个 <code>Result</code> 类型。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::fmt::Result;
use std::io::Result as IoResult;
fn function1() -&gt; Result {
// --snip--
<span class="boring"> Ok(())
</span>}
fn function2() -&gt; IoResult&lt;()&gt; {
// --snip--
<span class="boring"> Ok(())
</span>}</code></pre>
<p><span class="caption">示例 7-16: 使用 <code>as</code> 关键字重命名引入作用域的类型</span></p>
<p>在第二个 <code>use</code> 语句中,我们选择 <code>IoResult</code> 作为 <code>std::io::Result</code> 的新名称,它与从 <code>std::fmt</code> 引入作用域的 <code>Result</code> 并不冲突。示例 7-15 和示例 7-16 都是惯用的,如何选择都取决于你!</p>
<h3 id="使用-pub-use-重导出名称"><a class="header" href="#使用-pub-use-重导出名称">使用 <code>pub use</code> 重导出名称</a></h3>
<p>使用 <code>use</code> 关键字,将某个名称导入当前作用域后,这个名称在此作用域中就可以使用了,但它对此作用域之外还是私有的。如果想让其他人调用我们的代码时,也能够正常使用这个名称,就好像它本来就在当前作用域一样,那我们可以将 <code>pub</code><code>use</code> 合起来使用。这种技术被称为 “<em>重导出</em><em>re-exporting</em>)”:我们不仅将一个名称导入了当前作用域,还允许别人把它导入他们自己的作用域。</p>
<p>示例 7-17 将示例 7-11 根模块中的 <code>use</code> 改为 <code>pub use</code></p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground test_harness">mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}</code></pre>
<p><span class="caption">示例 7-17: 通过 <code>pub use</code> 使名称可从新作用域中被导入至任何代码</span></p>
<p>在这个修改之前,外部代码需要使用路径 <code>restaurant::front_of_house::hosting::add_to_waitlist()</code> 来调用 <code>add_to_waitlist</code> 函数。现在这个 <code>pub use</code> 从根模块重导出了 <code>hosting</code> 模块,外部代码现在可以使用路径 <code>restaurant::hosting::add_to_waitlist</code></p>
<p>当你代码的内部结构与调用你代码的程序员所想象的结构不同时,重导出会很有用。例如,在这个餐馆的比喻中,经营餐馆的人会想到“前台”和“后台”。但顾客在光顾一家餐馆时,可能不会以这些术语来考虑餐馆的各个部分。使用 <code>pub use</code>,我们可以使用一种结构编写代码,却将不同的结构形式暴露出来。这样做使我们的库井井有条,也使开发这个库的程序员和调用这个库的程序员都更加方便。在<a href="ch14-02-publishing-to-crates-io.html#%E4%BD%BF%E7%94%A8-pub-use-%E5%AF%BC%E5%87%BA%E5%90%88%E9%80%82%E7%9A%84%E5%85%AC%E6%9C%89-api">“使用 <code>pub use</code> 导出合适的公有 API”</a>部分让我们再看另一个 <code>pub use</code> 的例子来了解这如何影响 crate 的文档。</p>
<h3 id="使用外部包"><a class="header" href="#使用外部包">使用外部包</a></h3>
<p>在第二章中我们编写了一个猜猜看游戏。那个项目使用了一个外部包,<code>rand</code>,来生成随机数。为了在项目中使用 <code>rand</code>,在 <em>Cargo.toml</em> 中加入了如下行:</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">rand = "0.8.5"
</code></pre>
<p><em>Cargo.toml</em> 中加入 <code>rand</code> 依赖告诉了 Cargo 要从 <a href="https://crates.io">crates.io</a> 下载 <code>rand</code> 和其依赖,并使其可在项目代码中使用。</p>
<p>接着,为了将 <code>rand</code> 定义引入项目包的作用域,我们加入一行 <code>use</code> 起始的包名,它以 <code>rand</code> 包名开头并列出了需要引入作用域的项。回忆一下第二章的 “生成一个随机数” 部分,我们曾将 <code>Rng</code> trait 引入作用域并调用了 <code>rand::thread_rng</code> 函数:</p>
<pre><code class="language-rust ignore"><span class="boring">use std::io;
</span>use rand::Rng;
fn main() {
<span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span> let secret_number = rand::thread_rng().gen_range(1..=100);
<span class="boring">
</span><span class="boring"> println!("The secret number is: {secret_number}");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {guess}");
</span>}</code></pre>
<p><a href="https://crates.io">crates.io</a> 上有很多 Rust 社区成员发布的包,将其引入你自己的项目都需要一道相同的步骤:在 <em>Cargo.toml</em> 列出它们并通过 <code>use</code> 将其中定义的项引入项目包的作用域中。</p>
<p>注意 <code>std</code> 标准库对于你的包来说也是外部 crate。因为标准库随 Rust 语言一同分发,无需修改 <em>Cargo.toml</em> 来引入 <code>std</code>,不过需要通过 <code>use</code> 将标准库中定义的项引入项目包的作用域中来引用它们,比如我们使用的 <code>HashMap</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::collections::HashMap;
<span class="boring">}</span></code></pre></pre>
<p>这是一个以标准库 crate 名 <code>std</code> 开头的绝对路径。</p>
<h3 id="嵌套路径来消除大量的-use-行"><a class="header" href="#嵌套路径来消除大量的-use-行">嵌套路径来消除大量的 <code>use</code></a></h3>
<p>当需要引入很多定义于相同包或相同模块的项时,为每一项单独列出一行会占用源码很大的空间。例如猜猜看章节示例 2-4 中有两行 <code>use</code> 语句都从 <code>std</code> 引入项到作用域:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use rand::Rng;
</span>// --snip--
use std::cmp::Ordering;
use std::io;
// --snip--
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span><span class="boring"> println!("The secret number is: {secret_number}");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {guess}");
</span><span class="boring">
</span><span class="boring"> match guess.cmp(&amp;secret_number) {
</span><span class="boring"> Ordering::Less =&gt; println!("Too small!"),
</span><span class="boring"> Ordering::Greater =&gt; println!("Too big!"),
</span><span class="boring"> Ordering::Equal =&gt; println!("You win!"),
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>相反,我们可以使用嵌套路径将相同的项在一行中引入作用域。这么做需要指定路径的相同部分,接着是两个冒号,接着是大括号中的各自不同的路径部分,如示例 7-18 所示。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use rand::Rng;
</span>// --snip--
use std::{cmp::Ordering, io};
// --snip--
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span><span class="boring"> println!("The secret number is: {secret_number}");
</span><span class="boring">
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span><span class="boring"> let guess: u32 = guess.trim().parse().expect("Please type a number!");
</span><span class="boring">
</span><span class="boring"> println!("You guessed: {guess}");
</span><span class="boring">
</span><span class="boring"> match guess.cmp(&amp;secret_number) {
</span><span class="boring"> Ordering::Less =&gt; println!("Too small!"),
</span><span class="boring"> Ordering::Greater =&gt; println!("Too big!"),
</span><span class="boring"> Ordering::Equal =&gt; println!("You win!"),
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 7-18: 指定嵌套的路径在一行中将多个带有相同前缀的项引入作用域</span></p>
<p>在较大的程序中,使用嵌套路径从相同包或模块中引入很多项,可以显著减少所需的独立 <code>use</code> 语句的数量!</p>
<p>我们可以在路径的任何层级使用嵌套路径,这在组合两个共享子路径的 <code>use</code> 语句时非常有用。例如,示例 7-19 中展示了两个 <code>use</code> 语句:一个将 <code>std::io</code> 引入作用域,另一个将 <code>std::io::Write</code> 引入作用域:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::io;
use std::io::Write;</code></pre>
<p><span class="caption">示例 7-19: 通过两行 <code>use</code> 语句引入两个路径,其中一个是另一个的子路径</span></p>
<p>两个路径的相同部分是 <code>std::io</code>,这正是第一个路径。为了在一行 <code>use</code> 语句中引入这两个路径,可以在嵌套路径中使用 <code>self</code>,如示例 7-20 所示。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::io::{self, Write};</code></pre>
<p><span class="caption">示例 7-20: 将示例 7-19 中部分重复的路径合并为一个 <code>use</code> 语句</span></p>
<p>这一行便将 <code>std::io</code><code>std::io::Write</code> 同时引入作用域。</p>
<h3 id="通过-glob-运算符将所有的公有定义引入作用域"><a class="header" href="#通过-glob-运算符将所有的公有定义引入作用域">通过 glob 运算符将所有的公有定义引入作用域</a></h3>
<p>如果希望将一个路径下 <strong>所有</strong> 公有项引入作用域,可以指定路径后跟 <code>*</code>glob 运算符:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::collections::*;
<span class="boring">}</span></code></pre></pre>
<p>这个 <code>use</code> 语句将 <code>std::collections</code> 中定义的所有公有项引入当前作用域。使用 glob 运算符时请多加小心Glob 会使得我们难以推导作用域中有什么名称和它们是在何处定义的。</p>
<p>glob 运算符经常用于测试模块 <code>tests</code> 中,这时会将所有内容引入作用域;我们将在第十一章 “如何编写测试” 部分讲解。glob 运算符有时也用于 prelude 模式;查看 <a href="https://doc.rust-lang.org/std/prelude/index.html#other-preludes">标准库中的文档</a> 了解这个模式的更多细节。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="将模块拆分成多个文件"><a class="header" href="#将模块拆分成多个文件">将模块拆分成多个文件</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch07-05-separating-modules-into-different-files.md">ch07-05-separating-modules-into-different-files.md</a>
<br>
commit 2b4565662d1a7973d870744a923f58f8f7dcce91</p>
</blockquote>
<p>到目前为止,本章所有的例子都在一个文件中定义多个模块。当模块变得更大时,你可能想要将它们的定义移动到单独的文件中,从而使代码更容易阅读。</p>
<p>例如,我们从示例 7-17 中包含多个餐厅模块的代码开始。我们会将模块提取到各自的文件中,而不是将所有模块都定义到 crate 根文件中。在这里crate 根文件是 <em>src/lib.rs</em>,不过这个过程也适用于 crate 根文件是 <em>src/main.rs</em> 的二进制 crate。</p>
<p>首先将 <code>front_of_house</code> 模块提取到其自己的文件中。删除 <code>front_of_house</code> 模块的大括号中的代码,只留下 <code>mod front_of_house;</code> 声明,这样 <em>src/lib.rs</em> 会包含如示例 7-21 所示的代码。注意直到创建示例 7-22 中的 <em>src/front_of_house.rs</em> 文件之前代码都不能编译。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">mod front_of_house;
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}</code></pre>
<p><span class="caption">示例 7-21: 声明 <code>front_of_house</code> 模块,其内容将位于 <em>src/front_of_house.rs</em></span></p>
<p>接下来将之前大括号内的代码放入一个名叫 <em>src/front_of_house.rs</em> 的新文件中,如示例 7-22 所示。因为编译器找到了 crate 根中名叫 <code>front_of_house</code> 的模块声明,它就知道去搜寻这个文件。</p>
<p><span class="filename">文件名src/front_of_house.rs</span></p>
<pre><code class="language-rust ignore">pub mod hosting {
pub fn add_to_waitlist() {}
}</code></pre>
<p><span class="caption">示例 7-22: 在 <em>src/front_of_house.rs</em> 中定义 <code>front_of_house</code>
模块</span></p>
<p>注意你只需在模块树中的某处使用一次 <code>mod</code> 声明就可以加载这个文件。一旦编译器知道了这个文件是项目的一部分(并且通过 <code>mod</code> 语句的位置知道了代码在模块树中的位置),项目中的其他文件应该使用其所声明的位置的路径来引用那个文件的代码,这在<a href="ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html">“引用模块项目的路径”</a>部分有讲到。换句话说,<code>mod</code> <strong>不是</strong> 你可能会在其他编程语言中看到的 "include" 操作。</p>
<p>接下来我们同样将 <code>hosting</code> 模块提取到自己的文件中。这个过程会有所不同,因为 <code>hosting</code><code>front_of_house</code> 的子模块而不是根模块。我们将 <code>hosting</code> 的文件放在与模块树中它的父级模块同名的目录中,在这里是 <em>src/front_of_house/</em></p>
<p>为了移动 <code>hosting</code>,修改 <em>src/front_of_house.rs</em> 使之仅包含 <code>hosting</code> 模块的声明。</p>
<p><span class="filename">文件名src/front_of_house.rs</span></p>
<pre><code class="language-rust ignore">pub mod hosting;</code></pre>
<p>接着我们创建一个 <em>src/front_of_house</em> 目录和一个包含 <code>hosting</code> 模块定义的 <em>hosting.rs</em> 文件:</p>
<p><span class="filename">文件名src/front_of_house/hosting.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn add_to_waitlist() {}
<span class="boring">}</span></code></pre></pre>
<p>如果将 <em>hosting.rs</em> 放在 <em>src</em> 目录,编译器会认为 <code>hosting</code> 模块中的 <em>hosting.rs</em> 的代码声明于 crate 根,而不是声明为 <code>front_of_house</code> 的子模块。编译器所遵循的哪些文件对应哪些模块的代码的规则,意味着目录和文件更接近于模块树。</p>
<blockquote>
<h3 id="另一种文件路径"><a class="header" href="#另一种文件路径">另一种文件路径</a></h3>
<p>目前为止我们介绍了 Rust 编译器所最常用的文件路径;不过一种更老的文件路径也仍然是支持的。</p>
<p>对于声明于 crate 根的 <code>front_of_house</code> 模块,编译器会在如下位置查找模块代码:</p>
<ul>
<li><em>src/front_of_house.rs</em>(我们所介绍的)</li>
<li><em>src/front_of_house/mod.rs</em>(老风格,不过仍然支持)</li>
</ul>
<p>对于 <code>front_of_house</code> 的子模块 <code>hosting</code>,编译器会在如下位置查找模块代码:</p>
<ul>
<li><em>src/front_of_house/hosting.rs</em>(我们所介绍的)</li>
<li><em>src/front_of_house/hosting/mod.rs</em>(老风格,不过仍然支持)</li>
</ul>
<p>如果你对同一模块同时使用这两种路径风格,会得到一个编译错误。在同一项目中的不同模块混用不同的路径风格是允许的,不过这会使他人感到疑惑。</p>
<p>使用 <em>mod.rs</em> 这一文件名的风格的主要缺点是会导致项目中出现很多 <em>mod.rs</em> 文件,当你在编辑器中同时打开它们时会感到疑惑。</p>
</blockquote>
<p>我们将各个模块的代码移动到独立文件了,同时模块树依旧相同。<code>eat_at_restaurant</code> 中的函数调用也无需修改继续保持有效,即便其定义存在于不同的文件中。这个技巧让你可以在模块代码增长时,将它们移动到新文件中。</p>
<p>注意,<em>src/lib.rs</em> 中的 <code>pub use crate::front_of_house::hosting</code> 语句也并未发生改变。use 也不会对哪些文件会被编译为 crate 的一部分有任何影响。<code>mod</code> 关键字声明了模块,而 Rust 会在与模块同名的文件中查找模块的代码。</p>
<h2 id="总结-6"><a class="header" href="#总结-6">总结</a></h2>
<p>Rust 提供了将包分成多个 crate将 crate 分成模块,以及通过指定绝对或相对路径从一个模块引用另一个模块中定义的项的方式。你可以通过使用 <code>use</code> 语句将路径引入作用域,这样在多次使用时可以使用更短的路径。模块定义的代码默认是私有的,不过可以选择增加 <code>pub</code> 关键字使其定义变为公有。</p>
<p>接下来,让我们看看一些标准库提供的集合数据类型,你可以利用它们编写出漂亮整洁的代码。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="常见集合"><a class="header" href="#常见集合">常见集合</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch08-00-common-collections.md">ch08-00-common-collections.md</a>
<br>
commit 1fd890031311612e54965f7f800a8c8bd4464663</p>
</blockquote>
<p>Rust 标准库中包含一系列被称为 <strong>集合</strong><em>collections</em>)的非常有用的数据结构。大部分其他数据类型都代表一个特定的值,不过集合可以包含多个值。不同于内建的数组和元组类型,这些集合指向的数据是储存在堆上的,这意味着数据的数量不必在编译时就已知,并且还可以随着程序的运行增长或缩小。每种集合都有着不同功能和成本,而根据当前情况选择合适的集合,这是一项应当逐渐掌握的技能。在这一章里,我们将详细的了解三个在 Rust 程序中被广泛使用的集合:</p>
<ul>
<li><em>vector</em> 允许我们一个挨着一个地储存一系列数量可变的值</li>
<li><strong>字符串</strong><em>string</em>)是字符的集合。我们之前见过 <code>String</code> 类型,不过在本章我们将深入了解。</li>
<li><strong>哈希 map</strong><em>hash map</em>允许我们将值与一个特定的键key相关联。这是一个叫做 <em>map</em> 的更通用的数据结构的特定实现。</li>
</ul>
<p>对于标准库提供的其他类型的集合,请查看<a href="https://doc.rust-lang.org/std/collections/index.html">文档</a></p>
<p>我们将讨论如何创建和更新 vector、字符串和哈希 map以及它们有什么特别之处。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用-vector-储存列表"><a class="header" href="#使用-vector-储存列表">使用 Vector 储存列表</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch08-01-vectors.md">ch08-01-vectors.md</a>
<br>
commit ac16184a7f56d17daa9c4c76901371085dc0ac43</p>
</blockquote>
<p>我们要讲到的第一个类型是 <code>Vec&lt;T&gt;</code>,也被称为 <em>vector</em>。vector 允许我们在一个单独的数据结构中储存多于一个的值它在内存中彼此相邻地排列所有的值。vector 只能储存相同类型的值。它们在拥有一系列项的场景下非常实用,例如文件中的文本行或是购物车中商品的价格。</p>
<h3 id="新建-vector"><a class="header" href="#新建-vector">新建 vector</a></h3>
<p>为了创建一个新的空 vector可以调用 <code>Vec::new</code> 函数,如示例 8-1 所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let v: Vec&lt;i32&gt; = Vec::new();
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-1新建一个空的 vector 来储存 <code>i32</code> 类型的值</span></p>
<p>注意这里我们增加了一个类型注解。因为没有向这个 vector 中插入任何值Rust 并不知道我们想要储存什么类型的元素。这是一个非常重要的点。vector 是用泛型实现的,第十章会涉及到如何对你自己的类型使用它们。现在,所有你需要知道的就是 <code>Vec&lt;T&gt;</code> 是一个由标准库提供的类型,它可以存放任何类型,而当 <code>Vec</code> 存放某个特定类型时,那个类型位于尖括号中。在示例 8-1 中,我们告诉 Rust <code>v</code> 这个 <code>Vec&lt;T&gt;</code> 将存放 <code>i32</code> 类型的元素。</p>
<p>通常,我们会用初始值来创建一个 <code>Vec&lt;T&gt;</code> 而 Rust 会推断出储存值的类型,所以很少会需要这些类型注解。为了方便 Rust 提供了 <code>vec!</code> 宏,这个宏会根据我们提供的值来创建一个新的 vector。示例 8-2 新建一个拥有值 <code>1</code><code>2</code><code>3</code><code>Vec&lt;i32&gt;</code>。推断为 <code>i32</code> 是因为这是默认整型类型,第三章的 <a href="ch03-02-data-types.html#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">“数据类型”</a> 讨论过:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let v = vec![1, 2, 3];
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-2新建一个包含初值的 vector</span></p>
<p>因为我们提供了 <code>i32</code> 类型的初始值Rust 可以推断出 <code>v</code> 的类型是 <code>Vec&lt;i32&gt;</code>,因此类型注解就不是必须的。接下来让我们看看如何修改一个 vector。</p>
<h3 id="更新-vector"><a class="header" href="#更新-vector">更新 vector</a></h3>
<p>对于新建一个 vector 并向其增加元素,可以使用 <code>push</code> 方法,如示例 8-3 所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-3使用 <code>push</code> 方法向 vector 增加值</span></p>
<p>如第三章中讨论的任何变量一样,如果想要能够改变它的值,必须使用 <code>mut</code> 关键字使其可变。放入其中的所有值都是 <code>i32</code> 类型的,而且 Rust 也根据数据做出如此判断,所以不需要 <code>Vec&lt;i32&gt;</code> 注解。</p>
<h3 id="读取-vector-的元素"><a class="header" href="#读取-vector-的元素">读取 vector 的元素</a></h3>
<p>有两种方法引用 vector 中储存的值:通过索引或使用 <code>get</code> 方法。在接下来的示例中,为了更加清楚的说明,我们已经标注了这些函数返回的值的类型。</p>
<p>示例 8-4 展示了访问 vector 中一个值的两种方式,索引语法或者 <code>get</code> 方法:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let v = vec![1, 2, 3, 4, 5];
let third: &amp;i32 = &amp;v[2];
println!("The third element is {third}");
let third: Option&lt;&amp;i32&gt; = v.get(2);
match third {
Some(third) =&gt; println!("The third element is {third}"),
None =&gt; println!("There is no third element."),
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">列表 8-4使用索引语法或 <code>get</code> 方法来访问 vector 中的项</span></p>
<p>这里有几个细节需要注意。我们使用索引值 <code>2</code> 来获取第三个元素,因为索引是从数字 0 开始的。使用 <code>&amp;</code><code>[]</code> 会得到一个索引位置元素的引用。当使用索引作为参数调用 <code>get</code> 方法时,会得到一个可以用于 <code>match</code><code>Option&lt;&amp;T&gt;</code></p>
<p>Rust 提供了两种引用元素的方法的原因是当尝试使用现有元素范围之外的索引值时可以选择让程序如何运行。举个例子,让我们看看使用这个技术,尝试在当有一个 5 个元素的 vector 接着访问索引 100 位置的元素会发生什么,如示例 8-5 所示:</p>
<pre><pre class="playground"><code class="language-rust should_panic panics edition2021"><span class="boring">fn main() {
</span> let v = vec![1, 2, 3, 4, 5];
let does_not_exist = &amp;v[100];
let does_not_exist = v.get(100);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-5尝试访问一个包含 5 个元素的 vector 的索引 100 处的元素</span></p>
<p>当运行这段代码,你会发现对于第一个 <code>[]</code> 方法,当引用一个不存在的元素时 Rust 会造成 panic。这个方法更适合当程序认为尝试访问超过 vector 结尾的元素是一个严重错误的情况,这时应该使程序崩溃。</p>
<p><code>get</code> 方法被传递了一个数组外的索引时,它不会 panic 而是返回 <code>None</code>。当偶尔出现超过 vector 范围的访问属于正常情况的时候可以考虑使用它。接着你的代码可以有处理 <code>Some(&amp;element)</code><code>None</code> 的逻辑,如第六章讨论的那样。例如,索引可能来源于用户输入的数字。如果它们不慎输入了一个过大的数字那么程序就会得到 <code>None</code> 值,你可以告诉用户当前 vector 元素的数量并再请求它们输入一个有效的值。这就比因为输入错误而使程序崩溃要友好的多!</p>
<p>一旦程序获取了一个有效的引用,借用检查器将会执行所有权和借用规则(第四章讲到)来确保 vector 内容的这个引用和任何其他引用保持有效。回忆一下不能在相同作用域中同时存在可变和不可变引用的规则。这个规则适用于示例 8-6当我们获取了 vector 的第一个元素的不可变引用并尝试在 vector 末尾增加一个元素的时候,如果尝试在函数的后面引用这个元素是行不通的:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let mut v = vec![1, 2, 3, 4, 5];
let first = &amp;v[0];
v.push(6);
println!("The first element is: {first}");
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 8-6在拥有 vector 中项的引用的同时向其增加一个元素</span></p>
<p>编译会给出这个错误:</p>
<pre><code class="language-console">$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--&gt; src/main.rs:6:5
|
4 | let first = &amp;v[0];
| - immutable borrow occurs here
5 |
6 | v.push(6);
| ^^^^^^^^^ mutable borrow occurs here
7 |
8 | println!("The first element is: {first}");
| ------- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `collections` (bin "collections") due to 1 previous error
</code></pre>
<p>示例 8-6 中的代码看起来应该能够运行:为什么第一个元素的引用会关心 vector 结尾的变化?不能这么做的原因是由于 vector 的工作方式:在 vector 的结尾增加新元素时,在没有足够空间将所有元素依次相邻存放的情况下,可能会要求分配新内存并将老的元素拷贝到新的空间中。这时,第一个元素的引用就指向了被释放的内存。借用规则阻止程序陷入这种状况。</p>
<blockquote>
<p>注意:关于 <code>Vec&lt;T&gt;</code> 类型的更多实现细节,请查看 <a href="https://doc.rust-lang.org/nomicon/vec/vec.html">“The Rustonomicon”</a></p>
</blockquote>
<h3 id="遍历-vector-中的元素"><a class="header" href="#遍历-vector-中的元素">遍历 vector 中的元素</a></h3>
<p>如果想要依次访问 vector 中的每一个元素,我们可以遍历其所有的元素而无需通过索引一次一个的访问。示例 8-7 展示了如何使用 <code>for</code> 循环来获取 <code>i32</code> 值的 vector 中的每一个元素的不可变引用并将其打印:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let v = vec![100, 32, 57];
for i in &amp;v {
println!("{i}");
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-7通过 <code>for</code> 循环遍历 vector 的元素并打印</span></p>
<p>我们也可以遍历可变 vector 的每一个元素的可变引用以便能改变它们。示例 8-8 中的 <code>for</code> 循环会给每一个元素加 <code>50</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut v = vec![100, 32, 57];
for i in &amp;mut v {
*i += 50;
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-8遍历 vector 中元素的可变引用</span></p>
<p>为了修改可变引用所指向的值,在使用 <code>+=</code> 运算符之前必须使用解引用运算符(<code>*</code>)获取 <code>i</code> 中的值。第十五章的 <a href="ch15-02-deref.html#%E8%BF%BD%E8%B8%AA%E6%8C%87%E9%92%88%E7%9A%84%E5%80%BC">“通过解引用运算符追踪指针的值”</a> 部分会详细介绍解引用运算符。</p>
<p>因为借用检查器的规则,无论可变还是不可变地遍历一个 vector 都是安全的。如果尝试在示例 8-7 和 示例 8-8 的 <code>for</code> 循环体内插入或删除项,都会得到一个类似示例 8-6 代码中类似的编译错误。<code>for</code> 循环中获取的 vector 引用阻止了同时对 vector 整体的修改。</p>
<h3 id="使用枚举来储存多种类型"><a class="header" href="#使用枚举来储存多种类型">使用枚举来储存多种类型</a></h3>
<p>vector 只能储存相同类型的值。这是很不方便的;绝对会有需要储存一系列不同类型的值的用例。幸运的是,枚举的成员都被定义为相同的枚举类型,所以当需要在 vector 中储存不同类型值时,我们可以定义并使用一个枚举!</p>
<p>例如,假如我们想要从电子表格的一行中获取值,而这一行的有些列包含数字,有些包含浮点值,还有些是字符串。我们可以定义一个枚举,其成员会存放这些不同类型的值,同时所有这些枚举成员都会被当作相同类型:那个枚举的类型。接着可以创建一个储存枚举值的 vector这样最终就能够储存不同类型的值了。示例 8-9 展示了其用例:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-9定义一个枚举以便能在 vector 中存放不同类型的数据</span></p>
<p>Rust 在编译时必须确切知道 vector 中的类型,这样它才能确定在堆上需要为每个元素分配多少内存。我们还必须明确这个 vector 中允许的类型。如果 Rust 允许 vector 存储任意类型,那么可能会因为一个或多个类型在对 vector 元素执行操作时导致(类型相关)错误。使用枚举加上 <code>match</code> 表达式意味着 Rust 会在编译时确保每种可能的情况都得到处理,正如第六章讲到的那样。</p>
<p>如果在编写程序时不能确切无遗地知道运行时会储存进 vector 的所有类型,枚举技术就行不通了。相反,你可以使用 trait 对象,第十八章会讲到它。</p>
<p>现在我们了解了一些使用 vector 的最常见的方式,请一定去看看标准库中 <code>Vec</code> 定义的很多其他实用方法的 <a href="https://doc.rust-lang.org/std/vec/struct.Vec.html">API 文档</a>。例如,除了 <code>push</code> 之外还有一个 <code>pop</code> 方法,它会移除并返回 vector 的最后一个元素。</p>
<h3 id="丢弃-vector-时也会丢弃其所有元素"><a class="header" href="#丢弃-vector-时也会丢弃其所有元素">丢弃 vector 时也会丢弃其所有元素</a></h3>
<p>类似于任何其他的 <code>struct</code>vector 在其离开作用域时会被释放,如示例 8-4 所标注的:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> {
let v = vec![1, 2, 3, 4];
// do stuff with v
} // &lt;- v goes out of scope and is freed here
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-10展示 vector 和其元素于何处被丢弃</span></p>
<p>当 vector 被丢弃时,所有其内容也会被丢弃,这意味着这里它包含的整数将被清理。借用检查器确保了任何 vector 中内容的引用仅在 vector 本身有效时才可用。</p>
<p>让我们继续下一个集合类型:<code>String</code></p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用字符串储存-utf-8-编码的文本"><a class="header" href="#使用字符串储存-utf-8-编码的文本">使用字符串储存 UTF-8 编码的文本</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch08-02-strings.md">ch08-02-strings.md</a>
<br>
commit 668c64760b5c7ea654facb4ba5fe9faddfda27cc</p>
</blockquote>
<p>第四章已经讲过一些字符串的内容,不过现在让我们更深入地了解它。字符串是新晋 Rustacean 们通常会被困住的领域这是由于三方面理由的结合Rust 倾向于确保暴露出可能的错误,字符串是比很多程序员所想象的要更为复杂的数据结构,以及 UTF-8。所有这些要素结合起来对于来自其他语言背景的程序员就可能显得很困难了。</p>
<p>在集合章节中讨论字符串的原因是,字符串就是作为字节的集合外加一些方法实现的,当这些字节被解释为文本时,这些方法提供了实用的功能。在这一部分,我们会讲到 <code>String</code> 中那些任何集合类型都有的操作,比如创建、更新和读取。也会讨论 <code>String</code> 与其他集合不一样的地方,例如索引 <code>String</code> 是很复杂的,由于人和计算机理解 <code>String</code> 数据方式的不同。</p>
<h3 id="什么是字符串"><a class="header" href="#什么是字符串">什么是字符串?</a></h3>
<p>在开始深入这些方面之前,我们需要讨论一下术语 <strong>字符串</strong> 的具体意义。Rust 的核心语言中只有一种字符串类型:字符串 slice <code>str</code>,它通常以被借用的形式出现,<code>&amp;str</code>。第四章讲到了 <strong>字符串 slices</strong>:它们是一些对储存在别处的 UTF-8 编码字符串数据的引用。举例来说,由于字符串字面值被储存在程序的二进制输出中,因此字符串字面值也是字符串 slices。</p>
<p>字符串(<code>String</code>)类型由 Rust 标准库提供而不是编入核心语言它是一种可增长、可变、可拥有、UTF-8 编码的字符串类型。当 Rustaceans 提及 Rust 中的 "字符串 "时,他们可能指的是 <code>String</code> 或 string slice <code>&amp;str</code> 类型,而不仅仅是其中一种类型。虽然本节主要讨论 <code>String</code>,但这两种类型在 Rust 的标准库中都有大量使用,而且 <code>String</code> 和 字符串 slices 都是 UTF-8 编码的。</p>
<h3 id="新建字符串"><a class="header" href="#新建字符串">新建字符串</a></h3>
<p>很多 <code>Vec</code> 可用的操作在 <code>String</code> 中同样可用,事实上 <code>String</code> 被实现为一个带有一些额外保证、限制和功能的字节 vector 的封装。其中一个同样作用于 <code>Vec&lt;T&gt;</code><code>String</code> 函数的例子是用来新建一个实例的 <code>new</code> 函数,如示例 8-11 所示。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut s = String::new();
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-11新建一个空的 <code>String</code></span></p>
<p>这新建了一个叫做 <code>s</code> 的空的字符串,接着我们可以向其中装载数据。通常字符串会有初始数据,因为我们希望一开始就有这个字符串。为此,可以使用 <code>to_string</code> 方法,它能用于任何实现了 <code>Display</code> trait 的类型,比如字符串字面值。示例 8-12 展示了两个例子。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let data = "initial contents";
let s = data.to_string();
// 该方法也可直接用于字符串字面值:
let s = "initial contents".to_string();
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-12使用 <code>to_string</code> 方法从字符串字面值创建 <code>String</code></span></p>
<p>这些代码会创建包含 <code>initial contents</code> 的字符串。</p>
<p>也可以使用 <code>String::from</code> 函数来从字符串字面值创建 <code>String</code>。示例 8-13 中的代码等同于使用 <code>to_string</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s = String::from("initial contents");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-13使用 <code>String::from</code> 函数从字符串字面值创建 <code>String</code></span></p>
<p>因为字符串应用广泛,这里有很多不同的用于字符串的通用 API 可供选择。其中一些可能看起来多余,不过都有其用武之地!在这个例子中,<code>String::from</code><code>.to_string</code> 最终做了完全相同的工作,所以如何选择就是代码风格与可读性的问题了。</p>
<p>记住字符串是 UTF-8 编码的,所以可以包含任何可以正确编码的数据,如示例 8-14 所示。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let hello = String::from("السلام عليكم");
let hello = String::from("Dobrý den");
let hello = String::from("Hello");
let hello = String::from("שלום");
let hello = String::from("नमस्ते");
let hello = String::from("こんにちは");
let hello = String::from("안녕하세요");
let hello = String::from("你好");
let hello = String::from("Olá");
let hello = String::from("Здравствуйте");
let hello = String::from("Hola");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-14在字符串中储存不同语言的问候语</span></p>
<p>所有这些都是有效的 <code>String</code> 值。</p>
<h3 id="更新字符串"><a class="header" href="#更新字符串">更新字符串</a></h3>
<p><code>String</code> 的大小可以增加,其内容也可以改变,就像可以放入更多数据来改变 <code>Vec</code> 的内容一样。另外,可以方便的使用 <code>+</code> 运算符或 <code>format!</code> 宏来拼接 <code>String</code> 值。</p>
<h4 id="使用-push_str-和-push-附加字符串"><a class="header" href="#使用-push_str-和-push-附加字符串">使用 <code>push_str</code><code>push</code> 附加字符串</a></h4>
<p>可以通过 <code>push_str</code> 方法来附加字符串 slice从而使 <code>String</code> 变长,如示例 8-15 所示。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut s = String::from("foo");
s.push_str("bar");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-15使用 <code>push_str</code> 方法向 <code>String</code> 附加字符串 slice</span></p>
<p>执行这两行代码之后,<code>s</code> 将会包含 <code>foobar</code><code>push_str</code> 方法采用字符串 slice因为我们并不需要获取参数的所有权。例如示例 8-16 中我们希望在将 <code>s2</code> 的内容附加到 <code>s1</code> 之后还能使用它。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2);
println!("s2 is {s2}");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-16将字符串 slice 的内容附加到 <code>String</code> 后使用它</span></p>
<p>如果 <code>push_str</code> 方法获取了 <code>s2</code> 的所有权,就不能在最后一行打印出其值了。好在代码如我们期望那样工作!</p>
<p><code>push</code> 方法被定义为获取一个单独的字符作为参数,并附加到 <code>String</code> 中。示例 8-17 展示了使用 <code>push</code> 方法将字母 "l" 加入 <code>String</code> 的代码。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut s = String::from("lo");
s.push('l');
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-17使用 <code>push</code> 将一个字符加入 <code>String</code> 值中</span></p>
<p>执行这些代码之后,<code>s</code> 将会包含 “lol”。</p>
<h4 id="使用--运算符或-format-宏拼接字符串"><a class="header" href="#使用--运算符或-format-宏拼接字符串">使用 <code>+</code> 运算符或 <code>format!</code> 宏拼接字符串</a></h4>
<p>通常你会希望将两个已知的字符串合并在一起。一种办法是像这样使用 <code>+</code> 运算符,如示例 8-18 所示。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &amp;s2; // 注意 s1 被移动了,不能继续使用
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-18使用 <code>+</code> 运算符将两个 <code>String</code> 值合并到一个新的 <code>String</code> 值中</span></p>
<p>执行完这些代码之后,字符串 <code>s3</code> 将会包含 <code>Hello, world!</code><code>s1</code> 在相加后不再有效的原因,和使用 <code>s2</code> 的引用的原因,与使用 <code>+</code> 运算符时调用的函数签名有关。<code>+</code> 运算符使用了 <code>add</code> 函数,这个函数签名看起来像这样:</p>
<pre><code class="language-rust ignore">fn add(self, s: &amp;str) -&gt; String {</code></pre>
<p>在标准库中你会发现,<code>add</code> 的定义使用了泛型和关联类型。在这里我们替换为了具体类型,这也正是当使用 <code>String</code> 值调用这个方法会发生的。第十章会讨论泛型。这个签名提供了理解 <code>+</code> 运算那微妙部分的线索。</p>
<p>首先,<code>s2</code> 使用了 <code>&amp;</code>,意味着我们使用第二个字符串的 <strong>引用</strong> 与第一个字符串相加。这是因为 <code>add</code> 函数的 <code>s</code> 参数:只能将 <code>&amp;str</code><code>String</code> 相加,不能将两个 <code>String</code> 值相加。不过等一下 —— <code>&amp;s2</code> 的类型是 <code>&amp;String</code>, 而不是 <code>add</code> 第二个参数所指定的 <code>&amp;str</code>。那么为什么示例 8-18 还能编译呢?</p>
<p>之所以能够在 <code>add</code> 调用中使用 <code>&amp;s2</code> 是因为 <code>&amp;String</code> 可以被 <strong>强转</strong><em>coerced</em>)成 <code>&amp;str</code>。当<code>add</code>函数被调用时Rust 使用了一个被称为 <strong>Deref 强制转换</strong><em>deref coercion</em>)的技术,你可以将其理解为它把 <code>&amp;s2</code> 变成了 <code>&amp;s2[..]</code>。第十五章会更深入的讨论 Deref 强制转换。因为 <code>add</code> 没有获取参数的所有权,所以 <code>s2</code> 在这个操作后仍然是有效的 <code>String</code></p>
<p>其次,可以发现签名中 <code>add</code> 获取了 <code>self</code> 的所有权,因为 <code>self</code> <strong>没有</strong> 使用 <code>&amp;</code>。这意味着示例 8-18 中的 <code>s1</code> 的所有权将被移动到 <code>add</code> 调用中,之后就不再有效。所以虽然 <code>let s3 = s1 + &amp;s2;</code> 看起来就像它会复制两个字符串并创建一个新的字符串,而实际上这个语句会获取 <code>s1</code> 的所有权,附加上从 <code>s2</code> 中拷贝的内容,并返回结果的所有权。换句话说,它看起来好像生成了很多拷贝,不过实际上并没有:这个实现比拷贝要更高效。</p>
<p>如果想要级联多个字符串,<code>+</code> 的行为就显得笨重了:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = s1 + "-" + &amp;s2 + "-" + &amp;s3;
<span class="boring">}</span></code></pre></pre>
<p>这时 <code>s</code> 的内容会是 “tic-tac-toe”。在有这么多 <code>+</code><code>"</code> 字符的情况下,很难理解具体发生了什么。对于更为复杂的字符串链接,可以使用 <code>format!</code> 宏:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{s1}-{s2}-{s3}");
<span class="boring">}</span></code></pre></pre>
<p>这些代码也会将 <code>s</code> 设置为 “tic-tac-toe”。<code>format!</code><code>println!</code> 的工作原理相同,不过不同于将输出打印到屏幕上,它返回一个带有结果内容的 <code>String</code>。这个版本就好理解的多,宏 <code>format!</code> 生成的代码使用引用所以不会获取任何参数的所有权。</p>
<h3 id="索引字符串"><a class="header" href="#索引字符串">索引字符串</a></h3>
<p>在很多语言中,通过索引来引用字符串中的单独字符是有效且常见的操作。然而在 Rust 中,如果你尝试使用索引语法访问 <code>String</code> 的一部分,会出现一个错误。考虑一下如示例 8-19 中所示的无效代码。</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let h = s1[0];
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 8-19尝试对字符串使用索引语法</span></p>
<p>这段代码会导致如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0277]: the type `str` cannot be indexed by `{integer}`
--&gt; src/main.rs:3:16
|
3 | let h = s1[0];
| ^ string indices are ranges of `usize`
|
= help: the trait `SliceIndex&lt;str&gt;` is not implemented for `{integer}`, which is required by `String: Index&lt;_&gt;`
= note: you can use `.chars().nth()` or `.bytes().nth()`
for more information, see chapter 8 in The Book: &lt;https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings&gt;
= help: the trait `SliceIndex&lt;[_]&gt;` is implemented for `usize`
= help: for that trait implementation, expected `[_]`, found `str`
= note: required for `String` to implement `Index&lt;{integer}&gt;`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `collections` (bin "collections") due to 1 previous error
</code></pre>
<p>错误和提示说明了全部问题Rust 的字符串不支持索引。那么接下来的问题是,为什么不支持呢?为了回答这个问题,我们必须先聊一聊 Rust 是如何在内存中储存字符串的。</p>
<h4 id="内部表现"><a class="header" href="#内部表现">内部表现</a></h4>
<p><code>String</code> 是一个 <code>Vec&lt;u8&gt;</code> 的封装。让我们看看示例 8-14 中一些正确编码的字符串的例子。首先是这一个:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> let hello = String::from("السلام عليكم");
</span><span class="boring"> let hello = String::from("Dobrý den");
</span><span class="boring"> let hello = String::from("Hello");
</span><span class="boring"> let hello = String::from("שלום");
</span><span class="boring"> let hello = String::from("नमस्ते");
</span><span class="boring"> let hello = String::from("こんにちは");
</span><span class="boring"> let hello = String::from("안녕하세요");
</span><span class="boring"> let hello = String::from("你好");
</span><span class="boring"> let hello = String::from("Olá");
</span><span class="boring"> let hello = String::from("Здравствуйте");
</span> let hello = String::from("Hola");
<span class="boring">}</span></code></pre></pre>
<p>在这里,<code>len</code> 的值是 4这意味着储存字符串 “Hola” 的 <code>Vec</code> 的长度是四个字节:这里每一个字母的 UTF-8 编码都占用一个字节。那下面这个例子又如何呢?(注意这个字符串中的首字母是西里尔字母的 Ze 而不是数字 3。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> let hello = String::from("السلام عليكم");
</span><span class="boring"> let hello = String::from("Dobrý den");
</span><span class="boring"> let hello = String::from("Hello");
</span><span class="boring"> let hello = String::from("שלום");
</span><span class="boring"> let hello = String::from("नमस्ते");
</span><span class="boring"> let hello = String::from("こんにちは");
</span><span class="boring"> let hello = String::from("안녕하세요");
</span><span class="boring"> let hello = String::from("你好");
</span><span class="boring"> let hello = String::from("Olá");
</span> let hello = String::from("Здравствуйте");
<span class="boring"> let hello = String::from("Hola");
</span><span class="boring">}</span></code></pre></pre>
<p>当问及这个字符是多长的时候有人可能会说是 12。然而Rust 的回答是 24。这是使用 UTF-8 编码 “Здравствуйте” 所需要的字节数,这是因为每个 Unicode 标量值需要两个字节存储。因此一个字符串字节值的索引并不总是对应一个有效的 Unicode 标量值。作为演示,考虑如下无效的 Rust 代码:</p>
<pre><code class="language-rust ignore does_not_compile">let hello = "Здравствуйте";
let answer = &amp;hello[0];</code></pre>
<p>我们已经知道 <code>answer</code> 不是第一个字符 <code>3</code>。当使用 UTF-8 编码时,(西里尔字母的 Ze<code>З</code> 的第一个字节是 <code>208</code>,第二个是 <code>151</code>,所以 <code>answer</code> 实际上应该是 <code>208</code>,不过 <code>208</code> 自身并不是一个有效的字母。返回 <code>208</code> 可不是一个请求字符串第一个字母的人所希望看到的,不过它是 Rust 在字节索引 0 位置所能提供的唯一数据。用户通常不会想要一个字节值被返回。即使这个字符串只有拉丁字母,如果 <code>&amp;"hello"[0]</code> 是返回字节值的有效代码,它也会返回 <code>104</code> 而不是 <code>h</code></p>
<p>为了避免返回意外的值并造成不能立刻发现的 bugRust 根本不会编译这些代码,并在开发过程中及早杜绝了误会的发生。</p>
<h4 id="字节标量值和字形簇天呐"><a class="header" href="#字节标量值和字形簇天呐">字节、标量值和字形簇!天呐!</a></h4>
<p>这引起了关于 UTF-8 的另外一个问题:从 Rust 的角度来讲,事实上有三种相关方式可以理解字符串:字节、标量值和字形簇(最接近人们眼中 <strong>字母</strong> 的概念)。</p>
<p>比如这个用梵文书写的印度语单词 “नमस्ते”,最终它储存在 vector 中的 <code>u8</code> 值看起来像这样:</p>
<pre><code class="language-text">[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
224, 165, 135]
</code></pre>
<p>这里有 18 个字节,也就是计算机最终会储存的数据。如果从 Unicode 标量值的角度理解它们,也就像 Rust 的 <code>char</code> 类型那样,这些字节看起来像这样:</p>
<pre><code class="language-text">['न', 'म', 'स', '्', 'त', 'े']
</code></pre>
<p>这里有六个 <code>char</code>,不过第四个和第六个都不是字母,它们是发音符号本身并没有任何意义。最后,如果以字形簇的角度理解,就会得到人们所说的构成这个单词的四个字母:</p>
<pre><code class="language-text">["न", "म", "स्", "ते"]
</code></pre>
<p>Rust 提供了多种不同的方式来解释计算机储存的原始字符串数据,这样程序就可以选择它需要的表现方式,而无所谓是何种人类语言。</p>
<p>最后一个 Rust 不允许使用索引获取 <code>String</code> 字符的原因是索引操作预期总是需要常数时间O(1))。但是对于 <code>String</code> 不可能保证这样的性能,因为 Rust 必须从开头到索引位置遍历来确定有多少有效的字符。</p>
<h3 id="字符串-slice-1"><a class="header" href="#字符串-slice-1">字符串 slice</a></h3>
<p>索引字符串通常是一个坏点子,因为字符串索引应该返回的类型是不明确的:字节值、字符、字形簇或者字符串 slice。因此如果你真的希望使用索引创建字符串 slice 时Rust 会要求你更明确一些。为了更明确索引并表明你需要一个字符串 slice相比使用 <code>[]</code> 和单个值的索引,可以使用 <code>[]</code> 和一个 range 来创建含特定字节的字符串 slice</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let hello = "Здравствуйте";
let s = &amp;hello[0..4];
<span class="boring">}</span></code></pre></pre>
<p>这里,<code>s</code> 会是一个 <code>&amp;str</code>,它包含字符串的头四个字节。早些时候,我们提到了这些字母都是两个字节长的,所以这意味着 <code>s</code> 将会是 “Зд”。</p>
<p>如果获取 <code>&amp;hello[0..1]</code> 会发生什么呢答案是Rust 在运行时会 panic就跟访问 vector 中的无效索引时一样:</p>
<pre><code class="language-console">$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/collections`
thread 'main' panicked at src/main.rs:4:19:
byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>你应该小心谨慎地使用这个操作,因为这么做可能会使你的程序崩溃。</p>
<h3 id="遍历字符串的方法"><a class="header" href="#遍历字符串的方法">遍历字符串的方法</a></h3>
<p>操作字符串每一部分的最好的方法是明确表示需要字符还是字节。对于单独的 Unicode 标量值使用 <code>chars</code> 方法。对 “Зд” 调用 <code>chars</code> 方法会将其分开并返回两个 <code>char</code> 类型的值,接着就可以遍历其结果来访问每一个元素了:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>for c in "Зд".chars() {
println!("{c}");
}
<span class="boring">}</span></code></pre></pre>
<p>这些代码会打印出如下内容:</p>
<pre><code class="language-text">З
д
</code></pre>
<p>另外 <code>bytes</code> 方法返回每一个原始字节,这可能会适合你的使用场景:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>for b in "Зд".bytes() {
println!("{b}");
}
<span class="boring">}</span></code></pre></pre>
<p>这些代码会打印出组成 <code>String</code> 的 4 个字节:</p>
<pre><code class="language-text">208
151
208
180
</code></pre>
<p>不过请记住有效的 Unicode 标量值可能会由不止一个字节组成。</p>
<p>从字符串中获取如同天城文这样的字形簇是很复杂的,所以标准库并没有提供这个功能。<a href="https://crates.io/">crates.io</a><!-- ignore --> 上有些提供这样功能的 crate。</p>
<h3 id="字符串并不简单"><a class="header" href="#字符串并不简单">字符串并不简单</a></h3>
<p>总而言之字符串还是很复杂的。不同的语言选择了不同的向程序员展示其复杂性的方式。Rust 选择了以准确的方式处理 <code>String</code> 数据作为所有 Rust 程序的默认行为,这意味着程序员们必须更多的思考如何预先处理 UTF-8 数据。这种权衡取舍相比其他语言更多的暴露出了字符串的复杂性,不过也使你在开发周期后期免于处理涉及非 ASCII 字符的错误。</p>
<p>好消息是标准库提供了很多围绕 <code>String</code><code>&amp;str</code> 构建的功能,来帮助我们正确处理这些复杂场景。请务必查看这些使用方法的文档,例如 <code>contains</code> 来搜索一个字符串,和 <code>replace</code> 将字符串的一部分替换为另一个字符串。</p>
<p>称作 <code>String</code> 的类型是由标准库提供的而没有写进核心语言部分它是可增长的、可变的、有所有权的、UTF-8 编码的字符串类型。当 Rustacean 们谈到 Rust 的 “字符串”时,它们通常指的是 <code>String</code> 或字符串 slice <code>&amp;str</code> 类型,而不特指其中某一个。虽然本部分内容大多是关于 <code>String</code> 的,不过这两个类型在 Rust 标准库中都被广泛使用,<code>String</code> 和字符串 slices 都是 UTF-8 编码的。</p>
<p>现在让我们转向一些不太复杂的集合:哈希 map</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用-hash-map-储存键值对"><a class="header" href="#使用-hash-map-储存键值对">使用 Hash Map 储存键值对</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch08-03-hash-maps.md">ch08-03-hash-maps.md</a>
<br>
commit 50775360ba3904c41e84176337ff47e6e7d6177c</p>
</blockquote>
<p>最后介绍的常用集合类型是 <strong>哈希 map</strong><em>hash map</em>)。<code>HashMap&lt;K, V&gt;</code> 类型储存了一个键类型 <code>K</code> 对应一个值类型 <code>V</code> 的映射。它通过一个 <strong>哈希函数</strong><em>hashing function</em>来实现映射决定如何将键和值放入内存中。很多编程语言支持这种数据结构不过通常有不同的名字哈希、map、对象、哈希表或者关联数组仅举几例。</p>
<p>哈希 map 可以用于需要任何类型作为键来寻找数据的情况,而不是像 vector 那样通过索引。例如,在一个游戏中,你可以将每个团队的分数记录到哈希 map 中,其中键是队伍的名字而值是每个队伍的分数。给出一个队名,就能得到他们的得分。</p>
<p>本章我们会介绍哈希 map 的基本 API不过还有更多吸引人的功能隐藏于标准库在 <code>HashMap&lt;K, V&gt;</code> 上定义的函数中。一如既往请查看标准库文档来了解更多信息。</p>
<h3 id="新建一个哈希-map"><a class="header" href="#新建一个哈希-map">新建一个哈希 map</a></h3>
<p>可以使用 <code>new</code> 创建一个空的 <code>HashMap</code>,并使用 <code>insert</code> 增加元素。在示例 8-20 中我们记录两支队伍的分数,分别是蓝队和黄队。蓝队开始有 10 分而黄队开始有 50 分:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-20新建一个哈希 map 并插入一些键值对</span></p>
<p>注意必须首先 <code>use</code> 标准库中集合部分的 <code>HashMap</code>。在这三个常用集合中,<code>HashMap</code> 是最不常用的,所以并没有被 prelude 自动引用。标准库中对 <code>HashMap</code> 的支持也相对较少,例如,并没有内建的构建宏。</p>
<p>像 vector 一样,哈希 map 将它们的数据储存在堆上,这个 <code>HashMap</code> 的键类型是 <code>String</code> 而值类型是 <code>i32</code>。类似于 vector哈希 map 是同质的:所有的键必须是相同类型,值也必须都是相同类型。</p>
<h3 id="访问哈希-map-中的值"><a class="header" href="#访问哈希-map-中的值">访问哈希 map 中的值</a></h3>
<p>可以通过 <code>get</code> 方法并提供对应的键来从哈希 map 中获取值,如示例 8-21 所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let team_name = String::from("Blue");
let score = scores.get(&amp;team_name).copied().unwrap_or(0);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-21访问哈希 map 中储存的蓝队分数</span></p>
<p>这里,<code>score</code> 是与蓝队分数相关的值,应为 <code>10</code><code>get</code> 方法返回 <code>Option&lt;&amp;V&gt;</code>,如果某个键在哈希 map 中没有对应的值,<code>get</code> 会返回 <code>None</code>。程序中通过调用 <code>copied</code> 方法来获取一个 <code>Option&lt;i32&gt;</code> 而不是 <code>Option&lt;&amp;i32&gt;</code>,接着调用 <code>unwrap_or</code><code>scores</code> 中没有该键所对应的项时将其设置为零。</p>
<p>可以使用与 vector 类似的方式来遍历哈希 map 中的每一个键值对,也就是 <code>for</code> 循环:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
for (key, value) in &amp;scores {
println!("{key}: {value}");
}
<span class="boring">}</span></code></pre></pre>
<p>这会以任意顺序打印出每一个键值对:</p>
<pre><code class="language-text">Yellow: 50
Blue: 10
</code></pre>
<h3 id="哈希-map-和所有权"><a class="header" href="#哈希-map-和所有权">哈希 map 和所有权</a></h3>
<p>对于像 <code>i32</code> 这样的实现了 <code>Copy</code> trait 的类型,其值可以拷贝进哈希 map。对于像 <code>String</code> 这样拥有所有权的值,其值将被移动而哈希 map 会成为这些值的所有者,如示例 8-22 所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::collections::HashMap;
let field_name = String::from("Favorite color");
let field_value = String::from("Blue");
let mut map = HashMap::new();
map.insert(field_name, field_value);
// 这里 field_name 和 field_value 不再有效,
// 尝试使用它们看看会出现什么编译错误!
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-22展示一旦键值对被插入后就为哈希 map 所拥有</span></p>
<p><code>insert</code> 调用将 <code>field_name</code><code>field_value</code> 移动到哈希 map 中后,将不能使用这两个绑定。</p>
<p>如果将值的引用插入哈希 map这些值本身将不会被移动进哈希 map。但是这些引用指向的值必须至少在哈希 map 有效时也是有效的。第十章 <a href="ch10-03-lifetime-syntax.html#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E7%A1%AE%E4%BF%9D%E5%BC%95%E7%94%A8%E6%9C%89%E6%95%88">“生命周期确保引用有效”</a> 部分将会更多的讨论这个问题。</p>
<h3 id="更新哈希-map"><a class="header" href="#更新哈希-map">更新哈希 map</a></h3>
<p>尽管键值对的数量是可以增长的,每个唯一的键只能同时关联一个值(反之不一定成立:比如蓝队和黄队的 <code>scores</code> 哈希 map 中都可能存储有 10 这个值)。</p>
<p>当我们想要改变哈希 map 中的数据时,必须决定如何处理一个键已经有值了的情况。可以选择完全无视旧值并用新值代替旧值。可以选择保留旧值而忽略新值,并只在键 <strong>没有</strong> 对应值时增加新值。或者可以结合新旧两值。让我们看看这分别该如何处理!</p>
<h4 id="覆盖一个值"><a class="header" href="#覆盖一个值">覆盖一个值</a></h4>
<p>如果我们插入了一个键值对,接着用相同的键插入一个不同的值,与这个键相关联的旧值将被替换。即便示例 8-23 中的代码调用了两次 <code>insert</code>,哈希 map 也只会包含一个键值对,因为两次都是对蓝队的键插入的值:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
println!("{scores:?}");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-23替换以特定键储存的值</span></p>
<p>这会打印出 <code>{"Blue": 25}</code>。原始的值 <code>10</code> 则被覆盖了。</p>
<h4 id="只在键没有对应值时插入键值对"><a class="header" href="#只在键没有对应值时插入键值对">只在键没有对应值时插入键值对</a></h4>
<p>我们经常会检查某个特定的键是否已经存在于哈希 map 中并进行如下操作:如果哈希 map 中键已经存在则不做任何操作。如果不存在则连同值一块插入。</p>
<p>为此哈希 map 有一个特有的 API叫做 <code>entry</code>,它获取我们想要检查的键作为参数。<code>entry</code> 函数的返回值是一个枚举,<code>Entry</code>,它代表了可能存在也可能不存在的值。比如说我们想要检查黄队的键是否关联了一个值。如果没有,就插入值 50对于蓝队也是如此。使用 <code>entry</code> API 的代码看起来像示例 8-24 这样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.entry(String::from("Yellow")).or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);
println!("{scores:?}");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-24使用 <code>entry</code> 方法只在键没有对应一个值时插入</span></p>
<p><code>Entry</code><code>or_insert</code> 方法在键对应的值存在时就返回这个值的可变引用,如果不存在则将参数作为新值插入并返回新值的可变引用。这比编写自己的逻辑要简明的多,另外也与借用检查器结合得更好。</p>
<p>运行示例 8-24 的代码会打印出 <code>{"Yellow": 50, "Blue": 10}</code>。第一个 <code>entry</code> 调用会插入黄队的键和值 <code>50</code>,因为黄队并没有一个值。第二个 <code>entry</code> 调用不会改变哈希 map 因为蓝队已经有了值 <code>10</code></p>
<h4 id="根据旧值更新一个值"><a class="header" href="#根据旧值更新一个值">根据旧值更新一个值</a></h4>
<p>另一个常见的哈希 map 的应用场景是找到一个键对应的值并根据旧的值更新它。例如,示例 8-25 中的代码计数一些文本中每一个单词分别出现了多少次。我们使用哈希 map 以单词作为键并递增其值来记录我们遇到过几次这个单词。如果是第一次看到某个单词,就插入值 <code>0</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::collections::HashMap;
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{map:?}");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 8-25通过哈希 map 储存单词和计数来统计出现次数</span></p>
<p>这会打印出 <code>{"world": 2, "hello": 1, "wonderful": 1}</code>。你可能会看到相同的键值对以不同的顺序打印:回忆一下<a href="ch08-03-hash-maps.html#%E8%AE%BF%E9%97%AE%E5%93%88%E5%B8%8C-map-%E4%B8%AD%E7%9A%84%E5%80%BC">“访问哈希 map 中的值”</a>部分中遍历哈希 map 会以任意顺序进行。</p>
<p><code>split_whitespace</code> 方法返回一个由空格分隔 <code>text</code> 值子 slice 的迭代器。<code>or_insert</code> 方法返回这个键的值的一个可变引用(<code>&amp;mut V</code>)。这里我们将这个可变引用储存在 <code>count</code> 变量中,所以为了赋值必须首先使用星号(<code>*</code>)解引用 <code>count</code>。这个可变引用在 <code>for</code> 循环的结尾离开作用域,这样所有这些改变都是安全的并符合借用规则。</p>
<h3 id="哈希函数"><a class="header" href="#哈希函数">哈希函数</a></h3>
<p><code>HashMap</code> 默认使用一种叫做 SipHash 的哈希函数它可以抵御涉及哈希表hash table<sup class="footnote-reference"><a href="#siphash">1</a></sup> 的拒绝服务Denial of Service, DoS攻击。然而这并不是可用的最快的算法不过为了更高的安全性值得付出一些性能的代价。如果性能监测显示此哈希函数非常慢以致于你无法接受你可以指定一个不同的 <em>hasher</em> 来切换为其它函数。hasher 是一个实现了 <code>BuildHasher</code> trait 的类型。第十章会讨论 trait 和如何实现它们。你并不需要从头开始实现你自己的 hasher<a href="https://crates.io">crates.io</a> 有其他人分享的实现了许多常用哈希算法的 hasher 的库。</p>
<div class="footnote-definition" id="siphash"><sup class="footnote-definition-label">1</sup>
<p><a href="https://en.wikipedia.org/wiki/SipHash">https://en.wikipedia.org/wiki/SipHash</a></p>
</div>
<h2 id="总结-7"><a class="header" href="#总结-7">总结</a></h2>
<p>vector、字符串和哈希 map 会在你的程序需要储存、访问和修改数据时帮助你。这里有一些你应该能够解决的练习问题:</p>
<ul>
<li>给定一系列数字,使用 vector 并返回这个列表的中位数(排列数组后位于中间的值)和众数(出现次数最多的值;在这里哈希 map 会很有帮助)。</li>
<li>将字符串转换为 Pig Latin也就是每一个单词的第一个辅音字母被移动到单词的结尾并增加 “ay”所以 “first” 会变成 “irst-fay”。元音字母开头的单词则在结尾增加 “hay”“apple” 会变成 “apple-hay”。牢记 UTF-8 编码!</li>
<li>使用哈希 map 和 vector创建一个文本接口来允许用户向公司的部门中增加员工的名字。例如“Add Sally to Engineering” 或 “Add Amir to Sales”。接着让用户获取一个部门的所有员工的列表或者公司每个部门的所有员工按照字典序排列的列表。</li>
</ul>
<p>标准库 API 文档中描述的这些类型的方法将有助于你进行这些练习!</p>
<p>我们已经开始接触可能会有失败操作的复杂程序了,这也意味着接下来是一个了解错误处理的绝佳时机!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="错误处理"><a class="header" href="#错误处理">错误处理</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch09-00-error-handling.md">ch09-00-error-handling.md</a>
<br>
commit 199ca99926f232ee7f581a917eada4b65ff21754</p>
</blockquote>
<p>错误是软件中不可否认的事实,所以 Rust 有一些处理出错情况的特性。在许多情况下Rust 要求你承认错误的可能性,并在你的代码编译前采取一些行动。这一要求使你的程序更加健壮,因为它可以确保你在将代码部署到生产环境之前就能发现错误并进行适当的处理。</p>
<p>Rust 将错误分为两大类:<strong>可恢复的</strong><em>recoverable</em>)和 <strong>不可恢复的</strong><em>unrecoverable</em>)错误。对于一个可恢复的错误,比如文件未找到的错误,我们很可能只想向用户报告问题并重试操作。不可恢复的错误总是 bug 出现的征兆,比如试图访问一个超过数组末端的位置,因此我们要立即停止程序。</p>
<p>大多数语言并不区分这两种错误并采用类似异常这样方式统一处理它们。Rust 没有异常。相反,它有 <code>Result&lt;T, E&gt;</code> 类型,用于处理可恢复的错误,还有 <code>panic!</code> 宏,在程序遇到不可恢复的错误时停止执行。本章首先介绍 <code>panic!</code> 调用,接着会讲到如何返回 <code>Result&lt;T, E&gt;</code>。此外,我们将探讨在决定是尝试从错误中恢复还是停止执行时的注意事项。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="用-panic-处理不可恢复的错误"><a class="header" href="#用-panic-处理不可恢复的错误"><code>panic!</code> 处理不可恢复的错误</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch09-01-unrecoverable-errors-with-panic.md">ch09-01-unrecoverable-errors-with-panic.md</a>
<br>
commit 2921743516b3e2c0f45a95390e7b536e42f4af7c</p>
</blockquote>
<p>突然有一天代码出问题了而你对此束手无策。对于这种情况Rust 有 <code>panic!</code>宏。在实践中有两种方法造成 panic执行会造成代码 panic 的操作(比如访问超过数组结尾的内容)或者显式调用 <code>panic!</code> 宏。这两种情况都会使程序 panic。通常情况下这些 panic 会打印出一个错误信息,展开并清理栈数据,然后退出。通过一个环境变量,你也可以让 Rust 在 panic 发生时打印调用堆栈call stack以便于定位 panic 的原因。</p>
<blockquote>
<h3 id="对应-panic-时的栈展开或终止"><a class="header" href="#对应-panic-时的栈展开或终止">对应 panic 时的栈展开或终止</a></h3>
<p>当出现 panic 时,程序默认会开始 <strong>展开</strong><em>unwinding</em>),这意味着 Rust 会回溯栈并清理它遇到的每一个函数的数据,不过这个回溯并清理的过程有很多工作。另一种选择是直接 <strong>终止</strong><em>abort</em>),这会不清理数据就退出程序。</p>
<p>那么程序所使用的内存需要由操作系统来清理。如果你需要项目的最终二进制文件越小越好panic 时通过在 <em>Cargo.toml</em><code>[profile]</code> 部分增加 <code>panic = 'abort'</code>,可以由展开切换为终止。例如,如果你想要在 release 模式中 panic 时直接终止:</p>
<pre><code class="language-toml">[profile.release]
panic = 'abort'
</code></pre>
</blockquote>
<p>让我们在一个简单的程序中调用 <code>panic!</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust should_panic panics edition2021">fn main() {
panic!("crash and burn");
}</code></pre></pre>
<p>运行程序将会出现类似这样的输出:</p>
<pre><code class="language-console">$ cargo run
Compiling panic v0.1.0 (file:///projects/panic)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.25s
Running `target/debug/panic`
thread 'main' panicked at src/main.rs:2:5:
crash and burn
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>最后两行包含 <code>panic!</code> 调用造成的错误信息。第一行显示了 panic 提供的信息并指明了源码中 panic 出现的位置:<em>src/main.rs:2:5</em> 表明这是 <em>src/main.rs</em> 文件的第二行第五个字符。</p>
<p>在这个例子中,被指明的那一行是我们代码的一部分,而且查看这一行的话就会发现 <code>panic!</code> 宏的调用。在其他情况下,<code>panic!</code> 可能会出现在我们的代码所调用的代码中。错误信息报告的文件名和行号可能指向别人代码中的 <code>panic!</code> 宏调用,而不是我们代码中最终导致 <code>panic!</code> 的那一行。我们可以使用 <code>panic!</code> 被调用的函数的 backtrace 来寻找代码中出问题的地方。下面我们会详细介绍 backtrace 是什么。</p>
<h3 id="使用-panic-的-backtrace"><a class="header" href="#使用-panic-的-backtrace">使用 <code>panic!</code> 的 backtrace</a></h3>
<p>让我们来看看另一个因为我们代码中的 bug 引起的别的库中 <code>panic!</code> 的例子,而不是直接的宏调用。示例 9-1 有一些尝试通过索引访问 vector 中元素的例子:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust should_panic panics edition2021">fn main() {
let v = vec![1, 2, 3];
v[99];
}</code></pre></pre>
<p><span class="caption">示例 9-1尝试访问超越 vector 结尾的元素,这会造成 <code>panic!</code></span></p>
<p>这里尝试访问 vector 的第一百个元素(这里的索引是 99 因为索引从 0 开始),不过它只有三个元素。这种情况下 Rust 会 panic。<code>[]</code> 应当返回一个元素,不过如果传递了一个无效索引,就没有可供 Rust 返回的正确的元素。</p>
<p>C 语言中尝试读取数据结构之后的值是未定义行为undefined behavior。你会得到任何对应数据结构中这个元素的内存位置的值甚至是这些内存并不属于这个数据结构的情况。这被称为 <strong>缓冲区溢出</strong><em>buffer overread</em>),并可能会导致安全漏洞,比如攻击者可以像这样操作索引来读取储存在数据结构之后不被允许的数据。</p>
<p>为了保护程序远离这类漏洞如果尝试读取一个索引不存在的元素Rust 会停止执行并拒绝继续。尝试运行上面的程序会出现如下:</p>
<pre><code class="language-console">$ cargo run
Compiling panic v0.1.0 (file:///projects/panic)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s
Running `target/debug/panic`
thread 'main' panicked at src/main.rs:4:6:
index out of bounds: the len is 3 but the index is 99
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>错误指向 <code>main.rs</code> 的第 4 行,这里我们尝试访问索引 99。下面的说明note行提醒我们可以设置 <code>RUST_BACKTRACE</code> 环境变量来得到一个 backtrace。<em>backtrace</em> 是一个执行到目前位置所有被调用的函数的列表。Rust 的 backtrace 跟其他语言中的一样:阅读 backtrace 的关键是从头开始读直到发现你编写的文件。这就是问题的发源地。这一行往上是你的代码所调用的代码;往下则是调用你的代码的代码。这些行可能包含核心 Rust 代码,标准库代码或用到的 crate 代码。让我们将 <code>RUST_BACKTRACE</code> 环境变量设置为任何不是 0 的值来获取 backtrace 看看。示例 9-2 展示了与你看到类似的输出:</p>
<pre><code class="language-console">$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5
stack backtrace:
0: rust_begin_unwind
at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/std/src/panicking.rs:584:5
1: core::panicking::panic_fmt
at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/panicking.rs:142:14
2: core::panicking::panic_bounds_check
at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/panicking.rs:84:5
3: &lt;usize as core::slice::index::SliceIndex&lt;[T]&gt;&gt;::index
at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/slice/index.rs:242:10
4: core::slice::index::&lt;impl core::ops::index::Index&lt;I&gt; for [T]&gt;::index
at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/slice/index.rs:18:9
5: &lt;alloc::vec::Vec&lt;T,A&gt; as core::ops::index::Index&lt;I&gt;&gt;::index
at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/alloc/src/vec/mod.rs:2591:9
6: panic::main
at ./src/main.rs:4:5
7: core::ops::function::FnOnce::call_once
at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/ops/function.rs:248:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
</code></pre>
<p><span class="caption">示例 9-2当设置 <code>RUST_BACKTRACE</code> 环境变量时 <code>panic!</code> 调用所生成的 backtrace 信息</span></p>
<p>这里有大量的输出!你实际看到的输出可能因不同的操作系统和 Rust 版本而有所不同。为了获取带有这些信息的 backtrace必须启用 debug 标识。当不使用 <code>--release</code> 参数运行 cargo build 或 cargo run 时 debug 标识会默认启用,就像这里一样。</p>
<p>示例 9-2 的输出中backtrace 的 12 行指向了我们项目中造成问题的行:<em>src/main.rs</em> 的第 4 行。如果你不希望程序 panic第一个提到我们编写的代码行的位置是你应该开始调查的以便查明是什么值如何在这个地方引起了 panic。在示例 9-1 中,我们故意编写会 panic 的代码来演示如何使用 backtrace修复这个 panic 的方法就是不要尝试在一个只包含三个项的 vector 中请求索引是 100 的元素。当将来你的代码出现了 panic你需要搞清楚在这特定的场景下代码中执行了什么操作和什么值导致了 panic以及应当如何处理才能避免这个问题。</p>
<p>本章后面的小节 <a href="ch09-03-to-panic-or-not-to-panic.html#%E8%A6%81%E4%B8%8D%E8%A6%81-panic">“要不要 panic!”</a> 会再次回到 <code>panic!</code> 并讲解何时应该、何时不应该使用 <code>panic!</code> 来处理错误情况。接下来,我们来看看如何使用 <code>Result</code> 来从错误中恢复。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="用-result-处理可恢复的错误"><a class="header" href="#用-result-处理可恢复的错误"><code>Result</code> 处理可恢复的错误</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch09-02-recoverable-errors-with-result.md">ch09-02-recoverable-errors-with-result.md</a>
<br>
commit 699adc6f5cb76f6e9d567ff0a57d8a844ac07a88</p>
</blockquote>
<p>大部分错误并没有严重到需要程序完全停止执行。有时候,一个函数失败,仅仅就是因为一个容易理解和响应的原因。例如,如果因为打开一个并不存在的文件而失败,此时我们可能想要创建这个文件,而不是终止进程。</p>
<p>回忆一下第二章 <a href="ch02-00-guessing-game-tutorial.html#%E4%BD%BF%E7%94%A8-result-%E7%B1%BB%E5%9E%8B%E6%9D%A5%E5%A4%84%E7%90%86%E6%BD%9C%E5%9C%A8%E7%9A%84%E9%94%99%E8%AF%AF">“使用 <code>Result</code> 类型来处理潜在的错误”</a> 部分中的那个 <code>Result</code> 枚举,它定义有如下两个成员,<code>Ok</code><code>Err</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>enum Result&lt;T, E&gt; {
Ok(T),
Err(E),
}
<span class="boring">}</span></code></pre></pre>
<p><code>T</code><code>E</code> 是泛型类型参数;第十章会详细介绍泛型。现在你需要知道的就是 <code>T</code> 代表成功时返回的 <code>Ok</code> 成员中的数据的类型,而 <code>E</code> 代表失败时返回的 <code>Err</code> 成员中的错误的类型。因为 <code>Result</code> 有这些泛型类型参数,我们可以将 <code>Result</code> 类型和标准库中为其定义的函数用于很多不同的场景,这些情况中需要返回的成功值和失败值可能会各不相同。</p>
<p>让我们调用一个返回 <code>Result</code> 的函数,因为它可能会失败:如示例 9-3 所示打开一个文件:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::fs::File;
fn main() {
let greeting_file_result = File::open("hello.txt");
}</code></pre></pre>
<p><span class="caption">示例 9-3打开文件</span></p>
<p><code>File::open</code> 的返回值是 <code>Result&lt;T, E&gt;</code>。泛型参数 <code>T</code> 会被 <code>File::open</code> 的实现放入成功返回值的类型 <code>std::fs::File</code>,这是一个文件句柄。错误返回值使用的 <code>E</code> 的类型是 <code>std::io::Error</code>。这些返回类型意味着 <code>File::open</code> 调用可能成功并返回一个可以读写的文件句柄。这个函数调用也可能会失败:例如,也许文件不存在,或者可能没有权限访问这个文件。<code>File::open</code> 函数需要一个方法在告诉我们成功与否的同时返回文件句柄或者错误信息。这些信息正好是 <code>Result</code> 枚举所代表的。</p>
<p><code>File::open</code> 成功时,<code>greeting_file_result</code> 变量将会是一个包含文件句柄的 <code>Ok</code> 实例。当失败时,<code>greeting_file_result</code> 变量将会是一个包含了更多关于发生了何种错误的信息的 <code>Err</code> 实例。</p>
<p>我们需要在示例 9-3 的代码中增加根据 <code>File::open</code> 返回值进行不同处理的逻辑。示例 9-4 展示了一个使用基本工具处理 <code>Result</code> 的例子:第六章学习过的 <code>match</code> 表达式。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust should_panic edition2021">use std::fs::File;
fn main() {
let greeting_file_result = File::open("hello.txt");
let greeting_file = match greeting_file_result {
Ok(file) =&gt; file,
Err(error) =&gt; panic!("Problem opening the file: {error:?}"),
};
}</code></pre></pre>
<p><span class="caption">示例 9-4使用 <code>match</code> 表达式处理可能会返回的 <code>Result</code> 成员</span></p>
<p>注意与 <code>Option</code> 枚举一样,<code>Result</code> 枚举和其成员也被导入到了 prelude 中,所以就不需要在 <code>match</code> 分支中的 <code>Ok</code><code>Err</code> 之前指定 <code>Result::</code></p>
<p>这里我们告诉 Rust 当结果是 <code>Ok</code> 时,返回 <code>Ok</code> 成员中的 <code>file</code> 值,然后将这个文件句柄赋值给变量 <code>greeting_file</code><code>match</code> 之后,我们可以利用这个文件句柄来进行读写。</p>
<p><code>match</code> 的另一个分支处理从 <code>File::open</code> 得到 <code>Err</code> 值的情况。在这种情况下,我们选择调用 <code>panic!</code> 宏。如果当前目录没有一个叫做 <em>hello.txt</em> 的文件,当运行这段代码时会看到如下来自 <code>panic!</code> 宏的输出:</p>
<pre><code class="language-console">$ cargo run
Compiling error-handling v0.1.0 (file:///projects/error-handling)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.73s
Running `target/debug/error-handling`
thread 'main' panicked at src/main.rs:8:23:
Problem opening the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>一如既往,此输出准确地告诉了我们到底出了什么错。</p>
<h3 id="匹配不同的错误"><a class="header" href="#匹配不同的错误">匹配不同的错误</a></h3>
<p>示例 9-4 中的代码不管 <code>File::open</code> 是因为什么原因失败都会 <code>panic!</code>。我们真正希望的是对不同的错误原因采取不同的行为:如果 <code>File::open </code>因为文件不存在而失败,我们希望创建这个文件并返回新文件的句柄。如果 <code>File::open</code> 因为任何其他原因失败,例如没有打开文件的权限,我们仍然希望像示例 9-4 那样 <code>panic!</code>。让我们看看示例 9-5其中 <code>match</code> 增加了另一个分支:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use std::fs::File;
use std::io::ErrorKind;
fn main() {
let greeting_file_result = File::open("hello.txt");
let greeting_file = match greeting_file_result {
Ok(file) =&gt; file,
Err(error) =&gt; match error.kind() {
ErrorKind::NotFound =&gt; match File::create("hello.txt") {
Ok(fc) =&gt; fc,
Err(e) =&gt; panic!("Problem creating the file: {e:?}"),
},
other_error =&gt; {
panic!("Problem opening the file: {other_error:?}");
}
},
};
}</code></pre>
<p><span class="caption">示例 9-5使用不同的方式处理不同类型的错误</span></p>
<p><code>File::open</code> 返回的 <code>Err</code> 成员中的值类型 <code>io::Error</code>,它是一个标准库中提供的结构体。这个结构体有一个返回 <code>io::ErrorKind</code> 值的 <code>kind</code> 方法可供调用。<code>io::ErrorKind</code> 是一个标准库提供的枚举,它的成员对应 <code>io</code> 操作可能导致的不同错误类型。我们感兴趣的成员是 <code>ErrorKind::NotFound</code>,它代表尝试打开的文件并不存在。这样,<code>match</code> 就匹配完 <code>greeting_file_result</code> 了,不过对于 <code>error.kind()</code> 还有一个内层 <code>match</code></p>
<p>我们希望在内层 <code>match</code> 中检查的条件是 <code>error.kind()</code> 的返回值是否为 <code>ErrorKind</code><code>NotFound</code> 成员。如果是,则尝试通过 <code>File::create</code> 创建文件。然而因为 <code>File::create</code> 也可能会失败,还需要增加一个内层 <code>match</code> 语句。当文件不能被创建,会打印出一个不同的错误信息。外层 <code>match</code> 的最后一个分支保持不变,这样对任何除了文件不存在的错误会使程序 panic。</p>
<blockquote>
<p>不同于使用 <code>match</code><code>Result&lt;T, E&gt;</code></p>
<p>这里有好多 <code>match</code><code>match</code> 确实很强大不过也非常的原始。第十三章我们会介绍闭包closure它会和定义在 <code>Result&lt;T, E&gt;</code> 中的很多方法一起使用。在处理代码中的 <code>Result&lt;T, E&gt;</code> 值时,相比于使用 <code>match</code> ,使用这些方法会更加简洁。</p>
<p>例如,这是另一个编写与示例 9-5 逻辑相同但是使用闭包和 <code>unwrap_or_else</code> 方法的例子:</p>
<pre><code class="language-rust ignore">use std::fs::File;
use std::io::ErrorKind;
fn main() {
let greeting_file = File::open("hello.txt").unwrap_or_else(|error| {
if error.kind() == ErrorKind::NotFound {
File::create("hello.txt").unwrap_or_else(|error| {
panic!("Problem creating the file: {:?}", error);
})
} else {
panic!("Problem opening the file: {:?}", error);
}
});
}</code></pre>
<p>虽然这段代码有着如示例 9-5 一样的行为,但并没有包含任何 <code>match</code> 表达式且更容易阅读。在阅读完第十三章后再回到这个例子,并查看标准库文档 <code>unwrap_or_else</code> 方法都做了什么操作。在处理错误时,还有很多这类方法可以消除大量嵌套的 <code>match</code> 表达式。</p>
</blockquote>
<h3 id="失败时-panic-的简写unwrap-和-expect"><a class="header" href="#失败时-panic-的简写unwrap-和-expect">失败时 panic 的简写:<code>unwrap</code><code>expect</code></a></h3>
<p><code>match</code> 能够胜任它的工作,不过它可能有点冗长并且不总是能很好的表明其意图。<code>Result&lt;T, E&gt;</code> 类型定义了很多辅助方法来处理各种情况。其中之一叫做 <code>unwrap</code>,它的实现就类似于示例 9-4 中的 <code>match</code> 语句。如果 <code>Result</code> 值是成员 <code>Ok</code><code>unwrap</code> 会返回 <code>Ok</code> 中的值。如果 <code>Result</code> 是成员 <code>Err</code><code>unwrap</code> 会为我们调用 <code>panic!</code>。这里是一个实践 <code>unwrap</code> 的例子:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust should_panic edition2021">use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt").unwrap();
}</code></pre></pre>
<p>如果调用这段代码时不存在 <em>hello.txt</em> 文件,我们将会看到一个 <code>unwrap</code> 调用 <code>panic!</code> 时提供的错误信息:</p>
<pre><code class="language-text">thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os {
code: 2, kind: NotFound, message: "No such file or directory" }',
src/main.rs:4:49
</code></pre>
<p>还有另一个类似于 <code>unwrap</code> 的方法它还允许我们选择 <code>panic!</code> 的错误信息:<code>expect</code>。使用 <code>expect</code> 而不是 <code>unwrap</code> 并提供一个好的错误信息可以表明你的意图并更易于追踪 panic 的根源。<code>expect</code> 的语法看起来像这样:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust should_panic edition2021">use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt")
.expect("hello.txt should be included in this project");
}</code></pre></pre>
<p><code>expect</code><code>unwrap</code> 的使用方式一样:返回文件句柄或调用 <code>panic!</code> 宏。<code>expect</code> 在调用 <code>panic!</code> 时使用的错误信息将是我们传递给 <code>expect</code> 的参数,而不像 <code>unwrap</code> 那样使用默认的 <code>panic!</code> 信息。它看起来像这样:</p>
<pre><code class="language-text">thread 'main' panicked at 'hello.txt should be included in this project: Error
{ repr: Os { code: 2, message: "No such file or directory" } }',
src/libcore/result.rs:906:4
</code></pre>
<p>在生产级别的代码中,大部分 Rustaceans 选择 <code>expect</code> 而不是 <code>unwrap</code> 并提供更多关于为何操作期望是一直成功的上下文。如此如果该假设真的被证明是错的,你也有更多的信息来用于调试。</p>
<h3 id="传播错误"><a class="header" href="#传播错误">传播错误</a></h3>
<p>当编写一个其实先会调用一些可能会失败的操作的函数时,除了在这个函数中处理错误外,还可以选择让调用者知道这个错误并决定该如何处理。这被称为 <strong>传播</strong><em>propagating</em>)错误,这样能更好的控制代码调用,因为比起你代码所拥有的上下文,调用者可能拥有更多信息或逻辑来决定应该如何处理错误。</p>
<p>例如,示例 9-6 展示了一个从文件中读取用户名的函数。如果文件不存在或不能读取,这个函数会将这些错误返回给调用它的代码:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::fs::File;
use std::io::{self, Read};
fn read_username_from_file() -&gt; Result&lt;String, io::Error&gt; {
let username_file_result = File::open("hello.txt");
let mut username_file = match username_file_result {
Ok(file) =&gt; file,
Err(e) =&gt; return Err(e),
};
let mut username = String::new();
match username_file.read_to_string(&amp;mut username) {
Ok(_) =&gt; Ok(username),
Err(e) =&gt; Err(e),
}
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 9-6一个函数使用 <code>match</code> 将错误返回给代码调用者</span></p>
<p>这个函数可以编写成更加简短的形式,不过我们以大量手动处理开始以便探索错误处理;在最后我们会展示更短的形式。让我们看看函数的返回值:<code>Result&lt;String, io::Error&gt;</code>。这意味着函数返回一个 <code>Result&lt;T, E&gt;</code> 类型的值,其中泛型参数 <code>T</code> 的具体类型是 <code>String</code>,而 <code>E</code> 的具体类型是 <code>io::Error</code></p>
<p>如果这个函数没有出任何错误成功返回,函数的调用者会收到一个包含 <code>String</code><code>Ok</code> 值 —— 函数从文件中读取到的用户名。如果函数遇到任何错误,函数的调用者会收到一个 <code>Err</code> 值,它储存了一个包含更多这个问题相关信息的 <code>io::Error</code> 实例。这里选择 <code>io::Error</code> 作为函数的返回值是因为它正好是函数体中那两个可能会失败的操作的错误返回值:<code>File::open</code> 函数和 <code>read_to_string</code> 方法。</p>
<p>函数体以调用 <code>File::open</code> 函数开始。接着使用 <code>match</code> 处理返回值 <code>Result</code>,类似示例 9-4如果 <code>File::open</code> 成功了,模式变量 <code>file</code> 中的文件句柄就变成了可变变量 <code>username_file</code> 中的值,接着函数继续执行。在 <code>Err</code> 的情况下,我们没有调用 <code>panic!</code>,而是使用 <code>return</code> 关键字提前结束整个函数,并将来自 <code>File::open</code> 的错误值(现在在模式变量 <code>e</code> 中)作为函数的错误值传回给调用者。</p>
<p>所以,如果在 <code>username_file</code> 中有一个文件句柄,该函数随后会在变量 <code>username</code> 中创建一个新的 <code>String</code> 并调用文件句柄 <code>username_file</code> 上的 <code>read_to_string</code> 方法,以将文件的内容读入 <code>username</code><code>read_to_string</code> 方法也返回一个 <code>Result</code>,因为它可能会失败,哪怕是 <code>File::open</code> 已经成功了。因此,我们需要另一个 <code>match</code> 来处理这个 <code>Result</code>:如果 <code>read_to_string</code> 执行成功,那么这个函数也就成功了,我们将从文件中读取的用户名返回,此时用户名位于被封装进 <code>Ok</code><code>username</code> 中。如果 <code>read_to_string</code> 执行失败,则像之前处理 <code>File::open</code> 的返回值的 <code>match</code> 那样返回错误值。然而,我们无需显式调用 <code>return</code> 语句,因为这是函数的最后一个表达式。</p>
<p>调用这个函数的代码最终会得到一个包含用户名的 <code>Ok</code> 值,或者一个包含 <code>io::Error</code><code>Err</code> 值。我们无从得知调用者会如何处理这些值。例如,如果他们得到了一个 <code>Err</code> 值,他们可能会选择 <code>panic!</code> 并使程序崩溃、使用一个默认的用户名或者从文件之外的地方寻找用户名。我们没有足够的信息知晓调用者具体会如何尝试,所以将所有的成功或失败信息向上传播,让他们选择合适的处理方法。</p>
<p>这种传播错误的模式在 Rust 是如此的常见,以至于 Rust 提供了 <code>?</code> 问号运算符来使其更易于处理。</p>
<h3 id="传播错误的简写-运算符"><a class="header" href="#传播错误的简写-运算符">传播错误的简写:<code>?</code> 运算符</a></h3>
<p>示例 9-7 展示了一个 <code>read_username_from_file</code> 的实现,它实现了与示例 9-6 中的代码相同的功能,不过这个实现使用了 <code>?</code> 运算符:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::fs::File;
use std::io::{self, Read};
fn read_username_from_file() -&gt; Result&lt;String, io::Error&gt; {
let mut username_file = File::open("hello.txt")?;
let mut username = String::new();
username_file.read_to_string(&amp;mut username)?;
Ok(username)
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 9-7一个使用 <code>?</code> 运算符向调用者返回错误的函数</span></p>
<p><code>Result</code> 值之后的 <code>?</code> 被定义为与示例 9-6 中定义的处理 <code>Result</code> 值的 <code>match</code> 表达式有着完全相同的工作方式。如果 <code>Result</code> 的值是 <code>Ok</code>,这个表达式将会返回 <code>Ok</code> 中的值而程序将继续执行。如果值是 <code>Err</code><code>Err</code> 将作为整个函数的返回值,就好像使用了 <code>return</code> 关键字一样,这样错误值就被传播给了调用者。</p>
<p>示例 9-6 中的 <code>match</code> 表达式与 <code>?</code> 运算符所做的有一点不同:<code>?</code> 运算符所使用的错误值被传递给了 <code>from</code> 函数,它定义于标准库的 <code>From</code> trait 中,其用来将错误从一种类型转换为另一种类型。当 <code>?</code> 运算符调用 <code>from</code> 函数时,收到的错误类型被转换为由当前函数返回类型所指定的错误类型。这在当函数返回单个错误类型来代表所有可能失败的方式时很有用,即使其可能会因很多种原因失败。</p>
<p>例如,我们可以将示例 9-7 中的 <code>read_username_from_file</code> 函数修改为返回一个自定义的 <code>OurError</code> 错误类型。如果我们也定义了 <code>impl From&lt;io::Error&gt; for OurError</code> 来从 <code>io::Error</code> 构造一个 <code>OurError</code> 实例,那么 <code>read_username_from_file</code> 函数体中的 <code>?</code> 运算符调用会调用 <code>from</code> 并转换错误而无需在函数中增加任何额外的代码。</p>
<p>在示例 9-7 的上下文中,<code>File::open</code> 调用结尾的 <code>?</code> 会将 <code>Ok</code> 中的值返回给变量 <code>username_file</code>。如果发生了错误,<code>?</code> 运算符会使整个函数提前返回并将任何 <code>Err</code> 值返回给调用代码。同理也适用于 <code>read_to_string</code> 调用结尾的 <code>?</code></p>
<p><code>?</code> 运算符消除了大量样板代码并使得函数的实现更简单。我们甚至可以在 <code>?</code> 之后直接使用链式方法调用来进一步缩短代码,如示例 9-8 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::fs::File;
use std::io::{self, Read};
fn read_username_from_file() -&gt; Result&lt;String, io::Error&gt; {
let mut username = String::new();
File::open("hello.txt")?.read_to_string(&amp;mut username)?;
Ok(username)
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 9-8问号运算符之后的链式方法调用</span></p>
<p><code>username</code> 中创建新的 <code>String</code> 被放到了函数开头;这一部分没有变化。我们对 <code>File::open("hello.txt")?</code> 的结果直接链式调用了 <code>read_to_string</code>,而不再创建变量 <code>username_file</code>。仍然需要 <code>read_to_string</code> 调用结尾的 <code>?</code>,而且当 <code>File::open</code><code>read_to_string</code> 都成功没有失败时返回包含用户名 <code>username</code><code>Ok</code> 值。其功能再一次与示例 9-6 和示例 9-7 保持一致不过这是一个与众不同且更符合工程学ergonomic的写法。</p>
<p>示例 9-9 展示了一个使用 <code>fs::read_to_string</code> 的更为简短的写法:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::fs;
use std::io;
fn read_username_from_file() -&gt; Result&lt;String, io::Error&gt; {
fs::read_to_string("hello.txt")
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 9-9: 使用 <code>fs::read_to_string</code> 而不是打开后读取文件</span></p>
<p>将文件读取到一个字符串是相当常见的操作,所以 Rust 提供了名为 <code>fs::read_to_string</code> 的函数,它会打开文件、新建一个 <code>String</code>、读取文件的内容,并将内容放入 <code>String</code>,接着返回它。当然,这样做就没有展示所有这些错误处理的机会了,所以我们最初就选择了艰苦的道路。</p>
<h3 id="哪里可以使用--运算符"><a class="header" href="#哪里可以使用--运算符">哪里可以使用 <code>?</code> 运算符</a></h3>
<p><code>?</code> 运算符只能被用于返回值与 <code>?</code> 作用的值相兼容的函数。因为 <code>?</code> 运算符被定义为从函数中提早返回一个值,这与示例 9-6 中的 <code>match</code> 表达式有着完全相同的工作方式。示例 9-6 中 <code>match</code> 作用于一个 <code>Result</code> 值,提早返回的分支返回了一个 <code>Err(e)</code> 值。函数的返回值必须是 <code>Result</code> 才能与这个 <code>return</code> 相兼容。</p>
<p>在示例 9-10 中,让我们看看在返回值不兼容的 <code>main</code> 函数中使用 <code>?</code> 运算符会得到什么错误:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt")?;
}</code></pre>
<p><span class="caption">示例 9-10: 尝试在返回 <code>()</code><code>main</code> 函数中使用 <code>?</code> 的代码不能编译</span></p>
<p>这段代码打开一个文件,这可能会失败。<code>?</code> 运算符作用于 <code>File::open</code> 返回的 <code>Result</code> 值,不过 <code>main</code> 函数的返回类型是 <code>()</code> 而不是 <code>Result</code>。当编译这些代码,会得到如下错误信息:</p>
<pre><code class="language-console">$ cargo run
Compiling error-handling v0.1.0 (file:///projects/error-handling)
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
--&gt; src/main.rs:4:48
|
3 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
4 | let greeting_file = File::open("hello.txt")?;
| ^ cannot use the `?` operator in a function that returns `()`
|
= help: the trait `FromResidual&lt;Result&lt;Infallible, std::io::Error&gt;&gt;` is not implemented for `()`
help: consider adding return type
|
3 ~ fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {
4 | let greeting_file = File::open("hello.txt")?;
5 +
6 + Ok(())
7 + }
|
For more information about this error, try `rustc --explain E0277`.
error: could not compile `error-handling` (bin "error-handling") due to 1 previous error
</code></pre>
<p>这个错误指出只能在返回 <code>Result</code> 或者其它实现了 <code>FromResidual</code> 的类型的函数中使用 <code>?</code> 运算符。</p>
<p>为了修复这个错误,有两个选择。一个是,如果没有限制的话将函数的返回值改为 <code>Result&lt;T, E&gt;</code>。另一个是使用 <code>match</code><code>Result&lt;T, E&gt;</code> 的方法中合适的一个来处理 <code>Result&lt;T, E&gt;</code></p>
<p>错误信息也提到 <code>?</code> 也可用于 <code>Option&lt;T&gt;</code> 值。如同对 <code>Result</code> 使用 <code>?</code> 一样,只能在返回 <code>Option</code> 的函数中对 <code>Option</code> 使用 <code>?</code>。在 <code>Option&lt;T&gt;</code> 上调用 <code>?</code> 运算符的行为与 <code>Result&lt;T, E&gt;</code> 类似:如果值是 <code>None</code>,此时 <code>None</code> 会从函数中提前返回。如果值是 <code>Some</code><code>Some</code> 中的值作为表达式的返回值同时函数继续。示例 9-11 中有一个从给定文本中返回第一行最后一个字符的函数的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn last_char_of_first_line(text: &amp;str) -&gt; Option&lt;char&gt; {
text.lines().next()?.chars().last()
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> assert_eq!(
</span><span class="boring"> last_char_of_first_line("Hello, world\nHow are you today?"),
</span><span class="boring"> Some('d')
</span><span class="boring"> );
</span><span class="boring">
</span><span class="boring"> assert_eq!(last_char_of_first_line(""), None);
</span><span class="boring"> assert_eq!(last_char_of_first_line("\nhi"), None);
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 9-11: 在 <code>Option&lt;T&gt;</code> 值上使用 <code>?</code> 运算符</span></p>
<p>这个函数返回 <code>Option&lt;char&gt;</code> 因为它可能会在这个位置找到一个字符,也可能没有字符。这段代码获取 <code>text</code> 字符串 slice 作为参数并调用其 <code>lines</code> 方法,这会返回一个字符串中每一行的迭代器。因为函数希望检查第一行,所以调用了迭代器 <code>next</code> 来获取迭代器中第一个值。如果 <code>text</code> 是空字符串,<code>next</code> 调用会返回 <code>None</code>,此时我们可以使用 <code>?</code> 来停止并从 <code>last_char_of_first_line</code> 返回 <code>None</code>。如果 <code>text</code> 不是空字符串,<code>next</code> 会返回一个包含 <code>text</code> 中第一行的字符串 slice 的 <code>Some</code> 值。</p>
<p><code>?</code> 会提取这个字符串 slice然后可以在字符串 slice 上调用 <code>chars</code> 来获取字符的迭代器。我们感兴趣的是第一行的最后一个字符,所以可以调用 <code>last</code> 来返回迭代器的最后一项。这是一个 <code>Option</code>,因为有可能第一行是一个空字符串,例如 <code>text</code> 以一个空行开头而后面的行有文本,像是 <code>"\nhi"</code>。不过,如果第一行有最后一个字符,它会返回在一个 <code>Some</code> 成员中。<code>?</code> 运算符作用于其中给了我们一个简洁的表达这种逻辑的方式。如果我们不能在 <code>Option</code> 上使用 <code>?</code> 运算符,则不得不使用更多的方法调用或者 <code>match</code> 表达式来实现这些逻辑。</p>
<p>注意你可以在返回 <code>Result</code> 的函数中对 <code>Result</code> 使用 <code>?</code> 运算符,可以在返回 <code>Option</code> 的函数中对 <code>Option</code> 使用 <code>?</code> 运算符,但是不可以混合搭配。<code>?</code> 运算符不会自动将 <code>Result</code> 转化为 <code>Option</code>,反之亦然;在这些情况下,可以使用类似 <code>Result</code><code>ok</code> 方法或者 <code>Option</code><code>ok_or</code> 方法来显式转换。</p>
<p>目前为止,我们所使用的所有 <code>main</code> 函数都返回 <code>()</code><code>main</code> 函数是特殊的因为它是可执行程序的入口点和退出点,为了使程序能正常工作,其可以返回的类型是有限制的。</p>
<p>幸运的是 <code>main</code> 函数也可以返回 <code>Result&lt;(), E&gt;</code>,示例 9-12 中的代码来自示例 9-10 不过修改了 <code>main</code> 的返回值为 <code>Result&lt;(), Box&lt;dyn Error&gt;&gt;</code> 并在结尾增加了一个 <code>Ok(())</code> 作为返回值。这段代码可以编译:</p>
<pre><code class="language-rust ignore">use std::error::Error;
use std::fs::File;
fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
let greeting_file = File::open("hello.txt")?;
Ok(())
}</code></pre>
<p><span class="caption">示例 9-12: 修改 <code>main</code> 返回 <code>Result&lt;(), E&gt;</code> 允许对 <code>Result</code> 值使用 <code>?</code> 运算符</span></p>
<p><code>Box&lt;dyn Error&gt;</code> 类型是一个 <strong>trait 对象</strong><em>trait object</em>)第十八章 <a href="ch18-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> 部分会做介绍。目前可以将 <code>Box&lt;dyn Error&gt;</code> 理解为 “任何类型的错误”。在返回 <code>Box&lt;dyn Error&gt;</code> 错误类型 <code>main</code> 函数中对 <code>Result</code> 使用 <code>?</code> 是允许的,因为它允许任何 <code>Err</code> 值提前返回。即便 <code>main</code> 函数体从来只会返回 <code>std::io::Error</code> 错误类型,通过指定 <code>Box&lt;dyn Error&gt;</code>,这个签名也仍是正确的,甚至当 <code>main</code> 函数体中增加更多返回其他错误类型的代码时也是如此。</p>
<p><code>main</code> 函数返回 <code>Result&lt;(), E&gt;</code>,如果 <code>main</code> 返回 <code>Ok(())</code> 可执行程序会以 <code>0</code> 值退出,而如果 <code>main</code> 返回 <code>Err</code> 值则会以非零值退出;成功退出的程序会返回整数 <code>0</code>,运行错误的程序会返回非 <code>0</code> 的整数。Rust 也会从二进制程序中返回与这个惯例相兼容的整数。</p>
<p><code>main</code> 函数也可以返回任何实现了 <a href="https://doc.rust-lang.org/std/process/trait.Termination.html"><code>std::process::Termination</code> trait</a> 的类型,它包含了一个返回 <code>ExitCode</code><code>report</code> 函数。请查阅标准库文档了解更多为自定义类型实现 <code>Termination</code> trait 的细节。</p>
<p>现在我们讨论过了调用 <code>panic!</code> 或返回 <code>Result</code> 的细节,是时候回到它们各自适合哪些场景的话题了。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="要不要-panic"><a class="header" href="#要不要-panic">要不要 <code>panic!</code></a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch09-03-to-panic-or-not-to-panic.md">ch09-03-to-panic-or-not-to-panic.md</a>
<br>
commit dd8f47a74b67178cea8c832e3b4eaf3bb515bd72</p>
</blockquote>
<p>那么,该如何决定何时应该 <code>panic!</code> 以及何时应该返回 <code>Result</code> 呢?如果代码 panic就没有恢复的可能。你可以选择对任何错误场景都调用 <code>panic!</code>,不管是否有可能恢复,不过这样就是你代替调用者决定了这是不可恢复的。选择返回 <code>Result</code> 值的话,就将选择权交给了调用者,而不是代替他们做出决定。调用者可能会选择以符合他们场景的方式尝试恢复,或者也可能干脆就认为 <code>Err</code> 是不可恢复的,所以他们也可能会调用 <code>panic!</code> 并将可恢复的错误变成了不可恢复的错误。因此返回 <code>Result</code> 是定义可能会失败的函数的一个好的默认选择。</p>
<p>在一些类似示例、原型代码prototype code和测试中panic 比返回 <code>Result</code> 更为合适,下文中会讨论合适的原因,紧接着讨论另外一种特殊情况,即有些场景编译器无法认识这个分支代码是不可能走到的,但是程序员可以判断出来的,这种场景也可以用 panic!。另外章节最后会总结一些在库代码中如何决定是否要 panic 的通用指导原则。</p>
<h3 id="示例代码原型和测试都非常适合-panic"><a class="header" href="#示例代码原型和测试都非常适合-panic">示例、代码原型和测试都非常适合 panic</a></h3>
<p>当你编写一个示例来展示一些概念时,在拥有健壮的错误处理代码的同时也会使得例子不那么明确。例如,调用一个类似 <code>unwrap</code> 这样可能 <code>panic!</code> 的方法可以被理解为一个你实际希望程序处理错误方式的占位符,它根据其余代码运行方式可能会各不相同。</p>
<p>类似地,在我们准备好决定如何处理错误之前,<code>unwrap</code><code>expect</code>方法在原型设计时非常方便。当我们准备好让程序更加健壮时,它们会在代码中留下清晰的标记。</p>
<p>如果方法调用在测试中失败了,我们希望这个测试都失败,即便这个方法并不是需要测试的功能。因为 <code>panic!</code> 会将测试标记为失败,此时调用 <code>unwrap</code><code>expect</code> 是恰当的。</p>
<h3 id="当我们比编译器知道更多的情况"><a class="header" href="#当我们比编译器知道更多的情况">当我们比编译器知道更多的情况</a></h3>
<p>当你有一些其他的逻辑来确保 <code>Result</code> 会是 <code>Ok</code> 值时,调用 <code>unwrap</code> 或者 <code>expect</code> 也是合适的,虽然编译器无法理解这种逻辑。你仍然需要处理一个 <code>Result</code> 值:即使在你的特定情况下逻辑上是不可能的,你所调用的任何操作仍然有可能失败。如果通过人工检查代码来确保永远也不会出现 <code>Err</code> 值,那么调用 <code>unwrap</code> 也是完全可以接受的,这里是一个例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::net::IpAddr;
let home: IpAddr = "127.0.0.1"
.parse()
.expect("Hardcoded IP address should be valid");
<span class="boring">}</span></code></pre></pre>
<p>我们通过解析一个硬编码的字符来创建一个 <code>IpAddr</code> 实例。可以看出 <code>127.0.0.1</code> 是一个有效的 IP 地址,所以这里使用 <code>expect</code> 是可以接受的。然而,拥有一个硬编码的有效的字符串也不能改变 <code>parse</code> 方法的返回值类型:它仍然是一个 <code>Result</code> 值,而编译器仍然会要求我们处理这个 <code>Result</code>,好像还是有可能出现 <code>Err</code> 成员那样。这是因为编译器还没有智能到可以识别出这个字符串总是一个有效的 IP 地址。如果 IP 地址字符串来源于用户而不是硬编码进程序中的话,那么就 <strong>确实</strong> 有失败的可能性,这时就绝对需要我们以一种更健壮的方式处理 <code>Result</code> 了。提及这个 IP 地址是硬编码的假设会促使我们将来把 <code>expect</code> 替换为更好的错误处理,我们应该从其它代码获取 IP 地址。</p>
<h3 id="错误处理指导原则"><a class="header" href="#错误处理指导原则">错误处理指导原则</a></h3>
<p>在当有可能会导致有害状态的情况下建议使用 <code>panic!</code> —— 在这里,有害状态是指当一些假设、保证、协议或不可变性被打破的状态,例如无效的值、自相矛盾的值或者被传递了不存在的值 —— 外加如下几种情况:</p>
<ul>
<li>有害状态是非预期的行为,与偶尔会发生的行为相对,比如用户输入了错误格式的数据。</li>
<li>在此之后代码的运行依赖于不处于这种有害状态,而不是在每一步都检查是否有问题。</li>
<li>没有可行的手段来将有害状态信息编码进所使用的类型中的情况。我们会在第十八章 <a href="ch18-03-oo-design-patterns.html#%E5%B0%86%E7%8A%B6%E6%80%81%E5%92%8C%E8%A1%8C%E4%B8%BA%E7%BC%96%E7%A0%81%E4%B8%BA%E7%B1%BB%E5%9E%8B">“将状态和行为编码为类型”</a> 部分通过一个例子来说明我们的意思。</li>
</ul>
<p>如果别人调用你的代码并传递了一个没有意义的值,尽最大可能返回一个错误,如此库的用户就可以决定在这种情况下该如何处理。然而在继续执行代码是不安全或有害的情况下,最好的选择可能是调用 <code>panic!</code> 并警告库的用户他们的代码中有 bug这样他们就会在开发时进行修复。类似的如果你正在调用不受你控制的外部代码并且它返回了一个你无法修复的无效状态那么 <code>panic!</code> 往往是合适的。</p>
<p>然而当错误预期会出现时,返回 <code>Result</code> 仍要比调用 <code>panic!</code> 更为合适。这样的例子包括解析器接收到格式错误的数据,或者 HTTP 请求返回了一个表明触发了限流的状态。在这些例子中,应该通过返回 <code>Result</code> 来表明失败预期是可能的,这样将有害状态向上传播,调用者就可以决定该如何处理这个问题。使用 <code>panic!</code> 来处理这些情况就不是最好的选择。</p>
<p>当你的代码在进行一个使用无效值进行调用时可能将用户置于风险中的操作时,代码应该首先验证值是有效的,并在其无效时 <code>panic!</code>。这主要是出于安全的原因:尝试操作无效数据会暴露代码漏洞,这就是标准库在尝试越界访问数组时会 <code>panic!</code> 的主要原因:尝试访问不属于当前数据结构的内存是一个常见的安全隐患。函数通常都遵循 <strong>契约</strong><em>contracts</em>):它们的行为只有在输入满足特定条件时才能得到保证。当违反契约时 panic 是有道理的,因为这通常代表调用方的 bug而且这也不是那种你希望所调用的代码必须处理的错误。事实上所调用的代码也没有合理的方式来恢复而是需要调用方的 <strong>程序员</strong> 修复其代码。函数的契约,尤其是当违反它会造成 panic 的契约,应该在函数的 API 文档中得到解释。</p>
<p>虽然在所有函数中都拥有许多错误检查是冗长而烦人的。幸运的是,可以利用 Rust 的类型系统(以及编译器的类型检查)为你进行很多检查。如果函数有一个特定类型的参数,可以在知晓编译器已经确保其拥有一个有效值的前提下进行你的代码逻辑。例如,如果你使用了一个并不是 <code>Option</code> 的类型,则程序期望它是 <strong>有值</strong> 的并且不是 <strong>空值</strong>。你的代码无需处理 <code>Some</code><code>None</code> 这两种情况,它只会有一种情况就是绝对会有一个值。尝试向函数传递空值的代码甚至根本不能编译,所以你的函数在运行时没有必要判空。另外一个例子是使用像 <code>u32</code> 这样的无符号整型,也会确保它永远不为负。</p>
<h3 id="创建自定义类型进行有效性验证"><a class="header" href="#创建自定义类型进行有效性验证">创建自定义类型进行有效性验证</a></h3>
<p>让我们使用 Rust 类型系统的思想来进一步确保值的有效性,并尝试创建一个自定义类型以进行验证。回忆一下第二章的猜猜看游戏,我们的代码要求用户猜测一个 1 到 100 之间的数字在将其与秘密数字做比较之前我们从未验证用户的猜测是位于这两个数字之间的我们只验证它是否为正。在这种情况下其影响并不是很严重“Too high” 或 “Too low” 的输出仍然是正确的。但是这是一个很好的引导用户得出有效猜测的辅助,例如当用户猜测一个超出范围的数字或者输入字母时采取不同的行为。</p>
<p>一种实现方式是将猜测解析成 <code>i32</code> 而不仅仅是 <code>u32</code>,来默许输入负数,接着检查数字是否在范围内:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use rand::Rng;
</span><span class="boring">use std::cmp::Ordering;
</span><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span> loop {
// --snip--
<span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span> let guess: i32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
if guess &lt; 1 || guess &gt; 100 {
println!("The secret number will be between 1 and 100.");
continue;
}
match guess.cmp(&amp;secret_number) {
// --snip--
<span class="boring"> Ordering::Less =&gt; println!("Too small!"),
</span><span class="boring"> Ordering::Greater =&gt; println!("Too big!"),
</span><span class="boring"> Ordering::Equal =&gt; {
</span><span class="boring"> println!("You win!");
</span><span class="boring"> break;
</span><span class="boring"> }
</span><span class="boring"> }
</span> }
<span class="boring">}</span></code></pre>
<p><code>if</code> 表达式检查了值是否超出范围,告诉用户出了什么问题,并调用 <code>continue</code> 开始下一次循环,请求另一个猜测。<code>if</code> 表达式之后,就可以在知道 <code>guess</code> 在 1 到 100 之间的情况下与秘密数字作比较了。</p>
<p>然而,这并不是一个理想的解决方案:如果让程序仅仅处理 1 到 100 之间的值是一个绝对需要满足的要求,而且程序中的很多函数都有这样的要求,在每个函数中都有这样的检查将是非常冗余的(并可能潜在的影响性能)。</p>
<p>相反我们可以创建一个新类型来将验证放入创建其实例的函数中,而不是到处重复这些检查。这样就可以安全地在函数签名中使用新类型并相信它们接收到的值。示例 9-13 中展示了一个定义 <code>Guess</code> 类型的方法,只有在 <code>new</code> 函数接收到 1 到 100 之间的值时才会创建 <code>Guess</code> 的实例:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -&gt; Guess {
if value &lt; 1 || value &gt; 100 {
panic!("Guess value must be between 1 and 100, got {value}.");
}
Guess { value }
}
pub fn value(&amp;self) -&gt; i32 {
self.value
}
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 9-13一个 <code>Guess</code> 类型,它只在值位于 1 和 100 之间时才继续</span></p>
<p>首先,我们定义了一个包含 <code>i32</code> 类型字段 <code>value</code> 的结构体 <code>Guess</code>。这里是储存猜测值的地方。</p>
<p>接着在 <code>Guess</code> 上实现了一个叫做 <code>new</code> 的关联函数来创建 <code>Guess</code> 的实例。<code>new</code> 定义为接收一个 <code>i32</code> 类型的参数 <code>value</code> 并返回一个 <code>Guess</code><code>new</code> 函数中代码的测试确保了其值是在 1 到 100 之间的。如果 <code>value</code> 没有通过测试则调用 <code>panic!</code>,这会警告调用这个函数的程序员有一个需要修改的 bug因为创建一个 <code>value</code> 超出范围的 <code>Guess</code> 将会违反 <code>Guess::new</code> 所遵循的契约。<code>Guess::new</code> 会出现 panic 的条件应该在其公有 API 文档中被提及;第十四章会涉及到在 API 文档中表明 <code>panic!</code> 可能性的相关规则。如果 <code>value</code> 通过了测试,我们新建一个 <code>Guess</code>,其字段 <code>value</code> 将被设置为参数 <code>value</code> 的值,接着返回这个 <code>Guess</code></p>
<p>接着,我们实现了一个借用了 <code>self</code> 的方法 <code>value</code>,它没有任何其他参数并返回一个 <code>i32</code>。这类方法有时被称为 <em>getter</em>,因为它的目的就是返回对应字段的数据。这样的公有方法是必要的,因为 <code>Guess</code> 结构体的 <code>value</code> 字段是私有的。私有的字段 <code>value</code> 是很重要的,这样使用 <code>Guess</code> 结构体的代码将不允许直接设置 <code>value</code> 的值:调用者 <strong>必须</strong> 使用 <code>Guess::new</code> 方法来创建一个 <code>Guess</code> 的实例,这就确保了不会存在一个 <code>value</code> 没有通过 <code>Guess::new</code> 函数的条件检查的 <code>Guess</code></p>
<p>于是一个接收或返回1 到 100 之间数字的函数就可以声明为接收(或返回) <code>Guess</code>的实例,而不是 <code>i32</code>,同时其函数体中也无需进行任何额外的检查。</p>
<h2 id="总结-8"><a class="header" href="#总结-8">总结</a></h2>
<p>Rust 的错误处理功能被设计为帮助你编写更加健壮的代码。<code>panic!</code> 宏代表一个程序无法处理的状态并停止执行而不是使用无效或不正确的值继续处理。Rust 类型系统的 <code>Result</code> 枚举代表操作可能会在一种可以恢复的情况下失败。可以使用 <code>Result</code> 来告诉代码调用者他需要处理潜在的成功或失败。在适当的场景使用 <code>panic!</code><code>Result</code> 将会使你的代码在面对不可避免的错误时显得更加可靠。</p>
<p>现在我们已经见识过了标准库中 <code>Option</code><code>Result</code> 泛型枚举的能力了,在下一章让我们聊聊泛型是如何工作的,以及如何在你的代码中使用它们。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="泛型trait-和生命周期"><a class="header" href="#泛型trait-和生命周期">泛型、Trait 和生命周期</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch10-00-generics.md">ch10-00-generics.md</a>
<br>
commit 4aa96a3d20570f868bd20e8e3e865b047284be30</p>
</blockquote>
<p>每一个编程语言都有高效处理重复概念的工具。在 Rust 中其工具之一就是 <strong>泛型</strong><em>generics</em>)。泛型是具体类型或其他属性的抽象替代。我们可以表达泛型的属性,比如它们的行为或如何与其他泛型相关联,而不需要在编写和编译代码时知道它们在这里实际上代表什么。</p>
<p>函数可以获取一些不同于 <code>i32</code><code>String</code> 这样具体类型的泛型参数,就像一个获取未知类型值的函数可以对多种具体类型的值运行同一段代码一样。事实上我们已经使用过第六章的 <code>Option&lt;T&gt;</code>,第八章的 <code>Vec&lt;T&gt;</code><code>HashMap&lt;K, V&gt;</code>,以及第九章的 <code>Result&lt;T, E&gt;</code> 这些泛型了。本章会探索如何使用泛型定义我们自己的类型、函数和方法!</p>
<p>首先,我们将回顾一下提取函数以减少代码重复的机制。接下来,我们将使用相同的技术,从两个仅参数类型不同的函数中创建一个泛型函数。我们也会讲到结构体和枚举定义中的泛型。</p>
<p>之后,我们讨论 <strong>trait</strong>这是一个定义泛型行为的方法。trait 可以与泛型结合来将泛型限制为只接受拥有特定行为的类型,而不是任意类型。</p>
<p>最后介绍 <strong>生命周期</strong><em>lifetimes</em>它是一类允许我们向编译器提供引用如何相互关联的泛型。Rust 的生命周期功能允许在很多场景下借用值的同时仍然使编译器能够检查这些引用的有效性。</p>
<h2 id="提取函数来减少重复"><a class="header" href="#提取函数来减少重复">提取函数来减少重复</a></h2>
<p>泛型允许我们使用一个可以代表多种类型的占位符来替换特定类型,以此来减少代码冗余。在深入了解泛型的语法之前,我们首先来看一种没有使用泛型的减少冗余的方法,即提取一个函数。在这个函数中,我们用一个可以代表多种值的占位符来替换具体的值。接着我们使用相同的技术来提取一个泛型函数!!通过学习如何识别并提取可以整合进一个函数的重复代码,你也会开始识别出可以使用泛型的重复代码。</p>
<p>让我们从下面这个这个寻找列表中最大值的小程序开始,如示例 10-1 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let mut largest = &amp;number_list[0];
for number in &amp;number_list {
if number &gt; largest {
largest = number;
}
}
println!("The largest number is {largest}");
<span class="boring"> assert_eq!(*largest, 100);
</span>}</code></pre></pre>
<p><span class="caption">示例 10-1在一个数字列表中寻找最大值的函数</span></p>
<p>这段代码获取一个整型列表,存放在变量 <code>number_list</code> 中。它将列表的第一个数字的引用放入了变量 <code>largest</code> 中。接着遍历了列表中的所有数字,如果当前值大于 <code>largest</code> 中储存的值,将 <code>largest</code> 替换为这个值。如果当前值小于或者等于目前为止的最大值,<code>largest</code> 保持不变。当列表中所有值都被考虑到之后,<code>largest</code> 将会指向最大值,在这里也就是 100。</p>
<p>我们的任务是在两个不同的数字列表中寻找最大值。为此我们可以选择重复示例 10-1 中的代码在程序的两个不同位置使用相同的逻辑,如示例 10-2 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let mut largest = &amp;number_list[0];
for number in &amp;number_list {
if number &gt; largest {
largest = number;
}
}
println!("The largest number is {largest}");
let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];
let mut largest = &amp;number_list[0];
for number in &amp;number_list {
if number &gt; largest {
largest = number;
}
}
println!("The largest number is {largest}");
}</code></pre></pre>
<p><span class="caption">示例 10-2寻找 <strong>两个</strong> 数字列表最大值的代码</span></p>
<p>虽然代码能够执行,但是重复的代码是冗余且容易出错的,更新逻辑时我们不得不记住需要修改多处地方的代码。</p>
<p>为了消除重复,我们要创建一层抽象,定义一个处理任意整型列表作为参数的函数。这个方案使得代码更简洁,并且表现了寻找任意列表中最大值这一概念。</p>
<p>在示例 10-3 的程序中将寻找最大值的代码提取到了一个叫做 <code>largest</code> 的函数中。接着我们调用该函数来寻找示例 10-2 中两个列表中的最大值。之后也可以将该函数用于任何可能的 <code>i32</code> 值的列表。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn largest(list: &amp;[i32]) -&gt; &amp;i32 {
let mut largest = &amp;list[0];
for item in list {
if item &gt; largest {
largest = item;
}
}
largest
}
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&amp;number_list);
println!("The largest number is {result}");
<span class="boring"> assert_eq!(*result, 100);
</span>
let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];
let result = largest(&amp;number_list);
println!("The largest number is {result}");
<span class="boring"> assert_eq!(*result, 6000);
</span>}</code></pre></pre>
<p><span class="caption">示例 10-3抽象后的寻找两个数字列表最大值的代码</span></p>
<p><code>largest</code> 函数有一个参数 <code>list</code>,它代表会传递给函数的任何具体的 <code>i32</code>值的 slice。函数定义中的 <code>list</code> 代表任何 <code>&amp;[i32]</code>。当调用 <code>largest</code> 函数时,其代码实际上运行于我们传递的特定值上。</p>
<p>总的来说,从示例 10-2 到示例 10-3 中涉及的机制经历了如下几步:</p>
<ol>
<li>找出重复代码。</li>
<li>将重复代码提取到了一个函数中,并在函数签名中指定了代码中的输入和返回值。</li>
<li>将重复代码的两个实例,改为调用函数。</li>
</ol>
<p>接下来我们会使用相同的步骤通过泛型来减少重复。与函数体可以处理任意的 <code>list</code> 而不是具体的值一样,泛型也允许代码处理任意类型。</p>
<p>如果我们有两个函数,一个寻找一个 <code>i32</code> 值的 slice 中的最大项而另一个寻找 <code>char</code> 值的 slice 中的最大项该怎么办?该如何消除重复呢?让我们拭目以待!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="泛型数据类型"><a class="header" href="#泛型数据类型">泛型数据类型</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch10-01-syntax.md">ch10-01-syntax.md</a>
<br>
commit f2a78f64b668f63f581203c6bac509903f7c00ee</p>
</blockquote>
<p>我们可以使用泛型为像函数签名或结构体这样的项创建定义,这样它们就可以用于多种不同的具体数据类型。让我们看看如何使用泛型定义函数、结构体、枚举和方法,然后我们将讨论泛型如何影响代码性能。</p>
<h3 id="在函数定义中使用泛型"><a class="header" href="#在函数定义中使用泛型">在函数定义中使用泛型</a></h3>
<p>当使用泛型定义函数时,本来在函数签名中指定参数和返回值的类型的地方,会改用泛型来表示。采用这种技术,使得代码适应性更强,从而为函数的调用者提供更多的功能,同时也避免了代码的重复。</p>
<p>回到 <code>largest</code> 函数,示例 10-4 中展示了两个函数,它们的功能都是寻找 slice 中最大值。接着我们使用泛型将其合并为一个函数。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn largest_i32(list: &amp;[i32]) -&gt; &amp;i32 {
let mut largest = &amp;list[0];
for item in list {
if item &gt; largest {
largest = item;
}
}
largest
}
fn largest_char(list: &amp;[char]) -&gt; &amp;char {
let mut largest = &amp;list[0];
for item in list {
if item &gt; largest {
largest = item;
}
}
largest
}
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = largest_i32(&amp;number_list);
println!("The largest number is {result}");
<span class="boring"> assert_eq!(*result, 100);
</span>
let char_list = vec!['y', 'm', 'a', 'q'];
let result = largest_char(&amp;char_list);
println!("The largest char is {result}");
<span class="boring"> assert_eq!(*result, 'y');
</span>}</code></pre></pre>
<p><span class="caption">示例 10-4两个函数不同点只是名称和签名类型</span></p>
<p><code>largest_i32</code> 函数是从示例 10-3 中摘出来的,它用来寻找 slice 中最大的 <code>i32</code><code>largest_char</code> 函数寻找 slice 中最大的 <code>char</code>。因为两者函数体的代码是一样的,我们可以定义一个函数,再引进泛型参数来消除这种重复。</p>
<p>为了参数化这个新函数中的这些类型,我们需要为类型参数命名,道理和给函数的形参起名一样。任何标识符都可以作为类型参数的名字。这里选用 <code>T</code>因为传统上来说Rust 的类型参数名字都比较短通常仅为一个字母同时Rust 类型名的命名规范是首字母大写驼峰式命名法UpperCamelCase<code>T</code> 作为 “type” 的缩写是大部分 Rust 程序员的首选。</p>
<p>如果要在函数体中使用参数,就必须在函数签名中声明它的名字,好让编译器知道这个名字指代的是什么。同理,当在函数签名中使用一个类型参数时,必须在使用它之前就声明它。为了定义泛型版本的 <code>largest</code> 函数,类型参数声明位于函数名称与参数列表中间的尖括号 <code>&lt;&gt;</code> 中,像这样:</p>
<pre><code class="language-rust ignore">fn largest&lt;T&gt;(list: &amp;[T]) -&gt; &amp;T {</code></pre>
<p>可以这样理解这个定义:函数 <code>largest</code> 有泛型类型 <code>T</code>。它有个参数 <code>list</code>,其类型是元素为 <code>T</code> 的 slice。<code>largest</code> 函数会返回一个与 <code>T</code> 相同类型的引用。</p>
<p>示例 10-5 中的 <code>largest</code> 函数在它的签名中使用了泛型,统一了两个实现。该示例也展示了如何调用 <code>largest</code> 函数,把 <code>i32</code> 值的 slice 或 <code>char</code> 值的 slice 传给它。请注意这些代码还不能编译,不过稍后在本章会解决这个问题。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn largest&lt;T&gt;(list: &amp;[T]) -&gt; &amp;T {
let mut largest = &amp;list[0];
for item in list {
if item &gt; largest {
largest = item;
}
}
largest
}
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&amp;number_list);
println!("The largest number is {result}");
let char_list = vec!['y', 'm', 'a', 'q'];
let result = largest(&amp;char_list);
println!("The largest char is {result}");
}</code></pre>
<p><span class="caption">示例 10-5一个使用泛型参数的 <code>largest</code> 函数定义,尚不能编译</span></p>
<p>如果现在就编译这个代码,会出现如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0369]: binary operation `&gt;` cannot be applied to type `&amp;T`
--&gt; src/main.rs:5:17
|
5 | if item &gt; largest {
| ---- ^ ------- &amp;T
| |
| &amp;T
|
help: consider restricting type parameter `T`
|
1 | fn largest&lt;T: std::cmp::PartialOrd&gt;(list: &amp;[T]) -&gt; &amp;T {
| ++++++++++++++++++++++
For more information about this error, try `rustc --explain E0369`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
</code></pre>
<p>帮助说明中提到了 <code>std::cmp::PartialOrd</code>,这是一个 <em>trait</em>。下一部分会讲到 trait。不过简单来说这个错误表明 <code>largest</code> 的函数体不能适用于 <code>T</code> 的所有可能的类型。因为在函数体需要比较 <code>T</code> 类型的值,不过它只能用于我们知道如何排序的类型。为了开启比较功能,标准库中定义的 <code>std::cmp::PartialOrd</code> trait 可以实现类型的比较功能(查看附录 C 获取该 trait 的更多信息)。依照帮助说明中的建议,我们限制 <code>T</code> 只对实现了 <code>PartialOrd</code> 的类型有效后代码就可以编译了,因为标准库为 <code>i32</code><code>char</code> 实现了 <code>PartialOrd</code></p>
<h3 id="结构体定义中的泛型"><a class="header" href="#结构体定义中的泛型">结构体定义中的泛型</a></h3>
<p>同样也可以用 <code>&lt;&gt;</code> 语法来定义结构体,它包含一个或多个泛型参数类型字段。示例 10-6 定义了一个可以存放任何类型的 <code>x</code><code>y</code> 坐标值的结构体 <code>Point</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct Point&lt;T&gt; {
x: T,
y: T,
}
fn main() {
let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };
}</code></pre></pre>
<p><span class="caption">示例 10-6<code>Point</code> 结构体存放了两个 <code>T</code> 类型的值 <code>x</code><code>y</code></span></p>
<p>其语法类似于函数定义中使用泛型。首先,必须在结构体名称后面的尖括号中声明泛型参数的名称。接着在结构体定义中可以指定具体数据类型的位置使用泛型类型。</p>
<p>注意 <code>Point&lt;T&gt;</code> 的定义中只使用了一个泛型类型,这个定义表明结构体 <code>Point&lt;T&gt;</code> 对于一些类型 <code>T</code> 是泛型的,而且字段 <code>x</code><code>y</code> <strong>都是</strong> 相同类型的,无论它具体是何类型。如果尝试创建一个有不同类型值的 <code>Point&lt;T&gt;</code> 的实例,像示例 10-7 中的代码就不能编译:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">struct Point&lt;T&gt; {
x: T,
y: T,
}
fn main() {
let wont_work = Point { x: 5, y: 4.0 };
}</code></pre>
<p><span class="caption">示例 10-7字段 <code>x</code><code>y</code> 的类型必须相同,因为它们都有相同的泛型类型 <code>T</code></span></p>
<p>在这个例子中,当把整型值 5 赋值给 <code>x</code> 时,就告诉了编译器这个 <code>Point&lt;T&gt;</code> 实例中的泛型 <code>T</code> 全是整型。接着指定 <code>y</code> 为浮点值 4.0,因为它<code>y</code>被定义为与 <code>x</code> 相同类型,所以将会得到一个像这样的类型不匹配错误:</p>
<pre><code class="language-console">$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0308]: mismatched types
--&gt; src/main.rs:7:38
|
7 | let wont_work = Point { x: 5, y: 4.0 };
| ^^^ expected integer, found floating-point number
For more information about this error, try `rustc --explain E0308`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
</code></pre>
<p>如果想要定义一个 <code>x</code><code>y</code> 可以有不同类型且仍然是泛型的 <code>Point</code> 结构体,我们可以使用多个泛型类型参数。在示例 10-8 中,我们修改 <code>Point</code> 的定义为拥有两个泛型类型 <code>T</code><code>U</code>。其中字段 <code>x</code><code>T</code> 类型的,而字段 <code>y</code><code>U</code> 类型的:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct Point&lt;T, U&gt; {
x: T,
y: U,
}
fn main() {
let both_integer = Point { x: 5, y: 10 };
let both_float = Point { x: 1.0, y: 4.0 };
let integer_and_float = Point { x: 5, y: 4.0 };
}</code></pre></pre>
<p><span class="caption">示例 10-8使用两个泛型的 <code>Point</code>,这样 <code>x</code><code>y</code> 可能是不同类型</span></p>
<p>现在所有这些 <code>Point</code> 实例都合法了!你可以在定义中使用任意多的泛型类型参数,不过太多的话,代码将难以阅读和理解。当你发现代码中需要很多泛型时,这可能表明你的代码需要重构分解成更小的结构。</p>
<h3 id="枚举定义中的泛型"><a class="header" href="#枚举定义中的泛型">枚举定义中的泛型</a></h3>
<p>和结构体类似,枚举也可以在成员中存放泛型数据类型。第六章我们曾用过标准库提供的 <code>Option&lt;T&gt;</code> 枚举,这里再回顾一下:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>enum Option&lt;T&gt; {
Some(T),
None,
}
<span class="boring">}</span></code></pre></pre>
<p>现在这个定义应该更容易理解了。如你所见 <code>Option&lt;T&gt;</code> 是一个拥有泛型 <code>T</code> 的枚举,它有两个成员:<code>Some</code>,它存放了一个类型 <code>T</code> 的值,和不存在任何值的<code>None</code>。通过 <code>Option&lt;T&gt;</code> 枚举可以表达有一个可能的值的抽象概念,同时因为 <code>Option&lt;T&gt;</code> 是泛型的,无论这个可能的值是什么类型都可以使用这个抽象。</p>
<p>枚举也可以拥有多个泛型类型。第九章使用过的 <code>Result</code> 枚举定义就是一个这样的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>enum Result&lt;T, E&gt; {
Ok(T),
Err(E),
}
<span class="boring">}</span></code></pre></pre>
<p><code>Result</code> 枚举有两个泛型类型,<code>T</code><code>E</code><code>Result</code> 有两个成员:<code>Ok</code>,它存放一个类型 <code>T</code> 的值,而 <code>Err</code> 则存放一个类型 <code>E</code> 的值。这个定义使得 <code>Result</code> 枚举能很方便的表达任何可能成功(返回 <code>T</code> 类型的值)也可能失败(返回 <code>E</code> 类型的值)的操作。实际上,这就是我们在示例 9-3 用来打开文件的方式:当成功打开文件的时候,<code>T</code> 对应的是 <code>std::fs::File</code> 类型;而当打开文件出现问题时,<code>E</code> 的值则是 <code>std::io::Error</code> 类型。</p>
<p>当你意识到代码中定义了多个结构体或枚举,它们不一样的地方只是其中的值的类型的时候,不妨通过泛型类型来避免重复。</p>
<h3 id="方法定义中的泛型"><a class="header" href="#方法定义中的泛型">方法定义中的泛型</a></h3>
<p>在为结构体和枚举实现方法时(像第五章那样),一样也可以用泛型。示例 10-9 中展示了示例 10-6 中定义的结构体 <code>Point&lt;T&gt;</code>,和在其上实现的名为 <code>x</code> 的方法。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct Point&lt;T&gt; {
x: T,
y: T,
}
impl&lt;T&gt; Point&lt;T&gt; {
fn x(&amp;self) -&gt; &amp;T {
&amp;self.x
}
}
fn main() {
let p = Point { x: 5, y: 10 };
println!("p.x = {}", p.x());
}</code></pre></pre>
<p><span class="caption">示例 10-9<code>Point&lt;T&gt;</code> 结构体上实现方法 <code>x</code>,它返回 <code>T</code> 类型的字段 <code>x</code> 的引用</span></p>
<p>这里在 <code>Point&lt;T&gt;</code> 上定义了一个叫做 <code>x</code> 的方法来返回字段 <code>x</code> 中数据的引用:</p>
<p>注意必须在 <code>impl</code> 后面声明 <code>T</code>,这样就可以在 <code>Point&lt;T&gt;</code> 上实现的方法中使用 <code>T</code> 了。通过在 <code>impl</code> 之后声明泛型 <code>T</code>Rust 就知道 <code>Point</code> 的尖括号中的类型是泛型而不是具体类型。我们可以为泛型参数选择一个与结构体定义中声明的泛型参数所不同的名称,不过依照惯例使用了相同的名称。在声明泛型类型参数的 <code>impl</code> 中编写的方法将会定义在该类型的任何实例上,无论最终替换泛型类型参数的是何具体类型。(译者注:以示例 10-9 为例,<code>impl</code> 中声明了泛型类型参数 <code>T</code><code>x</code> 是编写在 <code>impl</code> 中的方法,<code>x</code> 方法将会定义在 <code>Point&lt;T&gt;</code> 的任何实例上,无论最终替换泛型类型参数 <code>T</code> 的是何具体类型)。</p>
<p>定义方法时也可以为泛型指定限制constraint。例如可以选择为 <code>Point&lt;f32&gt;</code> 实例实现方法,而不是为泛型 <code>Point</code> 实例。示例 10-10 展示了一个没有在 <code>impl</code> 之后(的尖括号)声明泛型的例子,这里使用了一个具体类型,<code>f32</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct Point&lt;T&gt; {
</span><span class="boring"> x: T,
</span><span class="boring"> y: T,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl&lt;T&gt; Point&lt;T&gt; {
</span><span class="boring"> fn x(&amp;self) -&gt; &amp;T {
</span><span class="boring"> &amp;self.x
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>impl Point&lt;f32&gt; {
fn distance_from_origin(&amp;self) -&gt; f32 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let p = Point { x: 5, y: 10 };
</span><span class="boring">
</span><span class="boring"> println!("p.x = {}", p.x());
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 10-10构建一个只用于拥有泛型参数 <code>T</code> 的结构体的具体类型的 <code>impl</code></span></p>
<p>这段代码意味着 <code>Point&lt;f32&gt;</code> 类型会有一个方法 <code>distance_from_origin</code>,而其他 <code>T</code> 不是 <code>f32</code> 类型的 <code>Point&lt;T&gt;</code> 实例则没有定义此方法。这个方法计算点实例与坐标 (0.0, 0.0) 之间的距离,并使用了只能用于浮点型的数学运算符。</p>
<p>结构体定义中的泛型类型参数并不总是与结构体方法签名中使用的泛型是同一类型。示例 10-11 中为 <code>Point</code> 结构体使用了泛型类型 <code>X1</code><code>Y1</code>,为 <code>mixup</code> 方法签名使用了 <code>X2</code><code>Y2</code> 来使得示例更加清楚。这个方法用 <code>self</code><code>Point</code> 类型的 <code>x</code> 值(类型 <code>X1</code>)和参数的 <code>Point</code> 类型的 <code>y</code> 值(类型 <code>Y2</code>)来创建一个新 <code>Point</code> 类型的实例:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct Point&lt;X1, Y1&gt; {
x: X1,
y: Y1,
}
impl&lt;X1, Y1&gt; Point&lt;X1, Y1&gt; {
fn mixup&lt;X2, Y2&gt;(self, other: Point&lt;X2, Y2&gt;) -&gt; Point&lt;X1, Y2&gt; {
Point {
x: self.x,
y: other.y,
}
}
}
fn main() {
let p1 = Point { x: 5, y: 10.4 };
let p2 = Point { x: "Hello", y: 'c' };
let p3 = p1.mixup(p2);
println!("p3.x = {}, p3.y = {}", p3.x, p3.y);
}</code></pre></pre>
<p><span class="caption">示例 10-11方法使用了与结构体定义中不同类型的泛型</span></p>
<p><code>main</code> 函数中,定义了一个有 <code>i32</code> 类型的 <code>x</code>(其值为 <code>5</code>)和 <code>f64</code><code>y</code>(其值为 <code>10.4</code>)的 <code>Point</code><code>p2</code> 则是一个有着字符串 slice 类型的 <code>x</code>(其值为 <code>"Hello"</code>)和 <code>char</code> 类型的 <code>y</code>(其值为<code>c</code>)的 <code>Point</code>。在 <code>p1</code> 上以 <code>p2</code> 作为参数调用 <code>mixup</code> 会返回一个 <code>p3</code>,它会有一个 <code>i32</code> 类型的 <code>x</code>,因为 <code>x</code> 来自 <code>p1</code>,并拥有一个 <code>char</code> 类型的 <code>y</code>,因为 <code>y</code> 来自 <code>p2</code><code>println!</code> 会打印出 <code>p3.x = 5, p3.y = c</code></p>
<p>这个例子的目的是展示一些泛型通过 <code>impl</code> 声明而另一些通过方法定义声明的情况。这里泛型参数 <code>X1</code><code>Y1</code> 声明于 <code>impl</code> 之后,因为它们与结构体定义相对应。而泛型参数 <code>X2</code><code>Y2</code> 声明于 <code>fn mixup</code> 之后,因为它们只是相对于方法本身的。</p>
<h3 id="泛型代码的性能"><a class="header" href="#泛型代码的性能">泛型代码的性能</a></h3>
<p>在阅读本部分内容的同时,你可能会好奇使用泛型类型参数是否会有运行时消耗。好消息是泛型并不会使程序比具体类型运行得慢。</p>
<p>Rust 通过在编译时进行泛型代码的 <strong>单态化</strong><em>monomorphization</em>)来保证效率。单态化是一个通过填充编译时使用的具体类型,将通用代码转换为特定代码的过程。</p>
<p>在这个过程中,编译器所做的工作正好与示例 10-5 中我们创建泛型函数的步骤相反。编译器寻找所有泛型代码被调用的位置并使用泛型代码针对具体类型生成代码。</p>
<p>让我们看看这如何用于标准库中的 <code>Option</code> 枚举:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let integer = Some(5);
let float = Some(5.0);
<span class="boring">}</span></code></pre></pre>
<p>当 Rust 编译这些代码的时候,它会进行单态化。编译器会读取传递给 <code>Option&lt;T&gt;</code> 的值并发现有两种 <code>Option&lt;T&gt;</code>:一个对应 <code>i32</code> 另一个对应 <code>f64</code>。为此,它会将泛型定义 <code>Option&lt;T&gt;</code> 展开为两个针对 <code>i32</code><code>f64</code> 的定义,接着将泛型定义替换为这两个具体的定义。</p>
<p>编译器生成的单态化版本的代码看起来像这样(编译器会使用不同于如下假想的名字):</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">enum Option_i32 {
Some(i32),
None,
}
enum Option_f64 {
Some(f64),
None,
}
fn main() {
let integer = Option_i32::Some(5);
let float = Option_f64::Some(5.0);
}</code></pre></pre>
<p>泛型 <code>Option&lt;T&gt;</code> 被编译器替换为了具体的定义。因为 Rust 会将每种情况下的泛型代码编译为具体类型,使用泛型没有运行时开销。当代码运行时,它的执行效率就跟好像手写每个具体定义的重复代码一样。这个单态化过程正是 Rust 泛型在运行时极其高效的原因。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="trait定义共同行为"><a class="header" href="#trait定义共同行为">Trait定义共同行为</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch10-02-traits.md">ch10-02-traits.md</a>
<br>
commit 92bfbfacf88ee9a814cea0a58e9c019c529ef4ae</p>
</blockquote>
<p><em>trait</em> 定义了某个特定类型拥有可能与其他类型共享的功能。可以通过 trait 以一种抽象的方式定义共同行为。可以使用 <em>trait bounds</em> 指定泛型是任何拥有特定行为的类型。</p>
<blockquote>
<p>注意:<em>trait</em> 类似于其他语言中的常被称为 <strong>接口</strong><em>interfaces</em>)的功能,虽然有一些不同。</p>
</blockquote>
<h3 id="定义-trait"><a class="header" href="#定义-trait">定义 trait</a></h3>
<p>一个类型的行为由其可供调用的方法构成。如果可以对不同类型调用相同的方法的话这些类型就可以共享相同的行为了。trait 定义是一种将方法签名组合起来的方法,目的是定义一个实现某些目的所必需的行为的集合。</p>
<p>例如,这里有多个存放了不同类型和属性文本的结构体:结构体 <code>NewsArticle</code> 用于存放发生于世界各地的新闻故事,而结构体 <code>Tweet</code> 最多只能存放 280 个字符的内容,以及像是否转推或是否是对推友的回复这样的元数据。</p>
<p>我们想要创建一个名为 <code>aggregator</code> 的多媒体聚合库用来显示可能储存在 <code>NewsArticle</code><code>Tweet</code> 实例中的数据摘要。为了实现功能,每个结构体都要能够获取摘要,这样的话就可以调用实例的 <code>summarize</code> 方法来请求摘要。示例 10-12 中展示了一个表现这个概念的公有 <code>Summary</code> trait 的定义:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub trait Summary {
fn summarize(&amp;self) -&gt; String;
}</code></pre>
<p><span class="caption">示例 10-12<code>Summary</code> trait 定义,它包含由 <code>summarize</code> 方法提供的行为</span></p>
<p>这里使用 <code>trait</code> 关键字来声明一个 trait后面是 trait 的名字,在这个例子中是 <code>Summary</code>。我们也声明 <code>trait</code><code>pub</code> 以便依赖这个 crate 的 crate 也可以使用这个 trait正如我们见过的一些示例一样。在大括号中声明描述实现这个 trait 的类型所需要的行为的方法签名,在这个例子中是 <code>fn summarize(&amp;self) -&gt; String</code></p>
<p>在方法签名后跟分号,而不是在大括号中提供其实现。接着每一个实现这个 trait 的类型都需要提供其自定义行为的方法体,编译器也会确保任何实现 <code>Summary</code> trait 的类型都拥有与这个签名的定义完全一致的 <code>summarize</code> 方法。</p>
<p>trait 体中可以有多个方法:一行一个方法签名且都以分号结尾。</p>
<h3 id="为类型实现-trait"><a class="header" href="#为类型实现-trait">为类型实现 trait</a></h3>
<p>现在我们定义了 <code>Summary</code> trait 的签名,接着就可以在多媒体聚合库中实现这个类型了。示例 10-13 中展示了 <code>NewsArticle</code> 结构体上 <code>Summary</code> trait 的一个实现,它使用标题、作者和创建的位置作为 <code>summarize</code> 的返回值。对于 <code>Tweet</code> 结构体,我们选择将 <code>summarize</code> 定义为用户名后跟推文的全部文本作为返回值,并假设推文内容已经被限制为 280 字符以内。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Summary {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span>pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&amp;self) -&gt; String {
format!("{}, 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(&amp;self) -&gt; 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> traitcrate 的用户可以像调用常规方法一样调用 <code>NewsArticle</code><code>Tweet</code> 实例的 trait 方法了。唯一的区别是 trait 必须和类型一起引入作用域以便使用额外的 trait 方法。这是一个二进制 crate 如何利用 <code>aggregator</code> 库 crate 的例子:</p>
<pre><code class="language-rust ignore">use aggregator::{Summary, Tweet};
fn main() {
let tweet = Tweet {
username: String::from("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&lt;T&gt;</code> 实现 <code>Summary</code>,这是因为 <code>Summary</code> trait 位于 <code>aggregator</code> crate 本地作用域中。</p>
<p>但是不能为外部类型实现外部 trait。例如不能在 <code>aggregator</code> crate 中为 <code>Vec&lt;T&gt;</code> 实现 <code>Display</code> trait。这是因为 <code>Display</code><code>Vec&lt;T&gt;</code> 都定义于标准库中,它们并不位于 <code>aggregator</code> crate 本地作用域中。这个限制是被称为 <strong>相干性</strong><em>coherence</em>)的程序属性的一部分,或者更具体的说是 <strong>孤儿规则</strong><em>orphan rule</em>),其得名于不存在父类型。这条规则确保了其他人编写的代码不会破坏你代码,反之亦然。没有这条规则的话,两个 crate 可以分别对相同类型实现相同的 trait而 Rust 将无从得知应该使用哪一个实现。</p>
<h3 id="默认实现"><a class="header" href="#默认实现">默认实现</a></h3>
<p>有时为 trait 中的某些或全部方法提供默认的行为,而不是在每个类型的每个实现中都定义自己的行为是很有用的。这样当为某个特定类型实现 trait 时,可以选择保留或重载每个方法的默认行为。</p>
<p>示例 10-14 中我们为 <code>Summary</code> trait 的 <code>summarize</code> 方法指定一个默认的字符串值,而不是像示例 10-12 中那样只是定义方法签名:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub trait Summary {
fn summarize(&amp;self) -&gt; String {
String::from("(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(&amp;self) -&gt; 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(&amp;self) -&gt; String;
fn summarize(&amp;self) -&gt; 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(&amp;self) -&gt; 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(&amp;self) -&gt; String;
</span><span class="boring">
</span><span class="boring"> fn summarize(&amp;self) -&gt; 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(&amp;self) -&gt; 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(&amp;self) -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct NewsArticle {
</span><span class="boring"> pub headline: String,
</span><span class="boring"> pub location: String,
</span><span class="boring"> pub author: String,
</span><span class="boring"> pub content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for NewsArticle {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!("{}, 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(&amp;self) -&gt; 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: &amp;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&lt;T: Summary&gt;(item: &amp;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: &amp;impl Summary, item2: &amp;impl Summary) {</code></pre>
<p>这适用于 <code>item1</code><code>item2</code> 允许是不同类型的情况(只要它们都实现了 <code>Summary</code>)。不过如果你希望强制它们都是相同类型呢?这只有在使用 trait bound 时才有可能:</p>
<pre><code class="language-rust ignore">pub fn notify&lt;T: Summary&gt;(item1: &amp;T, item2: &amp;T) {</code></pre>
<p>泛型 <code>T</code> 被指定为 <code>item1</code><code>item2</code> 的参数限制,如此传递给参数 <code>item1</code><code>item2</code> 值的具体类型必须一致。</p>
<h4 id="通过--指定多个-trait-bound"><a class="header" href="#通过--指定多个-trait-bound">通过 <code>+</code> 指定多个 trait bound</a></h4>
<p>如果 <code>notify</code> 需要显示 <code>item</code> 的格式化形式,同时也要使用 <code>summarize</code> 方法,那么 <code>item</code> 就需要同时实现两个不同的 trait<code>Display</code><code>Summary</code>。这可以通过 <code>+</code> 语法实现:</p>
<pre><code class="language-rust ignore">pub fn notify(item: &amp;(impl Summary + Display)) {</code></pre>
<p><code>+</code> 语法也适用于泛型的 trait bound</p>
<pre><code class="language-rust ignore">pub fn notify&lt;T: Summary + Display&gt;(item: &amp;T) {</code></pre>
<p>通过指定这两个 trait bound<code>notify</code> 的函数体可以调用 <code>summarize</code> 并使用 <code>{}</code> 来格式化 <code>item</code></p>
<h4 id="通过-where-简化-trait-bound"><a class="header" href="#通过-where-简化-trait-bound">通过 <code>where</code> 简化 trait bound</a></h4>
<p>然而,使用过多的 trait bound 也有缺点。每个泛型有其自己的 trait bound所以有多个泛型参数的函数在名称和参数列表之间会有很长的 trait bound 信息这使得函数签名难以阅读。为此Rust 有另一个在函数签名之后的 <code>where</code> 从句中指定 trait bound 的语法。所以除了这么写:</p>
<pre><code class="language-rust ignore">fn some_function&lt;T: Display + Clone, U: Clone + Debug&gt;(t: &amp;T, u: &amp;U) -&gt; i32 {</code></pre>
<p>还可以像这样使用 <code>where</code> 从句:</p>
<pre><code class="language-rust ignore">fn some_function&lt;T, U&gt;(t: &amp;T, u: &amp;U) -&gt; i32
where
T: Display + Clone,
U: Clone + Debug,
{
<span class="boring"> unimplemented!()
</span><span class="boring">}</span></code></pre>
<p>这个函数签名就显得不那么杂乱,函数名、参数列表和返回值类型都离得很近,看起来跟没有那么多 trait bounds 的函数很像。</p>
<h3 id="返回实现了-trait-的类型"><a class="header" href="#返回实现了-trait-的类型">返回实现了 trait 的类型</a></h3>
<p>也可以在返回值中使用 <code>impl Trait</code> 语法,来返回实现了某个 trait 的类型:</p>
<pre><code class="language-rust ignore"><span class="boring">pub trait Summary {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct NewsArticle {
</span><span class="boring"> pub headline: String,
</span><span class="boring"> pub location: String,
</span><span class="boring"> pub author: String,
</span><span class="boring"> pub content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for NewsArticle {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!("{}, 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(&amp;self) -&gt; 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() -&gt; 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(&amp;self) -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct NewsArticle {
</span><span class="boring"> pub headline: String,
</span><span class="boring"> pub location: String,
</span><span class="boring"> pub author: String,
</span><span class="boring"> pub content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Summary for NewsArticle {
</span><span class="boring"> fn summarize(&amp;self) -&gt; String {
</span><span class="boring"> format!("{}, 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(&amp;self) -&gt; 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) -&gt; 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="ch18-02-trait-objects.html#%E9%A1%BE%E5%8F%8A%E4%B8%8D%E5%90%8C%E7%B1%BB%E5%9E%8B%E5%80%BC%E7%9A%84-trait-%E5%AF%B9%E8%B1%A1">“顾及不同类型值的 trait 对象”</a> 部分会介绍如何编写这样一个函数。</p>
<h3 id="使用-trait-bound-有条件地实现方法"><a class="header" href="#使用-trait-bound-有条件地实现方法">使用 trait bound 有条件地实现方法</a></h3>
<p>通过使用带有 trait bound 的泛型参数的 <code>impl</code> 块,可以有条件地只为那些实现了特定 trait 的类型实现方法。例如,示例 10-15 中的类型 <code>Pair&lt;T&gt;</code> 总是实现了 <code>new</code> 方法并返回一个 <code>Pair&lt;T&gt;</code> 的实例(回忆一下第五章的 <a href="ch05-03-method-syntax.html#%E5%AE%9A%E4%B9%89%E6%96%B9%E6%B3%95">“定义方法”</a> 部分,<code>Self</code> 是一个 <code>impl</code> 块类型的类型别名type alias在这里是 <code>Pair&lt;T&gt;</code>)。不过在下一个 <code>impl</code> 块中,只有那些为 <code>T</code> 类型实现了 <code>PartialOrd</code> trait来允许比较 <strong></strong> <code>Display</code> trait来启用打印<code>Pair&lt;T&gt;</code> 才会实现 <code>cmp_display</code> 方法:</p>
<pre><code class="language-rust noplayground">use std::fmt::Display;
struct Pair&lt;T&gt; {
x: T,
y: T,
}
impl&lt;T&gt; Pair&lt;T&gt; {
fn new(x: T, y: T) -&gt; Self {
Self { x, y }
}
}
impl&lt;T: Display + PartialOrd&gt; Pair&lt;T&gt; {
fn cmp_display(&amp;self) {
if self.x &gt;= self.y {
println!("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&lt;T: Display&gt; ToString for T {
// --snip--
}</code></pre>
<p>因为标准库有了这些 blanket implementation我们可以对任何实现了 <code>Display</code> trait 的类型调用由 <code>ToString</code> 定义的 <code>to_string</code> 方法。例如,可以将整型转换为对应的 <code>String</code> 值,因为整型实现了 <code>Display</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><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>
<div style="break-before: page; page-break-before: always;"></div><h2 id="生命周期确保引用有效"><a class="header" href="#生命周期确保引用有效">生命周期确保引用有效</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch10-03-lifetime-syntax.md">ch10-03-lifetime-syntax.md</a>
<br>
commit 5f67eee42345ba44f6f08a22c2192165f4b0e930</p>
</blockquote>
<p>生命周期是另一类我们已经使用过的泛型。不同于确保类型有期望的行为,生命周期确保引用如预期一直有效。</p>
<p>当在第四章讨论 <a href="ch04-02-references-and-borrowing.html#%E5%BC%95%E7%94%A8%E4%B8%8E%E5%80%9F%E7%94%A8">“引用和借用”</a> 部分时我们遗漏了一个重要的细节Rust 中的每一个引用都有其 <strong>生命周期</strong><em>lifetime</em>),也就是引用保持有效的作用域。大部分时候生命周期是隐含并可以推断的,正如大部分时候类型也是可以推断的一样。类似于当因为有多种可能类型的时候必须注明类型,也会出现引用的生命周期以一些不同方式相关联的情况,所以 Rust 需要我们使用泛型生命周期参数来注明它们的关系,这样就能确保运行时实际使用的引用绝对是有效的。</p>
<p>生命周期注解甚至不是一个大部分语言都有的概念,所以这可能感觉起来有些陌生。虽然本章不可能涉及到它全部的内容,我们会讲到一些通常你可能会遇到的生命周期语法以便你熟悉这个概念。</p>
<h3 id="生命周期避免了悬垂引用"><a class="header" href="#生命周期避免了悬垂引用">生命周期避免了悬垂引用</a></h3>
<p>生命周期的主要目标是避免<strong>悬垂引用</strong><em>dangling references</em>),后者会导致程序引用了非预期引用的数据。考虑一下示例 10-16 中的程序,它有一个外部作用域和一个内部作用域。</p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let r;
{
let x = 5;
r = &amp;x;
}
println!("r: {r}");
}</code></pre>
<p><span class="caption">示例 10-16尝试使用离开作用域的值的引用</span></p>
<blockquote>
<p>注意:示例 10-16、10-17 和 10-23 中声明了没有初始值的变量,所以这些变量存在于外部作用域。这乍看之下好像和 Rust 不允许存在空值相冲突。然而如果尝试在给它一个值之前使用这个变量,会出现一个编译时错误,这就说明了 Rust 确实不允许空值。</p>
</blockquote>
<p>外部作用域声明了一个没有初值的变量 <code>r</code>,而内部作用域声明了一个初值为 5 的变量<code>x</code>。在内部作用域中,我们尝试将 <code>r</code> 的值设置为一个 <code>x</code> 的引用。接着在内部作用域结束后,尝试打印出 <code>r</code> 的值。这段代码不能编译因为 <code>r</code> 引用的值在尝试使用之前就离开了作用域。如下是错误信息:</p>
<pre><code class="language-console">$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `x` does not live long enough
--&gt; src/main.rs:6:13
|
5 | let x = 5;
| - binding `x` declared here
6 | r = &amp;x;
| ^^ borrowed value does not live long enough
7 | }
| - `x` dropped here while still borrowed
8 |
9 | println!("r: {r}");
| --- borrow later used here
For more information about this error, try `rustc --explain E0597`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
</code></pre>
<p>变量 <code>x</code> 并没有 “存在的足够久”。其原因是 <code>x</code> 在到达第 7 行内部作用域结束时就离开了作用域。不过 <code>r</code> 在外部作用域仍是有效的;作用域越大我们就说它 “存在的越久”。如果 Rust 允许这段代码工作,<code>r</code> 将会引用在 <code>x</code> 离开作用域时被释放的内存,这时尝试对 <code>r</code> 做任何操作都不能正常工作。那么 Rust 是如何决定这段代码是不被允许的呢?这得益于借用检查器。</p>
<h4 id="借用检查器"><a class="header" href="#借用检查器">借用检查器</a></h4>
<p>Rust 编译器有一个 <strong>借用检查器</strong><em>borrow checker</em>),它比较作用域来确保所有的借用都是有效的。示例 10-17 展示了与示例 10-16 相同的例子不过带有变量生命周期的注释:</p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let r; // ---------+-- 'a
// |
{ // |
let x = 5; // -+-- 'b |
r = &amp;x; // | |
} // -+ |
// |
println!("r: {r}"); // |
} // ---------+</code></pre>
<p><span class="caption">示例 10-17<code>r</code><code>x</code> 的生命周期注解,分别叫做 <code>'a</code><code>'b</code></span></p>
<p>这里将 <code>r</code> 的生命周期标记为 <code>'a</code> 并将 <code>x</code> 的生命周期标记为 <code>'b</code>。如你所见,内部的 <code>'b</code> 块要比外部的生命周期 <code>'a</code> 小得多。在编译时Rust 比较这两个生命周期的大小,并发现 <code>r</code> 拥有生命周期 <code>'a</code>,不过它引用了一个拥有生命周期 <code>'b</code> 的对象。程序被拒绝编译,因为生命周期 <code>'b</code> 比生命周期 <code>'a</code> 要小:被引用的对象比它的引用者存在的时间更短。</p>
<p>让我们看看示例 10-18 中这个并没有产生悬垂引用且可以正确编译的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = 5; // ----------+-- 'b
// |
let r = &amp;x; // --+-- 'a |
// | |
println!("r: {r}"); // | |
// --+ |
} // ----------+</code></pre></pre>
<p><span class="caption">示例 10-18一个有效的引用因为数据比引用有着更长的生命周期</span></p>
<p>这里 <code>x</code> 拥有生命周期 <code>'b</code>,比 <code>'a</code> 要大。这就意味着 <code>r</code> 可以引用 <code>x</code>Rust 知道 <code>r</code> 中的引用在 <code>x</code> 有效的时候也总是有效的。</p>
<p>现在我们已经在一个具体的例子中展示了引用的生命周期位于何处,并讨论了 Rust 如何分析生命周期来保证引用总是有效的,接下来让我们聊聊在函数的上下文中参数和返回值的泛型生命周期。</p>
<h3 id="函数中的泛型生命周期"><a class="header" href="#函数中的泛型生命周期">函数中的泛型生命周期</a></h3>
<p>让我们来编写一个返回两个字符串 slice 中较长者的函数。这个函数获取两个字符串 slice 并返回一个字符串 slice。一旦我们实现了 <code>longest</code> 函数,示例 10-19 中的代码应该会打印出 <code>The longest string is abcd</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {result}");
}</code></pre>
<p><span class="caption">示例 10-19<code>main</code> 函数调用 <code>longest</code> 函数来寻找两个字符串 slice 中较长的一个</span></p>
<p>注意这个函数获取作为引用的字符串 slice而不是字符串因为我们不希望 <code>longest</code> 函数获取参数的所有权。参考之前第四章中的 <a href="ch04-03-slices.html#%E5%AD%97%E7%AC%A6%E4%B8%B2-slice-%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0">“字符串 slice 作为参数”</a> 部分中更多关于为什么示例 10-19 的参数正符合我们期望的讨论。</p>
<p>如果尝试像示例 10-20 中那样实现 <code>longest</code> 函数,它并不能编译:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span><span class="boring"> let string1 = String::from("abcd");
</span><span class="boring"> let string2 = "xyz";
</span><span class="boring">
</span><span class="boring"> let result = longest(string1.as_str(), string2);
</span><span class="boring"> println!("The longest string is {result}");
</span><span class="boring">}
</span><span class="boring">
</span>fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
if x.len() &gt; y.len() {
x
} else {
y
}
}</code></pre>
<p><span class="caption">示例 10-20一个 <code>longest</code> 函数的实现,它返回两个字符串 slice 中较长者,现在还不能编译</span></p>
<p>相应地会出现如下有关生命周期的错误:</p>
<pre><code class="language-console">$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0106]: missing lifetime specifier
--&gt; src/main.rs:9:33
|
9 | fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
|
9 | fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
| ++++ ++ ++ ++
For more information about this error, try `rustc --explain E0106`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
</code></pre>
<p>提示文本揭示了返回值需要一个泛型生命周期参数,因为 Rust 并不知道将要返回的引用是指向 <code>x</code><code>y</code>。事实上我们也不知道,因为函数体中 <code>if</code> 块返回一个 <code>x</code> 的引用而 <code>else</code> 块返回一个 <code>y</code> 的引用!</p>
<p>当我们定义这个函数的时候,并不知道传递给函数的具体值,所以也不知道到底是 <code>if</code> 还是 <code>else</code> 会被执行。我们也不知道传入的引用的具体生命周期,所以也就不能像示例 10-17 和 10-18 那样通过观察作用域来确定返回的引用是否总是有效。借用检查器自身同样也无法确定,因为它不知道 <code>x</code><code>y</code> 的生命周期是如何与返回值的生命周期相关联的。为了修复这个错误,我们将增加泛型生命周期参数来定义引用间的关系以便借用检查器可以进行分析。</p>
<h3 id="生命周期注解语法"><a class="header" href="#生命周期注解语法">生命周期注解语法</a></h3>
<p>生命周期注解并不改变任何引用的生命周期的长短。相反它们描述了多个引用生命周期相互的关系,而不影响其生命周期。与当函数签名中指定了泛型类型参数后就可以接受任何类型一样,当指定了泛型生命周期后函数也能接受任何生命周期的引用。</p>
<p>生命周期注解有着一个不太常见的语法:生命周期参数名称必须以撇号(<code>'</code>)开头,其名称通常全是小写,类似于泛型其名称非常短。大多数人使用 <code>'a</code> 作为第一个生命周期注解。生命周期参数注解位于引用的 <code>&amp;</code> 之后,并有一个空格来将引用类型与生命周期注解分隔开。</p>
<p>这里有一些例子:我们有一个没有生命周期参数的 <code>i32</code> 的引用,一个有叫做 <code>'a</code> 的生命周期参数的 <code>i32</code> 的引用,和一个生命周期也是 <code>'a</code><code>i32</code> 的可变引用:</p>
<pre><code class="language-rust ignore">&amp;i32 // 引用
&amp;'a i32 // 带有显式生命周期的引用
&amp;'a mut i32 // 带有显式生命周期的可变引用</code></pre>
<p>单个的生命周期注解本身没有多少意义,因为生命周期注解告诉 Rust 多个引用的泛型生命周期参数如何相互联系的。让我们在 <code>longest</code> 函数的上下文中理解生命周期注解如何相互联系。</p>
<p>例如如果函数有一个生命周期 <code>'a</code><code>i32</code> 的引用的参数 <code>first</code>。还有另一个同样是生命周期 <code>'a</code><code>i32</code> 的引用的参数 <code>second</code>。这两个生命周期注解意味着引用 <code>first</code><code>second</code> 必须与这泛型生命周期存在得一样久。</p>
<h3 id="函数签名中的生命周期注解"><a class="header" href="#函数签名中的生命周期注解">函数签名中的生命周期注解</a></h3>
<p>为了在函数签名中使用生命周期注解,需要在函数名和参数列表间的尖括号中声明泛型生命周期(<em>lifetime</em>)参数,就像泛型类型(<em>type</em>)参数一样。</p>
<p>我们希望函数签名表达如下限制:也就是这两个参数和返回的引用存活的一样久。(两个)参数和返回的引用的生命周期是相关的。就像示例 10-21 中在每个引用中都加上了 <code>'a</code> 那样。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> let string1 = String::from("abcd");
</span><span class="boring"> let string2 = "xyz";
</span><span class="boring">
</span><span class="boring"> let result = longest(string1.as_str(), string2);
</span><span class="boring"> println!("The longest string is {result}");
</span><span class="boring">}
</span><span class="boring">
</span>fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
if x.len() &gt; y.len() {
x
} else {
y
}
}</code></pre></pre>
<p><span class="caption">示例 10-21<code>longest</code> 函数定义指定了签名中所有的引用必须有相同的生命周期 <code>'a</code></span></p>
<p>这段代码能够编译并会产生我们希望得到的示例 10-19 中的 <code>main</code> 函数的结果。</p>
<p>现在函数签名表明对于某些生命周期 <code>'a</code>,函数会获取两个参数,它们都是与生命周期 <code>'a</code> 存在的至少一样长的字符串 slice。函数会返回一个同样也与生命周期 <code>'a</code> 存在的至少一样长的字符串 slice。它的实际含义是 <code>longest</code> 函数返回的引用的生命周期与函数参数所引用的值的生命周期的较小者一致。这些关系就是我们希望 Rust 分析代码时所使用的。</p>
<p>记住通过在函数签名中指定生命周期参数时,我们并没有改变任何传入值或返回值的生命周期,而是指出任何不满足这个约束条件的值都将被借用检查器拒绝。注意 <code>longest</code> 函数并不需要知道 <code>x</code><code>y</code> 具体会存在多久,而只需要知道有某个可以被 <code>'a</code> 替代的作用域将会满足这个签名。</p>
<p>当在函数中使用生命周期注解时,这些注解出现在函数签名中,而不存在于函数体中的任何代码中。生命周期注解成为了函数约定的一部分,非常像签名中的类型。让函数签名包含生命周期约定意味着 Rust 编译器的工作变得更简单了。如果函数注解有误或者调用方法不对编译器错误可以更准确地指出代码和限制的部分。如果不这么做的话Rust 编译会对我们期望的生命周期关系做更多的推断,这样编译器可能只能指出离出问题地方很多步之外的代码。</p>
<p>当具体的引用被传递给 <code>longest</code> 时,被 <code>'a</code> 所替代的具体生命周期是 <code>x</code> 的作用域与 <code>y</code> 的作用域相重叠的那一部分。换一种说法就是泛型生命周期 <code>'a</code> 的具体生命周期等同于 <code>x</code><code>y</code> 的生命周期中较小的那一个。因为我们用相同的生命周期参数 <code>'a</code> 标注了返回的引用值,所以返回的引用值就能保证在 <code>x</code><code>y</code> 中较短的那个生命周期结束之前保持有效。</p>
<p>让我们看看如何通过传递拥有不同具体生命周期的引用来限制 <code>longest</code> 函数的使用。示例 10-22 是一个很直观的例子。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let string1 = String::from("long string is long");
{
let string2 = String::from("xyz");
let result = longest(string1.as_str(), string2.as_str());
println!("The longest string is {result}");
}
}
<span class="boring">
</span><span class="boring">fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
</span><span class="boring"> if x.len() &gt; y.len() {
</span><span class="boring"> x
</span><span class="boring"> } else {
</span><span class="boring"> y
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 10-22通过拥有不同的具体生命周期的 <code>String</code> 值调用 <code>longest</code> 函数</span></p>
<p>在这个例子中,<code>string1</code> 直到外部作用域结束都是有效的,<code>string2</code> 则在内部作用域中是有效的,而 <code>result</code> 则引用了一些直到内部作用域结束都是有效的值。借用检查器认可这些代码;它能够编译和运行,并打印出 <code>The longest string is long string is long</code></p>
<p>接下来,让我们尝试另外一个例子,该例子揭示了 <code>result</code> 的引用的生命周期必须是两个参数中较短的那个。以下代码将 <code>result</code> 变量的声明移动出内部作用域,但是将 <code>result</code><code>string2</code> 变量的赋值语句一同留在内部作用域中。接着,使用了变量 <code>result</code><code>println!</code> 也被移动到内部作用域之外。注意示例 10-23 中的代码不能通过编译:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
}
println!("The longest string is {result}");
}
<span class="boring">
</span><span class="boring">fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
</span><span class="boring"> if x.len() &gt; y.len() {
</span><span class="boring"> x
</span><span class="boring"> } else {
</span><span class="boring"> y
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 10-23尝试在 <code>string2</code> 离开作用域之后使用 <code>result</code> </span></p>
<p>如果尝试编译会出现如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `string2` does not live long enough
--&gt; src/main.rs:6:44
|
5 | let string2 = String::from("xyz");
| ------- binding `string2` declared here
6 | result = longest(string1.as_str(), string2.as_str());
| ^^^^^^^ borrowed value does not live long enough
7 | }
| - `string2` dropped here while still borrowed
8 | println!("The longest string is {result}");
| -------- borrow later used here
For more information about this error, try `rustc --explain E0597`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
</code></pre>
<p>错误表明为了保证 <code>println!</code> 中的 <code>result</code> 是有效的,<code>string2</code> 需要直到外部作用域结束都是有效的。Rust 知道这些是因为(<code>longest</code>)函数的参数和返回值都使用了相同的生命周期参数 <code>'a</code></p>
<p>如果从人的角度读上述代码,我们可能会觉得这个代码是正确的。 <code>string1</code> 更长,因此 <code>result</code> 会包含指向 <code>string1</code> 的引用。因为 <code>string1</code> 尚未离开作用域,对于 <code>println!</code> 来说 <code>string1</code> 的引用仍然是有效的。然而,我们通过生命周期参数告诉 Rust 的是: <code>longest</code> 函数返回的引用的生命周期应该与传入参数的生命周期中较短那个保持一致。因此,借用检查器不允许示例 10-23 中的代码,因为它可能会存在无效的引用。</p>
<p>请尝试更多采用不同的值和不同生命周期的引用作为 <code>longest</code> 函数的参数和返回值的实验。并在开始编译前猜想你的实验能否通过借用检查器,接着编译一下看看你的理解是否正确!</p>
<h3 id="深入理解生命周期"><a class="header" href="#深入理解生命周期">深入理解生命周期</a></h3>
<p>指定生命周期参数的正确方式依赖函数实现的具体功能。例如,如果将 <code>longest</code> 函数的实现修改为总是返回第一个参数而不是最长的字符串 slice就不需要为参数 <code>y</code> 指定一个生命周期。如下代码将能够编译:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> let string1 = String::from("abcd");
</span><span class="boring"> let string2 = "efghijklmnopqrstuvwxyz";
</span><span class="boring">
</span><span class="boring"> let result = longest(string1.as_str(), string2);
</span><span class="boring"> println!("The longest string is {result}");
</span><span class="boring">}
</span><span class="boring">
</span>fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;str) -&gt; &amp;'a str {
x
}</code></pre></pre>
<p>我们为参数 <code>x</code> 和返回值指定了生命周期参数 <code>'a</code>,不过没有为参数 <code>y</code> 指定,因为 <code>y</code> 的生命周期与参数 <code>x</code> 和返回值的生命周期没有任何关系。</p>
<p>当从函数返回一个引用,返回值的生命周期参数需要与一个参数的生命周期参数相匹配。如果返回的引用 <strong>没有</strong> 指向任何一个参数,那么唯一的可能就是它指向一个函数内部创建的值。然而它将会是一个悬垂引用,因为它将会在函数结束时离开作用域。尝试考虑这个并不能编译的 <code>longest</code> 函数实现:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span><span class="boring"> let string1 = String::from("abcd");
</span><span class="boring"> let string2 = "xyz";
</span><span class="boring">
</span><span class="boring"> let result = longest(string1.as_str(), string2);
</span><span class="boring"> println!("The longest string is {result}");
</span><span class="boring">}
</span><span class="boring">
</span>fn longest&lt;'a&gt;(x: &amp;str, y: &amp;str) -&gt; &amp;'a str {
let result = String::from("really long string");
result.as_str()
}</code></pre>
<p>即便我们为返回值指定了生命周期参数 <code>'a</code>,这个实现却编译失败了,因为返回值的生命周期与参数完全没有关联。这里是会出现的错误信息:</p>
<pre><code class="language-console">$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0515]: cannot return value referencing local variable `result`
--&gt; src/main.rs:11:5
|
11 | result.as_str()
| ------^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `result` is borrowed here
For more information about this error, try `rustc --explain E0515`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
</code></pre>
<p>出现的问题是 <code>result</code><code>longest</code> 函数的结尾将离开作用域并被清理,而我们尝试从函数返回一个 <code>result</code> 的引用。无法指定生命周期参数来改变悬垂引用,而且 Rust 也不允许我们创建一个悬垂引用。在这种情况,最好的解决方案是返回一个有所有权的数据类型而不是一个引用,这样函数调用者就需要负责清理这个值了。</p>
<p>综上生命周期语法是用于将函数的多个参数与其返回值的生命周期进行关联的。一旦它们形成了某种关联Rust 就有了足够的信息来允许内存安全的操作并阻止会产生悬垂指针亦或是违反内存安全的行为。</p>
<h3 id="结构体定义中的生命周期注解"><a class="header" href="#结构体定义中的生命周期注解">结构体定义中的生命周期注解</a></h3>
<p>目前为止,我们定义的结构体全都包含拥有所有权的类型。也可以定义包含引用的结构体,不过这需要为结构体定义中的每一个引用添加生命周期注解。示例 10-24 中有一个存放了一个字符串 slice 的结构体 <code>ImportantExcerpt</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct ImportantExcerpt&lt;'a&gt; {
part: &amp;'a str,
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().unwrap();
let i = ImportantExcerpt {
part: first_sentence,
};
}</code></pre></pre>
<p><span class="caption">示例 10-24一个存放引用的结构体所以其定义需要生命周期注解</span></p>
<p>这个结构体有唯一一个字段 <code>part</code>,它存放了一个字符串 slice这是一个引用。类似于泛型参数类型必须在结构体名称后面的尖括号中声明泛型生命周期参数以便在结构体定义中使用生命周期参数。这个注解意味着 <code>ImportantExcerpt</code> 的实例不能比其 <code>part</code> 字段中的引用存在的更久。</p>
<p>这里的 <code>main</code> 函数创建了一个 <code>ImportantExcerpt</code> 的实例,它存放了变量 <code>novel</code> 所拥有的 <code>String</code> 的第一个句子的引用。<code>novel</code> 的数据在 <code>ImportantExcerpt</code> 实例创建之前就存在。另外,直到 <code>ImportantExcerpt</code> 离开作用域之后 <code>novel</code> 都不会离开作用域,所以 <code>ImportantExcerpt</code> 实例中的引用是有效的。</p>
<h3 id="生命周期省略lifetime-elision"><a class="header" href="#生命周期省略lifetime-elision">生命周期省略Lifetime Elision</a></h3>
<p>现在我们已经知道了每一个引用都有一个生命周期,而且我们需要为那些使用了引用的函数或结构体指定生命周期。然而,第四章的示例 4-9 中有一个函数,如示例 10-25 所示,它没有生命周期注解却能编译成功:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn first_word(s: &amp;str) -&gt; &amp;str {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return &amp;s[0..i];
}
}
&amp;s[..]
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let my_string = String::from("hello world");
</span><span class="boring">
</span><span class="boring"> // first_word works on slices of `String`s
</span><span class="boring"> let word = first_word(&amp;my_string[..]);
</span><span class="boring">
</span><span class="boring"> let my_string_literal = "hello world";
</span><span class="boring">
</span><span class="boring"> // first_word works on slices of string literals
</span><span class="boring"> let word = first_word(&amp;my_string_literal[..]);
</span><span class="boring">
</span><span class="boring"> // Because string literals *are* string slices already,
</span><span class="boring"> // this works too, without the slice syntax!
</span><span class="boring"> let word = first_word(my_string_literal);
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 10-25示例 4-9 定义了一个没有使用生命周期注解的函数,即便其参数和返回值都是引用</span></p>
<p>这个函数没有生命周期注解却能编译是由于一些历史原因在早期版本pre-1.0)的 Rust 中,这的确是不能编译的。每一个引用都必须有明确的生命周期。那时的函数签名将会写成这样:</p>
<pre><code class="language-rust ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;'a str {</code></pre>
<p>在编写了很多 Rust 代码后Rust 团队发现在特定情况下 Rust 程序员们总是重复地编写一模一样的生命周期注解。这些场景是可预测的并且遵循几个明确的模式。接着 Rust 团队就把这些模式编码进了 Rust 编译器中,如此借用检查器在这些情况下就能推断出生命周期而不再强制程序员显式的增加注解。</p>
<p>这里我们提到一些 Rust 的历史是因为更多的明确的模式被合并和添加到编译器中是完全可能的。未来只会需要更少的生命周期注解。</p>
<p>被编码进 Rust 引用分析的模式被称为 <strong>生命周期省略规则</strong><em>lifetime elision rules</em>)。这并不是需要程序员遵守的规则;这些规则是一系列特定的场景,此时编译器会考虑,如果代码符合这些场景,就无需明确指定生命周期。</p>
<p>省略规则并不提供完整的推断:如果 Rust 在明确遵守这些规则的前提下变量的生命周期仍然是模棱两可的话,它不会猜测剩余引用的生命周期应该是什么。编译器会在可以通过增加生命周期注解来解决错误问题的地方给出一个错误提示,而不是进行推断或猜测。</p>
<p>函数或方法的参数的生命周期被称为 <strong>输入生命周期</strong><em>input lifetimes</em>),而返回值的生命周期被称为 <strong>输出生命周期</strong><em>output lifetimes</em>)。</p>
<p>编译器采用三条规则来判断引用何时不需要明确的注解。第一条规则适用于输入生命周期,后两条规则适用于输出生命周期。如果编译器检查完这三条规则后仍然存在没有计算出生命周期的引用,编译器将会停止并生成错误。这些规则适用于 <code>fn</code> 定义,以及 <code>impl</code> 块。</p>
<p>第一条规则是编译器为每一个引用参数都分配一个生命周期参数。换句话说就是,函数有一个引用参数的就有一个生命周期参数:<code>fn foo&lt;'a&gt;(x: &amp;'a i32)</code>,有两个引用参数的函数就有两个不同的生命周期参数,<code>fn foo&lt;'a, 'b&gt;(x: &amp;'a i32, y: &amp;'b i32)</code>,依此类推。</p>
<p>第二条规则是如果只有一个输入生命周期参数,那么它被赋予所有输出生命周期参数:<code>fn foo&lt;'a&gt;(x: &amp;'a i32) -&gt; &amp;'a i32</code></p>
<p>第三条规则是如果方法有多个输入生命周期参数并且其中一个参数是 <code>&amp;self</code><code>&amp;mut self</code>,说明是个对象的方法 (method)(译者注:这里涉及 rust 的面向对象参见 17 章),那么所有输出生命周期参数被赋予 <code>self</code> 的生命周期。第三条规则使得方法更容易读写,因为只需更少的符号。</p>
<p>假设我们自己就是编译器。并应用这些规则来计算示例 10-25 中 <code>first_word</code> 函数签名中的引用的生命周期。开始时签名中的引用并没有关联任何生命周期:</p>
<pre><code class="language-rust ignore">fn first_word(s: &amp;str) -&gt; &amp;str {</code></pre>
<p>接着编译器应用第一条规则,也就是每个引用参数都有其自己的生命周期。我们像往常一样称之为 <code>'a</code>,所以现在签名看起来像这样:</p>
<pre><code class="language-rust ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;str {</code></pre>
<p>对于第二条规则,因为这里正好只有一个输入生命周期参数所以是适用的。第二条规则表明输入参数的生命周期将被赋予输出生命周期参数,所以现在签名看起来像这样:</p>
<pre><code class="language-rust ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;'a str {</code></pre>
<p>现在这个函数签名中的所有引用都有了生命周期,如此编译器可以继续它的分析而无须程序员标记这个函数签名中的生命周期。</p>
<p>让我们再看看另一个例子,这次我们从示例 10-20 中没有生命周期参数的 <code>longest</code> 函数开始:</p>
<pre><code class="language-rust ignore">fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {</code></pre>
<p>再次假设我们自己就是编译器并应用第一条规则:每个引用参数都有其自己的生命周期。这次有两个参数,所以就有两个(不同的)生命周期:</p>
<pre><code class="language-rust ignore">fn longest&lt;'a, 'b&gt;(x: &amp;'a str, y: &amp;'b str) -&gt; &amp;str {</code></pre>
<p>再来应用第二条规则,因为函数存在多个输入生命周期,它并不适用于这种情况。再来看第三条规则,它同样也不适用,这是因为没有 <code>self</code> 参数。应用了三个规则之后编译器还没有计算出返回值类型的生命周期。这就是在编译示例 10-20 的代码时会出现错误的原因:编译器使用所有已知的生命周期省略规则,仍不能计算出签名中所有引用的生命周期。</p>
<p>因为第三条规则真正能够适用的就只有方法签名,现在就让我们看看那种情况中的生命周期,并看看为什么这条规则意味着我们经常不需要在方法签名中标注生命周期。</p>
<h3 id="方法定义中的生命周期注解"><a class="header" href="#方法定义中的生命周期注解">方法定义中的生命周期注解</a></h3>
<p>当为带有生命周期的结构体实现方法时,其语法依然类似示例 10-11 中展示的泛型类型参数的语法。我们在哪里声明和使用生命周期参数,取决于它们是与结构体字段相关还是与方法参数和返回值相关。</p>
<p>(实现方法时)结构体字段的生命周期必须总是在 <code>impl</code> 关键字之后声明并在结构体名称之后被使用,因为这些生命周期是结构体类型的一部分。</p>
<p><code>impl</code> 块里的方法签名中,引用可能与结构体字段中的引用相关联,也可能是独立的。另外,生命周期省略规则也经常让我们无需在方法签名中使用生命周期注解。让我们看看一些使用示例 10-24 中定义的结构体 <code>ImportantExcerpt</code> 的例子。</p>
<p>首先,这里有一个方法 <code>level</code>。其唯一的参数是 <code>self</code> 的引用,而且返回值只是一个 <code>i32</code>,并不引用任何值:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct ImportantExcerpt&lt;'a&gt; {
</span><span class="boring"> part: &amp;'a str,
</span><span class="boring">}
</span><span class="boring">
</span>impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn level(&amp;self) -&gt; i32 {
3
}
}
<span class="boring">
</span><span class="boring">impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
</span><span class="boring"> fn announce_and_return_part(&amp;self, announcement: &amp;str) -&gt; &amp;str {
</span><span class="boring"> println!("Attention please: {announcement}");
</span><span class="boring"> self.part
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let novel = String::from("Call me Ishmael. Some years ago...");
</span><span class="boring"> let first_sentence = novel.split('.').next().unwrap();
</span><span class="boring"> let i = ImportantExcerpt {
</span><span class="boring"> part: first_sentence,
</span><span class="boring"> };
</span><span class="boring">}</span></code></pre></pre>
<p><code>impl</code> 之后和类型名称之后的生命周期参数是必要的,不过因为第一条生命周期规则我们并不必须标注 <code>self</code> 引用的生命周期。</p>
<p>这里是一个适用于第三条生命周期省略规则的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct ImportantExcerpt&lt;'a&gt; {
</span><span class="boring"> part: &amp;'a str,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
</span><span class="boring"> fn level(&amp;self) -&gt; i32 {
</span><span class="boring"> 3
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn announce_and_return_part(&amp;self, announcement: &amp;str) -&gt; &amp;str {
println!("Attention please: {announcement}");
self.part
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let novel = String::from("Call me Ishmael. Some years ago...");
</span><span class="boring"> let first_sentence = novel.split('.').next().unwrap();
</span><span class="boring"> let i = ImportantExcerpt {
</span><span class="boring"> part: first_sentence,
</span><span class="boring"> };
</span><span class="boring">}</span></code></pre></pre>
<p>这里有两个输入生命周期,所以 Rust 应用第一条生命周期省略规则并给予 <code>&amp;self</code><code>announcement</code> 它们各自的生命周期。接着,因为其中一个参数是 <code>&amp;self</code>,返回值类型被赋予了 <code>&amp;self</code> 的生命周期,这样所有的生命周期都被计算出来了。</p>
<h3 id="静态生命周期"><a class="header" href="#静态生命周期">静态生命周期</a></h3>
<p>这里有一种特殊的生命周期值得讨论:<code>'static</code>,其生命周期<strong>能够</strong>存活于整个程序期间。所有的字符串字面值都拥有 <code>'static</code> 生命周期,我们也可以选择像下面这样标注出来:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s: &amp;'static str = "I have a static lifetime.";
<span class="boring">}</span></code></pre></pre>
<p>这个字符串的文本被直接储存在程序的二进制文件中而这个文件总是可用的。因此所有的字符串字面值都是 <code>'static</code> 的。</p>
<p>你可能在错误信息的帮助文本中见过使用 <code>'static</code> 生命周期的建议,不过将引用指定为 <code>'static</code> 之前,思考一下这个引用是否真的在整个程序的生命周期里都有效,以及你是否希望它存在得这么久。大部分情况中,推荐 <code>'static</code> 生命周期的错误信息都是尝试创建一个悬垂引用或者可用的生命周期不匹配的结果。在这种情况下的解决方案是修复这些问题而不是指定一个 <code>'static</code> 的生命周期。</p>
<h3 id="结合泛型类型参数trait-bounds-和生命周期"><a class="header" href="#结合泛型类型参数trait-bounds-和生命周期">结合泛型类型参数、trait bounds 和生命周期</a></h3>
<p>让我们简要的看一下在同一函数中指定泛型类型参数、trait bounds 和生命周期的语法!</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> let string1 = String::from("abcd");
</span><span class="boring"> let string2 = "xyz";
</span><span class="boring">
</span><span class="boring"> let result = longest_with_an_announcement(
</span><span class="boring"> string1.as_str(),
</span><span class="boring"> string2,
</span><span class="boring"> "Today is someone's birthday!",
</span><span class="boring"> );
</span><span class="boring"> println!("The longest string is {result}");
</span><span class="boring">}
</span><span class="boring">
</span>use std::fmt::Display;
fn longest_with_an_announcement&lt;'a, T&gt;(
x: &amp;'a str,
y: &amp;'a str,
ann: T,
) -&gt; &amp;'a str
where
T: Display,
{
println!("Announcement! {ann}");
if x.len() &gt; y.len() {
x
} else {
y
}
}</code></pre></pre>
<p>这个是示例 10-21 中那个返回两个字符串 slice 中较长者的 <code>longest</code> 函数,不过带有一个额外的参数 <code>ann</code><code>ann</code> 的类型是泛型 <code>T</code>,它可以被放入任何实现了 <code>where</code> 从句中指定的 <code>Display</code> trait 的类型。这个额外的参数会使用 <code>{}</code> 打印,这也就是为什么 <code>Display</code> trait bound 是必须的。因为生命周期也是泛型,所以生命周期参数 <code>'a</code> 和泛型类型参数 <code>T</code> 都位于函数名后的同一尖括号列表中。</p>
<h2 id="总结-9"><a class="header" href="#总结-9">总结</a></h2>
<p>这一章介绍了很多的内容现在你知道了泛型类型参数、trait 和 trait bounds 以及泛型生命周期类型你已经准备好编写既不重复又能适用于多种场景的代码了。泛型类型参数意味着代码可以适用于不同的类型。trait 和 trait bounds 保证了即使类型是泛型的,这些类型也会拥有所需要的行为。由生命周期注解所指定的引用生命周期之间的关系保证了这些灵活多变的代码不会出现悬垂引用。而所有的这一切发生在编译时所以不会影响运行时效率!</p>
<p>你可能不会相信,这个话题还有更多需要学习的内容:第十八章会讨论 trait 对象,这是另一种使用 trait 的方式。还有更多更复杂的涉及生命周期注解的场景,只有在非常高级的情况下才会需要它们;对于这些内容,请阅读 <a href="https://doc.rust-lang.org/reference/index.html">Rust Reference</a>。不过接下来,让我们聊聊如何在 Rust 中编写测试,来确保代码的所有功能能像我们希望的那样工作!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="编写自动化测试"><a class="header" href="#编写自动化测试">编写自动化测试</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch11-00-testing.md">ch11-00-testing.md</a>
<br>
commit 765318b844569a642ceef7bf1adab9639cbf6af3</p>
</blockquote>
<p>Edsger W. Dijkstra 在其 1972 年的文章【谦卑的程序员】“The Humble Programmer”中说到 “软件测试是证明 bug 存在的有效方法而证明其不存在时则显得令人绝望的不足。”“Program testing can be a very effective way to show the presence of bugs, but it is hopelessly inadequate for showing their absence.”)这并不意味着我们不该尽可能地测试软件!</p>
<p>程序的正确性意味着代码如我们期望的那样运行。Rust 是一个相当注重正确性的编程语言不过正确性是一个难以证明的复杂主题。Rust 的类型系统在此问题上下了很大的功夫不过类型系统不可能捕获所有问题。为此Rust 包含了编写自动化软件测试的功能支持。</p>
<p>假设我们可以编写一个叫做 <code>add_two</code> 的将传递给它的值加二的函数。它的签名有一个整型参数并返回一个整型值。当实现和编译这个函数时Rust 会进行所有目前我们已经见过的类型检查和借用检查,例如,这些检查会确保我们不会传递 <code>String</code> 或无效的引用给这个函数。Rust 所 <strong>不能</strong> 检查的是这个函数是否会准确的完成我们期望的工作:返回参数加二后的值,而不是比如说参数加 10 或减 50 的值!这也就是测试出场的地方。</p>
<p>我们可以编写测试断言,比如说,当传递 <code>3</code><code>add_two</code> 函数时,返回值是 <code>5</code>。无论何时对代码进行修改,都可以运行测试来确保任何现存的正确行为没有被改变。</p>
<p>测试是一项复杂的技能:虽然不能在一个章节的篇幅中介绍如何编写好的测试的每个细节,但我们还是会讨论 Rust 测试功能的机制。我们会讲到编写测试时会用到的注解和宏,运行测试的默认行为和选项,以及如何将测试组织成单元测试和集成测试。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="如何编写测试"><a class="header" href="#如何编写测试">如何编写测试</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch11-01-writing-tests.md">ch11-01-writing-tests.md</a>
<br>
commit 6e2fe7c0f085989cc498cec139e717e2af172cb7</p>
</blockquote>
<p>Rust 中的测试函数是用来验证非测试代码是否是按照期望的方式运行的。测试函数体通常执行如下三种操作:</p>
<ol>
<li>设置任何所需的数据或状态</li>
<li>运行需要测试的代码</li>
<li>断言其结果是我们所期望的</li>
</ol>
<p>让我们看看 Rust 提供的专门用来编写测试的功能:<code>test</code> 属性、一些宏和 <code>should_panic</code> 属性。</p>
<h3 id="测试函数剖析"><a class="header" href="#测试函数剖析">测试函数剖析</a></h3>
<p>作为最简单例子Rust 中的测试就是一个带有 <code>test</code> 属性注解的函数。属性attribute是关于 Rust 代码片段的元数据;第五章中结构体中用到的 <code>derive</code> 属性就是一个例子。为了将一个函数变成测试函数,需要在 <code>fn</code> 行之前加上 <code>#[test]</code>。当使用 <code>cargo test</code> 命令运行测试时Rust 会构建一个测试执行程序用来调用被标注的函数,并报告每一个测试是通过还是失败。</p>
<p>每次使用 Cargo 新建一个库项目时,它会自动为我们生成一个测试模块和一个测试函数。这个模块提供了一个编写测试的模板,为此每次开始新项目时不必去查找测试函数的具体结构和语法了。因为这样当然你也可以额外增加任意多的测试函数以及测试模块!</p>
<p>在实际编写测试代码之前,让我们先通过尝试那些自动生成的测试模版来探索测试是如何工作的。接着,我们会写一些真正的测试,调用我们编写的代码并断言它们的行为的正确性。</p>
<p>让我们创建一个新的库项目 <code>adder</code>,它会将两个数字相加:</p>
<pre><code class="language-console">$ cargo new adder --lib
Created library `adder` project
$ cd adder
</code></pre>
<p>adder 库中 <code>src/lib.rs</code> 的内容应该看起来如示例 11-1 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add(left: usize, right: usize) -&gt; usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}</code></pre>
<p><span class="caption">示例 11-1<code>cargo new</code> 自动生成的测试模块和函数</span></p>
<p>现在让我们暂时忽略 <code>tests</code> 模块和 <code>#[cfg(test)]</code> 注解并只关注函数本身。注意 <code>fn</code> 行之前的 <code>#[test]</code>:这个属性表明这是一个测试函数,这样测试执行者就知道将其作为测试处理。<code>tests</code> 模块中也可以有非测试的函数来帮助我们建立通用场景或进行常见操作,必须每次都标明哪些函数是测试。</p>
<p>示例函数体通过使用 <code>assert_eq!</code> 宏来断言 2 加 2 等于 4。一个典型的测试的格式就是像这个例子中的断言一样。接下来运行就可以看到测试通过。</p>
<p><code>cargo test</code> 命令会运行项目中所有的测试,如示例 11-2 所示:</p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.57s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p><span class="caption">示例 11-2运行自动生成测试的输出</span></p>
<p>Cargo 编译并运行了测试。可以看到 <code>running 1 test</code> 这一行。下一行显示了生成的测试函数的名称,它是 <code>it_works</code>,以及测试的运行结果,<code>ok</code>。接着可以看到全体测试运行结果的摘要:<code>test result: ok.</code> 意味着所有测试都通过了。<code>1 passed; 0 failed</code> 表示通过或失败的测试数量。</p>
<p>可以将一个测试标记为忽略这样在特定情况下它就不会运行;本章之后的<a href="ch11-02-running-tests.html#%E9%99%A4%E9%9D%9E%E7%89%B9%E5%88%AB%E6%8C%87%E5%AE%9A%E5%90%A6%E5%88%99%E5%BF%BD%E7%95%A5%E6%9F%90%E4%BA%9B%E6%B5%8B%E8%AF%95">“除非特别指定否则忽略某些测试”</a>部分会介绍它。因为之前我们并没有将任何测试标记为忽略,所以摘要中会显示 <code>0 ignored</code>。我们也没有过滤需要运行的测试,所以摘要中会显示<code>0 filtered out</code>。在下一部分 <a href="ch11-02-running-tests.html#%E6%8E%A7%E5%88%B6%E6%B5%8B%E8%AF%95%E5%A6%82%E4%BD%95%E8%BF%90%E8%A1%8C">“控制测试如何运行”</a> 会讨论忽略和过滤测试。</p>
<p><code>0 measured</code> 统计是针对性能测试的。性能测试benchmark tests在编写本书时仍只能用于 Rust 开发版nightly Rust。请查看 <a href="https://doc.rust-lang.org/unstable-book/library-features/test.html">性能测试的文档</a> 了解更多。</p>
<p>测试输出中的以 <code>Doc-tests adder</code> 开头的这一部分是所有文档测试的结果。我们现在并没有任何文档测试,不过 Rust 会编译任何在 API 文档中的代码示例。这个功能帮助我们使文档和代码保持同步!在第十四章的 <a href="ch14-02-publishing-to-crates-io.html#%E6%96%87%E6%A1%A3%E6%B3%A8%E9%87%8A%E4%BD%9C%E4%B8%BA%E6%B5%8B%E8%AF%95">“文档注释作为测试”</a> 部分会讲到如何编写文档测试。现在我们将忽略 <code>Doc-tests</code> 部分的输出。</p>
<p>让我们开始自定义测试来满足我们的需求。首先给 <code>it_works</code> 函数起个不同的名字,比如 <code>exploration</code>,像这样:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add(left: usize, right: usize) -&gt; usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exploration() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}</code></pre>
<p>并再次运行 <code>cargo test</code>。现在输出中将出现 <code>exploration</code> 而不是 <code>it_works</code></p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.59s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::exploration ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>现在让我们增加另一个测试,不过这一次是一个会失败的测试!当测试函数中出现 panic 时测试就失败了。每一个测试都在一个新线程中运行,当主线程发现测试线程异常了,就将对应测试标记为失败。第九章讲到了最简单的造成 panic 的方法:调用 <code>panic!</code> 宏。写入新测试 <code>another</code> 后, <code>src/lib.rs</code> 现在看起来如示例 11-3 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust panics noplayground"><span class="boring">pub fn add(left: usize, right: usize) -&gt; usize {
</span><span class="boring"> left + right
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn exploration() {
</span><span class="boring"> let result = add(2, 2);
</span><span class="boring"> assert_eq!(result, 4);
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn another() {
</span><span class="boring"> panic!("Make this test fail");
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 11-3增加第二个因调用了 <code>panic!</code> 而失败的测试</span></p>
<p>再次 <code>cargo test</code> 运行测试。输出应该看起来像示例 11-4它表明 <code>exploration</code> 测试通过了而 <code>another</code> 失败了:</p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.72s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 2 tests
test tests::another ... FAILED
test tests::exploration ... ok
failures:
---- tests::another stdout ----
thread 'tests::another' panicked at src/lib.rs:17:9:
Make this test fail
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::another
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p><span class="caption">示例 11-4一个测试通过和一个测试失败的测试结果</span></p>
<p><code>test tests::another</code> 这一行是 <code>FAILED</code> 而不是 <code>ok</code> 了。在单独测试结果和摘要之间多了两个新的部分:第一个部分显示了测试失败的详细原因。在这个例子中,我们看到 <code>another</code> 因为在 <em>src/lib.rs</em> 的第 10 行 <code>panicked at 'Make this test fail'</code> 而失败的详细信息。下一部分列出了所有失败的测试,这在有很多测试和很多失败测试的详细输出时很有帮助。我们可以通过使用失败测试的名称来只运行这个测试,以便调试;下一部分 <a href="ch11-02-running-tests.html#%E6%8E%A7%E5%88%B6%E6%B5%8B%E8%AF%95%E5%A6%82%E4%BD%95%E8%BF%90%E8%A1%8C">“控制测试如何运行”</a> 会讲到更多运行测试的方法。</p>
<p>最后是摘要行:总体上讲,测试结果是 <code>FAILED</code>。有一个测试通过和一个测试失败。</p>
<p>现在我们见过不同场景中测试结果是什么样子的了,再来看看除 <code>panic!</code> 之外的一些在测试中有帮助的宏吧。</p>
<h3 id="使用-assert-宏来检查结果"><a class="header" href="#使用-assert-宏来检查结果">使用 <code>assert!</code> 宏来检查结果</a></h3>
<p><code>assert!</code> 宏由标准库提供,在希望确保测试中一些条件为 <code>true</code> 时非常有用。需要向 <code>assert!</code> 宏提供一个求值为布尔值的参数。如果值是 <code>true</code><code>assert!</code> 什么也不做,同时测试会通过。如果值为 <code>false</code><code>assert!</code> 调用 <code>panic!</code> 宏,这会导致测试失败。<code>assert!</code> 宏帮助我们检查代码是否以期望的方式运行。</p>
<p>回忆一下第五章中,示例 5-15 中有一个 <code>Rectangle</code> 结构体和一个 <code>can_hold</code> 方法,在示例 11-5 中再次使用它们。将它们放进 <em>src/lib.rs</em> 并使用 <code>assert!</code> 宏编写一些测试。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Rectangle {
</span><span class="boring"> fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
</span><span class="boring"> self.width &gt; other.width &amp;&amp; self.height &gt; other.height
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 11-5第五章中 <code>Rectangle</code> 结构体和其 <code>can_hold</code> 方法</span></p>
<p><code>can_hold</code> 方法返回一个布尔值,这意味着它完美符合 <code>assert!</code> 宏的使用场景。在示例 11-6 中,让我们编写一个 <code>can_hold</code> 方法的测试来作为练习,这里创建一个长为 8 宽为 7 的 <code>Rectangle</code> 实例,并假设它可以放得下另一个长为 5 宽为 1 的 <code>Rectangle</code> 实例:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Rectangle {
</span><span class="boring"> fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
</span><span class="boring"> self.width &gt; other.width &amp;&amp; self.height &gt; other.height
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_can_hold_smaller() {
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};
assert!(larger.can_hold(&amp;smaller));
}
}</code></pre>
<p><span class="caption">示例 11-6一个 <code>can_hold</code> 的测试,检查一个较大的矩形确实能放得下一个较小的矩形</span></p>
<p>注意在 <code>tests</code> 模块中新增加了一行:<code>use super::*;</code><code>tests</code> 是一个普通的模块,它遵循第七章 <a href="ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html">“路径用于引用模块树中的项”</a> 部分介绍的可见性规则。因为这是一个内部模块,要测试外部模块中的代码,需要将其引入到内部模块的作用域中。这里选择使用 glob 全局导入,以便在 <code>tests</code> 模块中使用所有在外部模块定义的内容。</p>
<p>我们将测试命名为 <code>larger_can_hold_smaller</code>,并创建所需的两个 <code>Rectangle</code> 实例。接着调用 <code>assert!</code> 宏并传递 <code>larger.can_hold(&amp;smaller)</code> 调用的结果作为参数。这个表达式预期会返回 <code>true</code>,所以测试应该通过。让我们拭目以待!</p>
<pre><code class="language-console">$ cargo test
Compiling rectangle v0.1.0 (file:///projects/rectangle)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66s
Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)
running 1 test
test tests::larger_can_hold_smaller ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests rectangle
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>它确实通过了!再来增加另一个测试,这一回断言一个更小的矩形不能放下一个更大的矩形:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Rectangle {
</span><span class="boring"> fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
</span><span class="boring"> self.width &gt; other.width &amp;&amp; self.height &gt; other.height
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_can_hold_smaller() {
// --snip--
<span class="boring"> let larger = Rectangle {
</span><span class="boring"> width: 8,
</span><span class="boring"> height: 7,
</span><span class="boring"> };
</span><span class="boring"> let smaller = Rectangle {
</span><span class="boring"> width: 5,
</span><span class="boring"> height: 1,
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> assert!(larger.can_hold(&amp;smaller));
</span> }
#[test]
fn smaller_cannot_hold_larger() {
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};
assert!(!smaller.can_hold(&amp;larger));
}
}</code></pre>
<p>因为这里 <code>can_hold</code> 函数的正确结果是 <code>false</code> ,我们需要将这个结果取反后传递给 <code>assert!</code> 宏。因此 <code>can_hold</code> 返回 <code>false</code> 时测试就会通过:</p>
<pre><code class="language-console">$ cargo test
Compiling rectangle v0.1.0 (file:///projects/rectangle)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66s
Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)
running 2 tests
test tests::larger_can_hold_smaller ... ok
test tests::smaller_cannot_hold_larger ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests rectangle
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>两个通过的测试!现在让我们看看如果引入一个 bug 的话测试结果会发生什么。将 <code>can_hold</code> 方法中比较长度时本应使用大于号的地方改成小于号:</p>
<pre><code class="language-rust not_desired_behavior noplayground"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>// --snip--
impl Rectangle {
fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.width &lt; other.width &amp;&amp; self.height &gt; other.height
}
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn larger_can_hold_smaller() {
</span><span class="boring"> let larger = Rectangle {
</span><span class="boring"> width: 8,
</span><span class="boring"> height: 7,
</span><span class="boring"> };
</span><span class="boring"> let smaller = Rectangle {
</span><span class="boring"> width: 5,
</span><span class="boring"> height: 1,
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> assert!(larger.can_hold(&amp;smaller));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn smaller_cannot_hold_larger() {
</span><span class="boring"> let larger = Rectangle {
</span><span class="boring"> width: 8,
</span><span class="boring"> height: 7,
</span><span class="boring"> };
</span><span class="boring"> let smaller = Rectangle {
</span><span class="boring"> width: 5,
</span><span class="boring"> height: 1,
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> assert!(!smaller.can_hold(&amp;larger));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>现在运行测试会产生:</p>
<pre><code class="language-console">$ cargo test
Compiling rectangle v0.1.0 (file:///projects/rectangle)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66s
Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)
running 2 tests
test tests::larger_can_hold_smaller ... FAILED
test tests::smaller_cannot_hold_larger ... ok
failures:
---- tests::larger_can_hold_smaller stdout ----
thread 'tests::larger_can_hold_smaller' panicked at src/lib.rs:28:9:
assertion failed: larger.can_hold(&amp;smaller)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::larger_can_hold_smaller
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>我们的测试捕获了 bug因为 <code>larger.length</code> 是 8 而 <code>smaller.length</code> 是 5<code>can_hold</code> 中的长度比较现在因为 8 不小于 5 而返回 <code>false</code></p>
<h3 id="使用-assert_eq-和-assert_ne-宏来测试相等"><a class="header" href="#使用-assert_eq-和-assert_ne-宏来测试相等">使用 <code>assert_eq!</code><code>assert_ne!</code> 宏来测试相等</a></h3>
<p>测试功能的一个常用方法是将需要测试代码的值与期望值做比较,并检查是否相等。可以通过向 <code>assert!</code> 宏传递一个使用 <code>==</code> 运算符的表达式来做到。不过这个操作实在是太常见了,以至于标准库提供了一对宏来更方便的处理这些操作 —— <code>assert_eq!</code><code>assert_ne!</code>。这两个宏分别比较两个值是相等还是不相等。当断言失败时它们也会打印出这两个值具体是什么,以便于观察测试 <strong>为什么</strong> 失败,而 <code>assert!</code> 只会打印出它从 <code>==</code> 表达式中得到了 <code>false</code> 值,而不是打印导致 <code>false</code> 的两个值。</p>
<p>示例 11-7 中,让我们编写一个对其参数加二并返回结果的函数 <code>add_two</code>。接着使用 <code>assert_eq!</code> 宏测试这个函数。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add_two(a: usize) -&gt; usize {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_adds_two() {
let result = add_two(2);
assert_eq!(result, 4);
}
}</code></pre>
<p><span class="caption">示例 11-7使用 <code>assert_eq!</code> 宏测试 <code>add_two</code> 函数</span></p>
<p>测试通过了!</p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>我们传递给 <code>assert_eq!</code> 宏的第一个参数 <code>4</code> ,它等于调用 <code>add_two(2)</code> 的结果。测试中的这一行 <code>test tests::it_adds_two ... ok</code><code>ok</code> 表明测试通过!</p>
<p>在代码中引入一个 bug 来看看使用 <code>assert_eq!</code> 的测试失败是什么样的。修改 <code>add_two</code> 函数的实现使其加 <code>3</code></p>
<pre><code class="language-rust not_desired_behavior noplayground">pub fn add_two(a: usize) -&gt; usize {
a + 3
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn it_adds_two() {
</span><span class="boring"> let result = add_two(2);
</span><span class="boring"> assert_eq!(result, 4);
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>再次运行测试:</p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.61s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::it_adds_two ... FAILED
failures:
---- tests::it_adds_two stdout ----
thread 'tests::it_adds_two' panicked at src/lib.rs:12:9:
assertion `left == right` failed
left: 5
right: 4
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::it_adds_two
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>测试捕获到了 bug<code>it_adds_two</code> 测试失败,错误信息告诉我们断言失败了,它告诉我们 <code>assertion failed: `(left == right)`</code> 以及 <code>left</code><code>right</code> 的值是什么。这个错误信息有助于我们开始调试:它说 <code>assert_eq!</code><code>left</code> 参数是 <code>4</code>,而 <code>right</code> 参数,也就是 <code>add_two(2)</code> 的结果,是 <code>5</code>。可以想象当有很多测试在运行时这些信息是多么的有用。</p>
<p>需要注意的是,在一些语言和测试框架中,断言两个值相等的函数的参数被称为 <code>expected</code><code>actual</code>,而且指定参数的顺序非常重要。然而在 Rust 中,它们则叫做 <code>left</code><code>right</code>,同时指定期望的值和被测试代码产生的值的顺序并不重要。这个测试中的断言也可以写成 <code>assert_eq!(add_two(2), 4)</code>,这时失败信息仍同样是 <code>assertion failed: `(left == right)`</code></p>
<p><code>assert_ne!</code> 宏在传递给它的两个值不相等时通过,而在相等时失败。在代码按预期运行,我们不确定值 <strong></strong> 是什么,不过能确定值绝对 <strong>不会</strong> 是什么的时候,这个宏最有用处。例如,如果一个函数保证会以某种方式改变其输出,不过这种改变方式是由运行测试时是星期几来决定的,这时最好的断言可能就是函数的输出不等于其输入。</p>
<p><code>assert_eq!</code><code>assert_ne!</code> 宏在底层分别使用了 <code>==</code><code>!=</code>。当断言失败时,这些宏会使用调试格式打印出其参数,这意味着被比较的值必须实现了 <code>PartialEq</code><code>Debug</code> trait。所有的基本类型和大部分标准库类型都实现了这些 trait。对于自定义的结构体和枚举需要实现 <code>PartialEq</code> 才能断言它们的值是否相等。需要实现 <code>Debug</code> 才能在断言失败时打印它们的值。因为这两个 trait 都是派生 trait如第五章示例 5-12 所提到的,通常可以直接在结构体或枚举上添加 <code>#[derive(PartialEq, Debug)]</code> 注解。附录 C <a href="appendix-03-derivable-traits.html">“可派生 trait”</a> 中有更多关于这些和其他派生 trait 的详细信息。</p>
<h3 id="自定义失败信息"><a class="header" href="#自定义失败信息">自定义失败信息</a></h3>
<p>你也可以向 <code>assert!</code><code>assert_eq!</code><code>assert_ne!</code> 宏传递一个可选的失败信息参数,可以在测试失败时将自定义失败信息一同打印出来。任何在 <code>assert!</code> 的一个必需参数和 <code>assert_eq!</code><code>assert_ne!</code> 的两个必需参数之后指定的参数都会传递给 <code>format!</code> 宏(在第八章的 <a href="ch08-02-strings.html#%E4%BD%BF%E7%94%A8--%E8%BF%90%E7%AE%97%E7%AC%A6%E6%88%96-format-%E5%AE%8F%E6%8B%BC%E6%8E%A5%E5%AD%97%E7%AC%A6%E4%B8%B2">“使用 <code>+</code> 运算符或 <code>format!</code> 宏拼接字符串”</a> 部分讨论过),所以可以传递一个包含 <code>{}</code> 占位符的格式字符串和需要放入占位符的值。自定义信息有助于记录断言的意义;当测试失败时就能更好的理解代码出了什么问题。</p>
<p>例如,比如说有一个根据人名进行问候的函数,而我们希望测试将传递给函数的人名显示在输出中:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn greeting(name: &amp;str) -&gt; String {
format!("Hello {name}!")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn greeting_contains_name() {
let result = greeting("Carol");
assert!(result.contains("Carol"));
}
}</code></pre>
<p>这个程序的需求还没有被确定,因此问候文本开头的 <code>Hello</code> 文本很可能会改变。然而我们并不想在需求改变时不得不更新测试,所以相比检查 <code>greeting</code> 函数返回的确切值,我们将仅仅断言输出的文本中包含输入参数。</p>
<p>让我们通过将 <code>greeting</code> 改为不包含 <code>name</code> 在代码中引入一个 bug 来测试失败时是怎样的:</p>
<pre><code class="language-rust not_desired_behavior noplayground">pub fn greeting(name: &amp;str) -&gt; String {
String::from("Hello!")
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn greeting_contains_name() {
</span><span class="boring"> let result = greeting("Carol");
</span><span class="boring"> assert!(result.contains("Carol"));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>运行测试会产生:</p>
<pre><code class="language-console">$ cargo test
Compiling greeter v0.1.0 (file:///projects/greeter)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.91s
Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)
running 1 test
test tests::greeting_contains_name ... FAILED
failures:
---- tests::greeting_contains_name stdout ----
thread 'tests::greeting_contains_name' panicked at src/lib.rs:12:9:
assertion failed: result.contains("Carol")
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::greeting_contains_name
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>结果仅仅告诉了我们断言失败了和失败的行号。一个更有用的失败信息应该打印出 <code>greeting</code> 函数的值。让我们为测试函数增加一个自定义失败信息参数:带占位符的格式字符串,以及 <code>greeting</code> 函数的值:</p>
<pre><code class="language-rust ignore"><span class="boring">pub fn greeting(name: &amp;str) -&gt; String {
</span><span class="boring"> String::from("Hello!")
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span> #[test]
fn greeting_contains_name() {
let result = greeting("Carol");
assert!(
result.contains("Carol"),
"Greeting did not contain name, value was `{result}`"
);
}
<span class="boring">}</span></code></pre>
<p>现在如果再次运行测试,将会看到更有价值的信息:</p>
<pre><code class="language-console">$ cargo test
Compiling greeter v0.1.0 (file:///projects/greeter)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.93s
Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)
running 1 test
test tests::greeting_contains_name ... FAILED
failures:
---- tests::greeting_contains_name stdout ----
thread 'tests::greeting_contains_name' panicked at src/lib.rs:12:9:
Greeting did not contain name, value was `Hello!`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::greeting_contains_name
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>可以在测试输出中看到所取得的确切的值,这会帮助我们理解真正发生了什么,而不是期望发生什么。</p>
<h3 id="使用-should_panic-检查-panic"><a class="header" href="#使用-should_panic-检查-panic">使用 <code>should_panic</code> 检查 panic</a></h3>
<p>除了检查返回值之外,检查代码是否按照期望处理错误也是很重要的。例如,考虑第九章示例 9-10 创建的 <code>Guess</code> 类型。其他使用 <code>Guess</code> 的代码都是基于 <code>Guess</code> 实例仅有的值范围在 1 到 100 的前提。可以编写一个测试来确保创建一个超出范围的值的 <code>Guess</code> 实例会 panic。</p>
<p>可以通过对函数增加另一个属性 <code>should_panic</code> 来实现这些。这个属性在函数中的代码 panic 时会通过,而在其中的代码没有 panic 时失败。</p>
<p>示例 11-8 展示了一个检查 <code>Guess::new</code> 是否按照我们的期望出错的测试:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -&gt; Guess {
if value &lt; 1 || value &gt; 100 {
panic!("Guess value must be between 1 and 100, got {value}.");
}
Guess { value }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn greater_than_100() {
Guess::new(200);
}
}</code></pre>
<p><span class="caption">示例 11-8测试会造成 <code>panic!</code> 的条件</span></p>
<p><code>#[should_panic]</code> 属性位于 <code>#[test]</code> 之后,对应的测试函数之前。让我们看看测试通过时它是什么样子:</p>
<pre><code class="language-console">$ cargo test
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58s
Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)
running 1 test
test tests::greater_than_100 - should panic ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests guessing_game
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>看起来不错!现在在代码中引入 bug移除 <code>new</code> 函数在值大于 100 时会 panic 的条件:</p>
<pre><code class="language-rust not_desired_behavior noplayground"><span class="boring">pub struct Guess {
</span><span class="boring"> value: i32,
</span><span class="boring">}
</span><span class="boring">
</span>// --snip--
impl Guess {
pub fn new(value: i32) -&gt; Guess {
if value &lt; 1 {
panic!("Guess value must be between 1 and 100, got {value}.");
}
Guess { value }
}
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> #[should_panic]
</span><span class="boring"> fn greater_than_100() {
</span><span class="boring"> Guess::new(200);
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>如果运行示例 11-8 的测试,它会失败:</p>
<pre><code class="language-console">$ cargo test
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.62s
Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)
running 1 test
test tests::greater_than_100 - should panic ... FAILED
failures:
---- tests::greater_than_100 stdout ----
note: test did not panic as expected
failures:
tests::greater_than_100
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>这回并没有得到非常有用的信息,不过一旦我们观察测试函数,会发现它标注了 <code>#[should_panic]</code>。这个错误意味着代码中测试函数 <code>Guess::new(200)</code> 并没有产生 panic。</p>
<p>然而 <code>should_panic</code> 测试结果可能会非常含糊不清。<code>should_panic</code> 甚至在一些不是我们期望的原因而导致 panic 时也会通过。为了使 <code>should_panic</code> 测试结果更精确,我们可以给 <code>should_panic</code> 属性增加一个可选的 <code>expected</code> 参数。测试工具会确保错误信息中包含其提供的文本。例如,考虑示例 11-9 中修改过的 <code>Guess</code>,这里 <code>new</code> 函数根据其值是过大还或者过小而提供不同的 panic 信息:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct Guess {
</span><span class="boring"> value: i32,
</span><span class="boring">}
</span><span class="boring">
</span>// --snip--
impl Guess {
pub fn new(value: i32) -&gt; Guess {
if value &lt; 1 {
panic!(
"Guess value must be greater than or equal to 1, got {value}."
);
} else if value &gt; 100 {
panic!(
"Guess value must be less than or equal to 100, got {value}."
);
}
Guess { value }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "less than or equal to 100")]
fn greater_than_100() {
Guess::new(200);
}
}</code></pre>
<p><span class="caption">示例 11-9一个会带有特定错误信息的 <code>panic!</code> 条件的测试</span></p>
<p>这个测试会通过,因为 <code>should_panic</code> 属性中 <code>expected</code> 参数提供的值是 <code>Guess::new</code> 函数 panic 信息的子串。我们可以指定期望的整个 panic 信息,在这个例子中是 <code>Guess value must be less than or equal to 100, got 200.</code><code>expected</code> 信息的选择取决于 panic 信息有多独特或动态,和你希望测试有多准确。在这个例子中,错误信息的子字符串足以确保函数在 <code>else if value &gt; 100</code> 的情况下运行。</p>
<p>为了观察带有 <code>expected</code> 信息的 <code>should_panic</code> 测试失败时会发生什么,让我们再次引入一个 bug<code>if value &lt; 1</code><code>else if value &gt; 100</code> 的代码块对换:</p>
<pre><code class="language-rust ignore not_desired_behavior"><span class="boring">pub struct Guess {
</span><span class="boring"> value: i32,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Guess {
</span><span class="boring"> pub fn new(value: i32) -&gt; Guess {
</span> if value &lt; 1 {
panic!(
"Guess value must be less than or equal to 100, got {value}."
);
} else if value &gt; 100 {
panic!(
"Guess value must be greater than or equal to 1, got {value}."
);
}
<span class="boring">
</span><span class="boring"> Guess { value }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> #[should_panic(expected = "less than or equal to 100")]
</span><span class="boring"> fn greater_than_100() {
</span><span class="boring"> Guess::new(200);
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>这一次运行 <code>should_panic</code> 测试,它会失败:</p>
<pre><code class="language-console">$ cargo test
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66s
Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)
running 1 test
test tests::greater_than_100 - should panic ... FAILED
failures:
---- tests::greater_than_100 stdout ----
thread 'tests::greater_than_100' panicked at src/lib.rs:12:13:
Guess value must be greater than or equal to 1, got 200.
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
note: panic did not contain expected string
panic message: `"Guess value must be greater than or equal to 1, got 200."`,
expected substring: `"less than or equal to 100"`
failures:
tests::greater_than_100
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>失败信息表明测试确实如期望 panic 了,不过 panic 信息中并没有包含 <code>expected</code> 信息 <code>'Guess value must be less than or equal to 100'</code>。而我们得到的 panic 信息是 <code>'Guess value must be greater than or equal to 1, got 200.'</code>。这样就可以开始寻找 bug 在哪了!</p>
<h3 id="将-resultt-e-用于测试"><a class="header" href="#将-resultt-e-用于测试"><code>Result&lt;T, E&gt;</code> 用于测试</a></h3>
<p>目前为止,我们编写的测试在失败时都会 panic。我们也可以使用 <code>Result&lt;T, E&gt;</code> 编写测试!这是一个延伸自示例 11-1 的测试,使用 <code>Result&lt;T, E&gt;</code> 重写,并在失败时返回 <code>Err</code> 而非 panic</p>
<pre><code class="language-rust noplayground">pub fn add(left: usize, right: usize) -&gt; usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
// ANCHOR: here
#[test]
fn it_works() -&gt; Result&lt;(), String&gt; {
let result = add(2, 2);
if result == 4 {
Ok(())
} else {
Err(String::from("two plus two does not equal four"))
}
}
// ANCHOR_END: here
}</code></pre>
<p>现在 <code>it_works</code> 函数的返回值类型为 <code>Result&lt;(), String&gt;</code>。在函数体中,不同于调用 <code>assert_eq!</code> 宏,而是在测试通过时返回 <code>Ok(())</code>,在测试失败时返回带有 <code>String</code><code>Err</code></p>
<p>这样编写测试来返回 <code>Result&lt;T, E&gt;</code> 就可以在函数体中使用问号运算符,如此可以方便的编写任何运算符会返回 <code>Err</code> 成员的测试。</p>
<p>不能对这些使用 <code>Result&lt;T, E&gt;</code> 的测试使用 <code>#[should_panic]</code> 注解。为了断言一个操作返回 <code>Err</code> 成员,<strong>不要</strong>使用对 <code>Result&lt;T, E&gt;</code> 值使用问号表达式(<code>?</code>)。而是使用 <code>assert!(value.is_err())</code></p>
<p>现在你知道了几种编写测试的方法,让我们看看运行测试时会发生什么,以及可以用于 <code>cargo test</code> 的不同选项。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="控制测试如何运行"><a class="header" href="#控制测试如何运行">控制测试如何运行</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch11-02-running-tests.md">ch11-02-running-tests.md</a>
<br>
commit 34314c10f699cc882d4e0b06f2a24bd37a5435f2</p>
</blockquote>
<p>就像 <code>cargo run</code> 会编译代码并运行生成的二进制文件一样,<code>cargo test</code> 在测试模式下编译代码并运行生成的测试二进制文件。<code>cargo test</code> 产生的二进制文件的默认行为是并发运行所有的测试,并截获测试运行过程中产生的输出,阻止它们被显示出来,使得阅读测试结果相关的内容变得更容易。不过可以指定命令行参数来改变 <code>cargo test</code> 的默认行为。</p>
<p>可以将一部分命令行参数传递给 <code>cargo test</code>,而将另外一部分传递给生成的测试二进制文件。为了分隔这两种参数,需要先列出传递给 <code>cargo test</code> 的参数,接着是分隔符 <code>--</code>,再之后是传递给测试二进制文件的参数。运行 <code>cargo test --help</code> 会提示 <code>cargo test</code> 的有关参数,而运行 <code>cargo test -- --help</code> 可以提示在分隔符之后使用的有关参数。</p>
<h3 id="并行或连续的运行测试"><a class="header" href="#并行或连续的运行测试">并行或连续的运行测试</a></h3>
<p>当运行多个测试时Rust 默认使用线程来并行运行。这意味着测试会更快地运行完毕,所以你可以更快的得到代码能否工作的反馈。因为测试是在同时运行的,你应该确保测试不能相互依赖,或依赖任何共享的状态,包括依赖共享的环境,比如当前工作目录或者环境变量。</p>
<p>举个例子,每一个测试都运行一些代码,假设这些代码都在硬盘上创建一个 <em>test-output.txt</em> 文件并写入一些数据。接着每一个测试都读取文件中的数据并断言这个文件包含特定的值,而这个值在每个测试中都是不同的。因为所有测试都是同时运行的,一个测试可能会在另一个测试读写文件过程中修改了文件。那么第二个测试就会失败,并不是因为代码不正确,而是因为测试并行运行时相互干扰。一个解决方案是使每一个测试读写不同的文件;另一个解决方案是一次运行一个测试。</p>
<p>如果你不希望测试并行运行,或者想要更加精确的控制线程的数量,可以传递 <code>--test-threads</code> 参数和希望使用线程的数量给测试二进制文件。例如:</p>
<pre><code class="language-console">$ cargo test -- --test-threads=1
</code></pre>
<p>这里将测试线程设置为 <code>1</code>,告诉程序不要使用任何并行机制。这也会比并行运行花费更多时间,不过在有共享的状态时,测试就不会潜在的相互干扰了。</p>
<h3 id="显示函数输出"><a class="header" href="#显示函数输出">显示函数输出</a></h3>
<p>默认情况下当测试通过时Rust 的测试库会截获打印到标准输出的所有内容。比如在测试中调用了 <code>println!</code> 而测试通过了,我们将不会在终端看到 <code>println!</code> 的输出:只会看到说明测试通过的提示行。如果测试失败了,则会看到所有标准输出和其他错误信息。</p>
<p>例如,示例 11-10 有一个无意义的函数,它打印出其参数的值并接着返回 10。接着还有一个会通过的测试和一个会失败的测试</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust panics noplayground">fn prints_and_returns_10(a: i32) -&gt; i32 {
println!("I got the value {a}");
10
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn this_test_will_pass() {
let value = prints_and_returns_10(4);
assert_eq!(value, 10);
}
#[test]
fn this_test_will_fail() {
let value = prints_and_returns_10(8);
assert_eq!(value, 5);
}
}</code></pre>
<p><span class="caption">示例 11-10一个调用了 <code>println!</code> 的函数的测试</span></p>
<p>运行 <code>cargo test</code> 将会看到这些测试的输出:</p>
<pre><code class="language-console">$ cargo test
Compiling silly-function v0.1.0 (file:///projects/silly-function)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58s
Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166)
running 2 tests
test tests::this_test_will_fail ... FAILED
test tests::this_test_will_pass ... ok
failures:
---- tests::this_test_will_fail stdout ----
I got the value 8
thread 'tests::this_test_will_fail' panicked at src/lib.rs:19:9:
assertion `left == right` failed
left: 10
right: 5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::this_test_will_fail
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>注意输出中不会出现测试通过时打印的内容,即 <code>I got the value 4</code>。因为当测试通过时,这些输出会被截获。失败测试的输出 <code>I got the value 8</code> ,则出现在输出的测试摘要部分,同时也显示了测试失败的原因。</p>
<p>如果你希望也能看到通过的测试中打印的值,也可以在结尾加上 <code>--show-output</code> 告诉 Rust 显示成功测试的输出。</p>
<pre><code class="language-console">$ cargo test -- --show-output
</code></pre>
<p>使用 <code>--show-output</code> 参数再次运行示例 11-10 中的测试会显示如下输出:</p>
<pre><code class="language-console">$ cargo test -- --show-output
Compiling silly-function v0.1.0 (file:///projects/silly-function)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.60s
Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166)
running 2 tests
test tests::this_test_will_fail ... FAILED
test tests::this_test_will_pass ... ok
successes:
---- tests::this_test_will_pass stdout ----
I got the value 4
successes:
tests::this_test_will_pass
failures:
---- tests::this_test_will_fail stdout ----
I got the value 8
thread 'tests::this_test_will_fail' panicked at src/lib.rs:19:9:
assertion `left == right` failed
left: 10
right: 5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::this_test_will_fail
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<h3 id="通过指定名字来运行部分测试"><a class="header" href="#通过指定名字来运行部分测试">通过指定名字来运行部分测试</a></h3>
<p>有时运行整个测试集会耗费很长时间。如果你负责特定位置的代码,你可能会希望只运行与这些代码相关的测试。你可以向 <code>cargo test</code> 传递所希望运行的测试名称的参数来选择运行哪些测试。</p>
<p>为了展示如何运行部分测试,示例 11-11 为 <code>add_two</code> 函数创建了三个测试,我们可以选择具体运行哪一个:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add_two(a: usize) -&gt; usize {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_two_and_two() {
let result = add_two(2);
assert_eq!(result, 4);
}
#[test]
fn add_three_and_two() {
let result = add_two(3);
assert_eq!(result, 5);
}
#[test]
fn one_hundred() {
let result = add_two(100);
assert_eq!(result, 102);
}
}</code></pre>
<p><span class="caption">示例 11-11不同名称的三个测试</span></p>
<p>如果没有传递任何参数就运行测试,如你所见,所有测试都会并行运行:</p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.62s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 3 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok
test tests::one_hundred ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<h4 id="运行单个测试"><a class="header" href="#运行单个测试">运行单个测试</a></h4>
<p>可以向 <code>cargo test</code> 传递任意测试的名称来只运行这个测试:</p>
<pre><code class="language-console">$ cargo test one_hundred
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.69s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::one_hundred ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s
</code></pre>
<p>只有名称为 <code>one_hundred</code> 的测试被运行了;因为其余两个测试并不匹配这个名称。测试输出在摘要行的结尾显示了 <code>2 filtered out</code> 表明还存在比本次所运行的测试更多的测试没有被运行。</p>
<p>不能像这样指定多个测试名称;只有传递给 <code>cargo test</code> 的第一个值才会被使用。不过有运行多个测试的方法。</p>
<h4 id="过滤运行多个测试"><a class="header" href="#过滤运行多个测试">过滤运行多个测试</a></h4>
<p>我们可以指定部分测试的名称,任何名称匹配这个名称的测试会被运行。例如,因为头两个测试的名称包含 <code>add</code>,可以通过 <code>cargo test add</code> 来运行这两个测试:</p>
<pre><code class="language-console">$ cargo test add
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.61s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 2 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
</code></pre>
<p>这运行了所有名字中带有 <code>add</code> 的测试,也过滤掉了名为 <code>one_hundred</code> 的测试。同时注意测试所在的模块也是测试名称的一部分,所以可以通过模块名来运行一个模块中的所有测试。</p>
<h3 id="除非特别指定否则忽略某些测试"><a class="header" href="#除非特别指定否则忽略某些测试">除非特别指定否则忽略某些测试</a></h3>
<p>有时一些特定的测试执行起来是非常耗费时间的,所以在大多数运行 <code>cargo test</code> 的时候希望能排除它们。虽然可以通过参数列举出所有希望运行的测试来做到,也可以使用 <code>ignore</code> 属性来标记耗时的测试并排除它们,如下所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add(left: usize, right: usize) -&gt; usize {
left + right
}
// ANCHOR: here
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
#[test]
#[ignore]
fn expensive_test() {
// 需要运行一个小时的代码
}
}
// ANCHOR_END: here</code></pre>
<p>对于想要排除的测试,我们在 <code>#[test]</code> 之后增加了 <code>#[ignore]</code> 行。现在如果运行测试,就会发现 <code>it_works</code> 运行了,而 <code>expensive_test</code> 没有运行:</p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.60s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 2 tests
test tests::expensive_test ... ignored
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p><code>expensive_test</code> 被列为 <code>ignored</code>,如果我们只希望运行被忽略的测试,可以使用 <code>cargo test -- --ignored</code></p>
<pre><code class="language-console">$ cargo test -- --ignored
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.61s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test expensive_test ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>通过控制运行哪些测试,你可以确保能够快速地运行 <code>cargo test</code> 。当你需要运行 <code>ignored</code> 的测试时,可以执行 <code>cargo test -- --ignored</code>。如果你希望不管是否忽略都要运行全部测试,可以运行 <code>cargo test -- --include-ignored</code></p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="测试的组织结构"><a class="header" href="#测试的组织结构">测试的组织结构</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch11-03-test-organization.md">ch11-03-test-organization.md</a>
<br>
commit 654d8902d380dbb8dd94ed2e548dfc0aa80c07cb</p>
</blockquote>
<p>本章一开始就提到测试是一个复杂的概念而且不同的开发者也采用不同的技术和组织。Rust 社区倾向于根据测试的两个主要分类来考虑问题:<strong>单元测试</strong><em>unit tests</em>)与 <strong>集成测试</strong><em>integration tests</em>)。单元测试倾向于更小而更集中,在隔离的环境中一次测试一个模块,或者是测试私有接口。而集成测试对于你的库来说则完全是外部的。它们与其他外部代码一样,通过相同的方式使用你的代码,只测试公有接口而且每个测试都有可能会测试多个模块。</p>
<p>为了保证你的库能够按照你的预期运行,从独立和整体的角度编写这两类测试都是非常重要的。</p>
<h3 id="单元测试"><a class="header" href="#单元测试">单元测试</a></h3>
<p>单元测试的目的是在与其他部分隔离的环境中测试每一个单元的代码,以便于快速而准确地验证某个单元的代码功能是否符合预期。单元测试与它们要测试的代码共同存放在位于 <em>src</em> 目录下相同的文件中。规范是在每个文件中创建包含测试函数的 <code>tests</code> 模块,并使用 <code>cfg(test)</code> 标注模块。</p>
<h4 id="测试模块和-cfgtest"><a class="header" href="#测试模块和-cfgtest">测试模块和 <code>#[cfg(test)]</code></a></h4>
<p>测试模块的 <code>#[cfg(test)]</code> 注解告诉 Rust 只在执行 <code>cargo test</code> 时才编译和运行测试代码,而在运行 <code>cargo build</code> 时不这么做。这在只希望构建库的时候可以节省编译时间,并且因为它们并没有包含测试,所以能减少编译产生的文件的大小。与之对应的集成测试因为位于另一个文件夹,所以它们并不需要 <code>#[cfg(test)]</code> 注解。然而单元测试位于与源码相同的文件中,所以你需要使用 <code>#[cfg(test)]</code> 来指定它们不应该被包含进编译结果中。</p>
<p>回忆本章第一部分新建的 <code>adder</code> 项目Cargo 为我们生成了如下代码:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add(left: usize, right: usize) -&gt; usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}</code></pre>
<p>上述代码就是自动生成的测试模块。<code>cfg</code> 属性代表<em>配置</em><em>configuration</em> ,它告诉 Rust接下来的项只有在给定特定配置选项时才会被包含。在这种情况下配置选项是 <code>test</code>,即 Rust 所提供的用于编译和运行测试的配置选项。通过使用 <code>cfg</code> 属性Cargo 只会在我们主动使用 <code>cargo test</code> 运行测试时才编译测试代码。这包括测试模块中可能存在的帮助函数,以及标注为 <code>#[test]</code> 的函数。</p>
<h4 id="测试私有函数"><a class="header" href="#测试私有函数">测试私有函数</a></h4>
<p>测试社区中一直存在关于是否应该对私有函数直接进行测试的论战而在其他语言中想要测试私有函数是一件困难的甚至是不可能的事。不过无论你坚持哪种测试意识形态Rust 的私有性规则确实允许你测试私有函数。考虑示例 11-12 中带有私有函数 <code>internal_adder</code> 的代码:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add_two(a: usize) -&gt; usize {
internal_adder(a, 2)
}
fn internal_adder(left: usize, right: usize) -&gt; usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn internal() {
let result = internal_adder(2, 2);
assert_eq!(result, 4);
}
}</code></pre>
<p><span class="caption">示例 11-12测试私有函数</span></p>
<p>注意 <code>internal_adder</code> 函数并没有标记为 <code>pub</code>。测试也不过是 Rust 代码,同时 <code>tests</code> 也仅仅是另一个模块。正如 <a href="ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html">“路径用于引用模块树中的项”</a> 部分所说,子模块的项可以使用其上级模块的项。在测试中,我们通过 <code>use super::*</code><code>test</code> 模块的父模块的所有项引入了作用域,接着测试调用了 <code>internal_adder</code>。如果你并不认为应该测试私有函数Rust 也不会强迫你这么做。</p>
<h3 id="集成测试"><a class="header" href="#集成测试">集成测试</a></h3>
<p>在 Rust 中,集成测试对于你需要测试的库来说完全是外部的。同其他使用库的代码一样使用库文件,也就是说它们只能调用一部分库中的公有 API。集成测试的目的是测试库的多个部分能否一起正常工作。一些单独能正确运行的代码单元集成在一起也可能会出现问题所以集成测试的覆盖率也是很重要的。为了创建集成测试你需要先创建一个 <em>tests</em> 目录。</p>
<h4 id="tests-目录"><a class="header" href="#tests-目录"><em>tests</em> 目录</a></h4>
<p>为了编写集成测试,需要在项目根目录创建一个 <em>tests</em> 目录,与 <em>src</em> 同级。Cargo 知道如何去寻找这个目录中的集成测试文件。接着可以随意在这个目录中创建任意多的测试文件Cargo 会将每一个文件当作单独的 crate 来编译。</p>
<p>让我们来创建一个集成测试。保留示例 11-12 中 <em>src/lib.rs</em> 的代码。创建一个 <em>tests</em> 目录,新建一个文件 <em>tests/integration_test.rs</em>。目录结构应该看起来像这样:</p>
<pre><code class="language-text">adder
├── Cargo.lock
├── Cargo.toml
├── src
│   └── lib.rs
└── tests
└── integration_test.rs
</code></pre>
<p>将示例 11-13 中的代码输入到 <em>tests/integration_test.rs</em> 文件中。</p>
<p><span class="filename">文件名tests/integration_test.rs</span></p>
<pre><code class="language-rust ignore">use adder::add_two;
#[test]
fn it_adds_two() {
let result = add_two(2);
assert_eq!(result, 4);
}</code></pre>
<p><span class="caption">示例 11-13一个 <code>adder</code> crate 中函数的集成测试</span></p>
<p>因为每一个 <code>tests</code> 目录中的测试文件都是完全独立的 crate所以需要在每一个文件中导入库。为此与单元测试不同我们需要在文件顶部添加 <code>use adder</code></p>
<p>并不需要将 <em>tests/integration_test.rs</em> 中的任何代码标注为 <code>#[cfg(test)]</code><code>tests</code> 文件夹在 Cargo 中是一个特殊的文件夹Cargo 只会在运行 <code>cargo test</code> 时编译这个目录中的文件。现在就运行 <code>cargo test</code> 试试:</p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 1.31s
Running unittests src/lib.rs (target/debug/deps/adder-1082c4b063a8fbe6)
running 1 test
test tests::internal ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/integration_test.rs (target/debug/deps/integration_test-1082c4b063a8fbe6)
running 1 test
test it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>现在有了三个部分的输出:单元测试、集成测试和文档测试。注意如果一个部分的任何测试失败,之后的部分都不会运行。例如如果一个单元测试失败,则不会有任何集成测试和文档测试的输出,因为这些测试只会在所有单元测试都通过后才会执行。</p>
<p>第一部分单元测试与我们之前见过的一样:每个单元测试一行(示例 11-12 中有一个叫做 <code>internal</code> 的测试),接着是一个单元测试的摘要行。</p>
<p>集成测试部分以行 <code>Running tests/integration_test.rs</code>开头。接下来每一行是一个集成测试中的测试函数,以及一个位于 <code>Doc-tests adder</code> 部分之前的集成测试的摘要行。</p>
<p>每一个集成测试文件有对应的测试结果部分,所以如果在 <em>tests</em> 目录中增加更多文件,测试结果中就会有更多集成测试结果部分。</p>
<p>我们仍然可以通过指定测试函数的名称作为 <code>cargo test</code> 的参数来运行特定集成测试。也可以使用 <code>cargo test</code><code>--test</code> 后跟文件的名称来运行某个特定集成测试文件中的所有测试:</p>
<pre><code class="language-console">$ cargo test --test integration_test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.64s
Running tests/integration_test.rs (target/debug/deps/integration_test-82e7799c1bc62298)
running 1 test
test it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>这个命令只运行了 <em>tests</em> 目录中我们指定的文件 <code>integration_test.rs</code> 中的测试。</p>
<h4 id="集成测试中的子模块"><a class="header" href="#集成测试中的子模块">集成测试中的子模块</a></h4>
<p>随着集成测试的增加,你可能希望在 <code>tests</code> 目录创建更多文件以便更好地组织它们,例如根据测试的功能来将测试分组。如前所述,<em>tests</em> 目录中的每一个文件都被编译成一个单独的 crate这有助于创建独立的作用域以便更接近于最终用户使用你的 crate 的方式。但这意味着,<em>tests</em> 目录中的文件的行为,和你在第七章中学习如何将代码分为模块和文件时,学到的 <em>src</em> 中的文件的行为不一样。</p>
<p>当你有一些在多个集成测试文件都会用到的帮助函数,而你尝试按照第七章 <a href="ch07-05-separating-modules-into-different-files.html">“将模块移动到其他文件”</a> 部分的步骤将它们提取到一个通用的模块中时, <em>tests</em> 目录中文件行为的不同就会凸显出来。例如,如果我们可以创建 一个<em>tests/common.rs</em> 文件并创建一个名叫 <code>setup</code> 的函数,我们希望这个函数能被多个测试文件的测试函数调用:</p>
<p><span class="filename">文件名tests/common.rs</span></p>
<pre><code class="language-rust noplayground">pub fn setup() {
// setup code specific to your library's tests would go here
}</code></pre>
<p>如果再次运行测试,将会在测试结果中看到一个新的对应 <em>common.rs</em> 文件的测试结果部分,即便这个文件并没有包含任何测试函数,也没有任何地方调用了 <code>setup</code> 函数:</p>
<pre><code class="language-console">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.89s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::internal ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/common.rs (target/debug/deps/common-92948b65e88960b4)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/integration_test.rs (target/debug/deps/integration_test-92948b65e88960b4)
running 1 test
test it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>我们并不想要<code>common</code> 出现在测试结果中显示 <code>running 0 tests</code> 。我们只是希望其能被其他多个集成测试文件中调用罢了。</p>
<p>为了不让 <code>common</code> 出现在测试输出中,我们将创建 <em>tests/common/mod.rs</em> ,而不是创建 <em>tests/common.rs</em> 。现在项目目录结构看起来像这样:</p>
<pre><code class="language-text">├── Cargo.lock
├── Cargo.toml
├── src
│   └── lib.rs
└── tests
├── common
│   └── mod.rs
└── integration_test.rs
</code></pre>
<p>这是一种老的命名规范,正如第七章 <a href="ch07-05-separating-modules-into-different-files.html#%E5%8F%A6%E4%B8%80%E7%A7%8D%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84">“另一种文件路径”</a> 中提到的 Rust 仍然理解它们。这样命名告诉 Rust 不要将 <code>common</code> 看作一个集成测试文件。将 <code>setup</code> 函数代码移动到 <em>tests/common/mod.rs</em> 并删除 <em>tests/common.rs</em> 文件之后,测试输出中将不会出现这一部分。<em>tests</em> 目录中的子目录不会被作为单独的 crate 编译或作为一个测试结果部分出现在测试输出中。</p>
<p>一旦拥有了 <em>tests/common/mod.rs</em>,就可以将其作为模块以便在任何集成测试文件中使用。这里是一个 <em>tests/integration_test.rs</em> 中调用 <code>setup</code> 函数的 <code>it_adds_two</code> 测试的例子:</p>
<p><span class="filename">文件名tests/integration_test.rs</span></p>
<pre><code class="language-rust ignore">use adder::add_two;
mod common;
#[test]
fn it_adds_two() {
common::setup();
let result = add_two(2);
assert_eq!(result, 4);
}</code></pre>
<p>注意 <code>mod common;</code> 声明与示例 7-21 中展示的模块声明相同。接着在测试函数中就可以调用 <code>common::setup()</code> 了。</p>
<h4 id="二进制-crate-的集成测试"><a class="header" href="#二进制-crate-的集成测试">二进制 crate 的集成测试</a></h4>
<p>如果项目是二进制 crate 并且只包含 <em>src/main.rs</em> 而没有 <em>src/lib.rs</em>,这样就不可能在 <em>tests</em> 目录创建集成测试并使用 <code>extern crate</code> 导入 <em>src/main.rs</em> 中定义的函数。只有库 crate 才会向其他 crate 暴露了可供调用和使用的函数;二进制 crate 只意在单独运行。</p>
<p>这就是许多 Rust 二进制项目使用一个简单的 <em>src/main.rs</em> 调用 <em>src/lib.rs</em> 中的逻辑的原因之一。因为通过这种结构,集成测试 <strong>就可以</strong> 通过 <code>extern crate</code> 测试库 crate 中的主要功能了,而如果这些重要的功能没有问题的话,<em>src/main.rs</em> 中的少量代码也就会正常工作且不需要测试。</p>
<h2 id="总结-10"><a class="header" href="#总结-10">总结</a></h2>
<p>Rust 的测试功能提供了一个确保即使你改变了函数的实现方式,也能继续以期望的方式运行的途径。单元测试独立地验证库的不同部分,也能够测试私有函数实现细节。集成测试则检查多个部分是否能结合起来正确地工作,并像其他外部代码那样测试库的公有 API。即使 Rust 的类型系统和所有权规则可以帮助避免一些 bug不过测试对于减少代码中不符合期望行为的逻辑 bug 仍然是很重要的。</p>
<p>让我们将本章和其他之前章节所学的知识组合起来,在下一章一起编写一个项目!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="一个-io-项目构建一个命令行程序"><a class="header" href="#一个-io-项目构建一个命令行程序">一个 I/O 项目:构建一个命令行程序</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch12-00-an-io-project.md">ch12-00-an-io-project.md</a>
<br>
commit 02a168ed346042f07010f8b65b4eeed623dd31d1</p>
</blockquote>
<p>本章既是一个目前所学的很多技能的概括,也是一个更多标准库功能的探索。我们将构建一个与文件和命令行输入/输出交互的命令行工具来练习现在一些你已经掌握的 Rust 技能。</p>
<p>Rust 的运行速度、安全性、单二进制文件输出和跨平台支持使其成为创建命令行程序的绝佳选择,所以我们的项目将创建一个我们自己版本的经典命令行搜索工具:<code>grep</code>。grep 是 “<strong>G</strong>lobally search a <strong>R</strong>egular <strong>E</strong>xpression and <strong>P</strong>rint.” 的首字母缩写。<code>grep</code> 最简单的使用场景是在特定文件中搜索指定字符串。为此,<code>grep</code> 获取一个文件路径和一个字符串作为参数,接着读取文件并找到其中包含字符串参数的行,然后打印出这些行。</p>
<p>在这个过程中,我们会展示如何让我们的命令行工具利用很多命令行工具中用到的终端功能。读取环境变量来使得用户可以配置工具的行为。打印到标准错误控制流(<code>stderr</code>)而不是标准输出(<code>stdout</code>),例如这样用户可以选择将成功输出重定向到文件中的同时仍然在屏幕上显示错误信息。</p>
<p>一位 Rust 社区的成员Andrew Gallant已经创建了一个功能完整且非常快速的 <code>grep</code> 版本,叫做 <code>ripgrep</code>。相比之下,我们的版本将非常简单,本章将教会你一些帮助理解像 <code>ripgrep</code> 这样真实项目的背景知识。</p>
<p>我们的 <code>grep</code> 项目将会结合之前所学的一些内容:</p>
<ul>
<li>代码组织(使用 <a href="ch07-00-managing-growing-projects-with-packages-crates-and-modules.html">第七章</a> 学习的模块)</li>
<li>vector 和字符串(<a href="ch08-00-common-collections.html">第八章</a>,集合)</li>
<li>错误处理(<a href="ch09-00-error-handling.html">第九章</a></li>
<li>合理的使用 trait 和生命周期(<a href="ch10-00-generics.html">第十章</a></li>
<li>测试(<a href="ch11-00-testing.html">第十一章</a></li>
</ul>
<p>另外还会简要的讲到闭包、迭代器和 trait 对象,它们分别会在 <a href="ch13-00-functional-features.html">第十三章</a><a href="ch18-00-oop.html">第十八章</a> 中详细介绍。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="接受命令行参数"><a class="header" href="#接受命令行参数">接受命令行参数</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch12-01-accepting-command-line-arguments.md">ch12-01-accepting-command-line-arguments.md</a>
<br>
commit 02a168ed346042f07010f8b65b4eeed623dd31d1</p>
</blockquote>
<p>一如既往使用 <code>cargo new</code> 新建一个项目,我们称之为 <code>minigrep</code> 以便与可能已经安装在系统上的 <code>grep</code> 工具相区别:</p>
<pre><code class="language-console">$ cargo new minigrep
Created binary (application) `minigrep` project
$ cd minigrep
</code></pre>
<p>第一个任务是让 <code>minigrep</code> 能够接受两个命令行参数:文件路径和要搜索的字符串。也就是说我们希望能够使用 <code>cargo run</code>、要搜索的字符串和被搜索的文件的路径来运行程序,像这样:</p>
<pre><code class="language-console">$ cargo run -- searchstring example-filename.txt
</code></pre>
<p>现在 <code>cargo new</code> 生成的程序忽略任何传递给它的参数。<a href="https://crates.io/">Crates.io</a> 上有一些现成的库可以帮助我们接受命令行参数,不过我们正在学习这些内容,让我们自己来实现一个。</p>
<h3 id="读取参数值"><a class="header" href="#读取参数值">读取参数值</a></h3>
<p>为了确保 <code>minigrep</code> 能够获取传递给它的命令行参数的值,我们需要一个 Rust 标准库提供的函数 <code>std::env::args</code>。这个函数返回一个传递给程序的命令行参数的 <strong>迭代器</strong><em>iterator</em>)。我们会在 <a href="ch13-00-functional-features.html">第十三章</a> 全面的介绍它们。但是现在只需理解迭代器的两个细节:迭代器生成一系列的值,可以在迭代器上调用 <code>collect</code> 方法将其转换为一个集合,比如包含所有迭代器产生元素的 vector。</p>
<p>示例 12-1 中允许 <code>minigrep</code> 程序读取任何传递给它的命令行参数并将其收集到一个 vector 中。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::env;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
dbg!(args);
}</code></pre></pre>
<p><span class="caption">示例 12-1将命令行参数收集到一个 vector 中并打印出来</span></p>
<p>首先使用 <code>use</code> 语句来将 <code>std::env</code> 模块引入作用域以便可以使用它的 <code>args</code> 函数。注意 <code>std::env::args</code> 函数被嵌套进了两层模块中。正如 <a href="ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#%E5%88%9B%E5%BB%BA%E6%83%AF%E7%94%A8%E7%9A%84-use-%E8%B7%AF%E5%BE%84">第七章</a> 讲到的,当所需函数嵌套了多于一层模块时,通常将父模块引入作用域,而不是其自身。这便于我们利用 <code>std::env</code> 中的其他函数。这比增加了 <code>use std::env::args;</code> 后仅仅使用 <code>args</code> 调用函数要更明确一些,因为 <code>args</code> 容易被错认成一个定义于当前模块的函数。</p>
<blockquote>
<h3 id="args-函数和无效的-unicode"><a class="header" href="#args-函数和无效的-unicode"><code>args</code> 函数和无效的 Unicode</a></h3>
<p>注意 <code>std::env::args</code> 在其任何参数包含无效 Unicode 字符时会 panic。如果你需要接受包含无效 Unicode 字符的参数,使用 <code>std::env::args_os</code> 代替。这个函数返回 <code>OsString</code> 值而不是 <code>String</code> 值。这里出于简单考虑使用了 <code>std::env::args</code>,因为 <code>OsString</code> 值每个平台都不一样而且比 <code>String</code> 值处理起来更为复杂。</p>
</blockquote>
<p><code>main</code> 函数的第一行,我们调用了 <code>env::args</code>,并立即使用 <code>collect</code> 来创建了一个包含迭代器所有值的 vector。<code>collect</code> 可以被用来创建很多类型的集合,所以这里显式注明 <code>args</code> 的类型来指定我们需要一个字符串 vector。虽然在 Rust 中我们很少会需要注明类型,然而 <code>collect</code> 是一个经常需要注明类型的函数,因为 Rust 不能推断出你想要什么类型的集合。</p>
<p>最后,我们使用调试宏打印出 vector。让我们尝试分别用两种方式不包含参数和包含参数运行代码</p>
<pre><code class="language-console">$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.61s
Running `target/debug/minigrep`
[src/main.rs:5:5] args = [
"target/debug/minigrep",
]
</code></pre>
<pre><code class="language-console">$ cargo run -- needle haystack
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.57s
Running `target/debug/minigrep needle haystack`
[src/main.rs:5:5] args = [
"target/debug/minigrep",
"needle",
"haystack",
]
</code></pre>
<p>注意 vector 的第一个值是 <code>"target/debug/minigrep"</code>,它是我们二进制文件的名称。这与 C 中的参数列表的行为相匹配,让程序使用在执行时调用它们的名称。如果要在消息中打印它或者根据用于调用程序的命令行别名更改程序的行为,通常可以方便地访问程序名称,不过考虑到本章的目的,我们将忽略它并只保存所需的两个参数。</p>
<h3 id="将参数值保存进变量"><a class="header" href="#将参数值保存进变量">将参数值保存进变量</a></h3>
<p>目前程序可以访问指定为命令行参数的值。现在需要将这两个参数的值保存进变量这样就可以在程序的余下部分使用这些值了。让我们如示例 12-2 这样做:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust should_panic noplayground">use std::env;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let query = &amp;args[1];
let file_path = &amp;args[2];
println!("Searching for {query}");
println!("In file {file_path}");
}</code></pre>
<p><span class="caption">示例 12-2创建变量来存放查询参数和文件路径参数</span></p>
<p>正如之前打印出 vector 时所所看到的,程序的名称占据了 vector 的第一个值 <code>args[0]</code>,所以我们从索引为 <code>1</code> 的参数开始。<code>minigrep</code> 获取的第一个参数是需要搜索的字符串,所以将其将第一个参数的引用存放在变量 <code>query</code> 中。第二个参数将是文件路径,所以将第二个参数的引用放入变量 <code>file_path</code> 中。</p>
<p>我们将临时打印出这些变量的值来证明代码如我们期望的那样工作。使用参数 <code>test</code><code>sample.txt</code> 再次运行这个程序:</p>
<pre><code class="language-console">$ cargo run -- test sample.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep test sample.txt`
Searching for test
In file sample.txt
</code></pre>
<p>好的,它可以工作!我们将所需的参数值保存进了对应的变量中。之后会增加一些错误处理来应对类似用户没有提供参数的情况,不过现在我们将忽略它们并开始增加读取文件功能。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="读取文件"><a class="header" href="#读取文件">读取文件</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch12-02-reading-a-file.md">ch12-02-reading-a-file.md</a>
<br>
commit 02a168ed346042f07010f8b65b4eeed623dd31d1</p>
</blockquote>
<p>现在我们要增加读取由 <code>file_path</code> 命令行参数指定的文件的功能。首先,需要一个用来测试的示例文件:我们会用一个拥有多行少量文本且有一些重复单词的文件。示例 12-3 是一首艾米莉·狄金森Emily Dickinson的诗它正适合这个工作在项目根目录创建一个文件 <code>poem.txt</code>,并输入诗 "I'm nobody! Who are you?"</p>
<p><span class="filename">文件名poem.txt</span></p>
<pre><code class="language-text">I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
</code></pre>
<p><span class="caption">示例 12-3艾米莉·狄金森的诗 “Im nobody! Who are you?”,一个好的测试用例</span></p>
<p>创建完这个文件之后,修改 <em>src/main.rs</em> 并增加如示例 12-4 所示的打开文件的代码:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust should_panic noplayground">use std::env;
use std::fs;
fn main() {
// --snip--
<span class="boring"> let args: Vec&lt;String&gt; = env::args().collect();
</span><span class="boring">
</span><span class="boring"> let query = &amp;args[1];
</span><span class="boring"> let file_path = &amp;args[2];
</span><span class="boring">
</span><span class="boring"> println!("Searching for {query}");
</span> println!("In file {file_path}");
let contents = fs::read_to_string(file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}</code></pre>
<p><span class="caption">示例 12-4读取第二个参数所指定的文件内容</span></p>
<p>首先,我们增加了一个 <code>use</code> 语句来引入标准库中的相关部分:我们需要 <code>std::fs</code> 来处理文件。</p>
<p><code>main</code> 中新增了一行语句:<code>fs::read_to_string</code> 接受 <code>file_path</code>,打开文件,接着返回包含其内容的 <code>std::io::Result&lt;String&gt;</code></p>
<p>在这些代码之后,我们再次增加了临时的 <code>println!</code> 打印出读取文件之后 <code>contents</code> 的值,这样就可以检查目前为止的程序能否工作。</p>
<p>尝试运行这些代码,随意指定一个字符串作为第一个命令行参数(因为还未实现搜索功能的部分)而将 <em>poem.txt</em> 文件将作为第二个参数:</p>
<pre><code class="language-console">$ cargo run -- the poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
</code></pre>
<p>好的!代码读取并打印出了文件的内容。虽然它还有一些瑕疵:此时 <code>main</code> 函数有着多个职能,通常函数只负责一个功能的话会更简洁并易于维护。另一个问题是没有尽可能的处理错误。虽然我们的程序还很小,这些瑕疵并不是什么大问题,不过随着程序功能的丰富,将会越来越难以用简单的方法修复它们。在开发程序时,及早开始重构是一个最佳实践,因为重构少量代码时要容易的多,所以让我们现在就开始吧。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="重构改进模块性和错误处理"><a class="header" href="#重构改进模块性和错误处理">重构改进模块性和错误处理</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch12-03-improving-error-handling-and-modularity.md">ch12-03-improving-error-handling-and-modularity.md</a>
<br>
commit 83788ff212a3281328e2f8f223ce9e0f69220b97</p>
</blockquote>
<p>为了改善我们的程序这里有四个问题需要修复,而且它们都与程序的组织方式和如何处理潜在错误有关。第一,<code>main</code> 现在进行了两个任务:它解析了参数并打开了文件。对于一个这样的小函数,这并不是一个大问题。然而如果 <code>main</code> 中的功能持续增加,<code>main</code> 函数处理的独立任务也会增加。当函数承担了更多责任,它就更难以推导,更难以测试,并且更难以在不破坏其他部分的情况下做出修改。最好能分离出功能以便每个函数就负责一个任务。</p>
<p>这同时也关系到第二个问题:<code>query</code><code>file_path</code> 是程序中的配置变量,而像 <code>contents</code> 则用来执行程序逻辑。随着 <code>main</code> 函数的增长,就需要引入更多的变量到作用域中,而当作用域中有更多的变量时,将更难以追踪每个变量的目的。最好能将配置变量组织进一个结构,这样就能使它们的目的更明确了。</p>
<p>第三个问题是如果打开文件失败我们使用 <code>expect</code> 来打印出错误信息,不过这个错误信息只是说 <code>Should have been able to read the file</code>。读取文件失败的原因有多种:例如文件不存在,或者没有打开此文件的权限。目前,无论处于何种情况,我们只是打印出“文件读取出现错误”的信息,这并没有给予使用者具体的信息!</p>
<p>第四,我们不停地使用 <code>expect</code> 来处理不同的错误,如果用户没有指定足够的参数来运行程序,他们会从 Rust 得到 <code>index out of bounds</code> 错误,而这并不能明确地解释问题。如果所有的错误处理都位于一处,这样将来的维护者在需要修改错误处理逻辑时就只需要考虑这一处代码。将所有的错误处理都放在一处也有助于确保我们打印的错误信息对终端用户来说是有意义的。</p>
<p>让我们通过重构项目来解决这些问题。</p>
<h3 id="二进制项目的关注分离"><a class="header" href="#二进制项目的关注分离">二进制项目的关注分离</a></h3>
<p><code>main</code> 函数负责多个任务的组织问题在许多二进制项目中很常见。所以 Rust 社区开发出一类在 <code>main</code> 函数开始变得庞大时进行二进制程序的关注分离的指导。这些过程有如下步骤:</p>
<ul>
<li>将程序拆分成 <em>main.rs</em><em>lib.rs</em> 并将程序的逻辑放入 <em>lib.rs</em> 中。</li>
<li>当命令行解析逻辑比较小时,可以保留在 <em>main.rs</em> 中。</li>
<li>当命令行解析开始变得复杂时,也同样将其从 <em>main.rs</em> 提取到 <em>lib.rs</em> 中。</li>
</ul>
<p>经过这些过程之后保留在 <code>main</code> 函数中的责任应该被限制为:</p>
<ul>
<li>使用参数值调用命令行解析逻辑</li>
<li>设置任何其他的配置</li>
<li>调用 <em>lib.rs</em> 中的 <code>run</code> 函数</li>
<li>如果 <code>run</code> 返回错误,则处理这个错误</li>
</ul>
<p>这个模式的一切就是为了关注分离:<em>main.rs</em> 处理程序运行,而 <em>lib.rs</em> 处理所有的真正的任务逻辑。因为不能直接测试 <code>main</code> 函数,这个结构通过将所有的程序逻辑移动到 <em>lib.rs</em> 的函数中使得我们可以测试它们。仅仅保留在 <em>main.rs</em> 中的代码将足够小以便阅读就可以验证其正确性。让我们遵循这些步骤来重构程序。</p>
<h3 id="提取参数解析器"><a class="header" href="#提取参数解析器">提取参数解析器</a></h3>
<p>首先,我们将解析参数的功能提取到一个 <code>main</code> 将会调用的函数中,为将命令行解析逻辑移动到 <em>src/lib.rs</em> 中做准备。示例 12-5 中展示了新 <code>main</code> 函数的开头,它调用了新函数 <code>parse_config</code>。目前它仍将定义在 <em>src/main.rs</em> 中:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span>fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let (query, file_path) = parse_config(&amp;args);
// --snip--
<span class="boring">
</span><span class="boring"> println!("Searching for {query}");
</span><span class="boring"> println!("In file {file_path}");
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(file_path)
</span><span class="boring"> .expect("Should have been able to read the file");
</span><span class="boring">
</span><span class="boring"> println!("With text:\n{contents}");
</span>}
fn parse_config(args: &amp;[String]) -&gt; (&amp;str, &amp;str) {
let query = &amp;args[1];
let file_path = &amp;args[2];
(query, file_path)
}</code></pre>
<p><span class="caption">示例 12-5<code>main</code> 中提取出 <code>parse_config</code> 函数</span></p>
<p>我们仍然将命令行参数收集进一个 vector不过不同于在 <code>main</code> 函数中将索引 1 的参数值赋值给变量 <code>query</code> 和将索引 2 的值赋值给变量 <code>file_path</code>,我们将整个 vector 传递给 <code>parse_config</code> 函数。接着 <code>parse_config</code> 函数将包含决定哪个参数该放入哪个变量的逻辑,并将这些值返回到 <code>main</code>。仍然在 <code>main</code> 中创建变量 <code>query</code><code>file_path</code>,不过 <code>main</code> 不再负责处理命令行参数与变量如何对应。</p>
<p>这对重构我们这小程序可能有点大材小用,不过我们将采用小的、增量的步骤进行重构。在做出这些改变之后,再次运行程序并验证参数解析是否仍然正常。经常验证你的进展是一个好习惯,这样在遇到问题时能帮助你定位问题的成因。</p>
<h3 id="组合配置值"><a class="header" href="#组合配置值">组合配置值</a></h3>
<p>我们可以采取另一个小的步骤来进一步改善这个函数。现在函数返回一个元组,不过立刻又将元组拆成了独立的部分。这是一个我们可能没有进行正确抽象的信号。</p>
<p>另一个表明还有改进空间的迹象是 <code>parse_config</code> 名称的 <code>config</code> 部分,它暗示了我们返回的两个值是相关的并都是一个配置值的一部分。目前除了将这两个值组合进元组之外并没有表达这个数据结构的意义:我们可以将这两个值放入一个结构体并给每个字段一个有意义的名字。这会让未来的维护者更容易理解不同的值如何相互关联以及它们的目的。</p>
<blockquote>
<p>注意:一些同学将这种在复杂类型更为合适的场景下使用基本类型的反模式称为 <strong>基本类型偏执</strong><em>primitive obsession</em>)。</p>
</blockquote>
<p>示例 12-6 展示了 <code>parse_config</code> 函数的改进。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust should_panic noplayground"><span class="boring">use std::env;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span>fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = parse_config(&amp;args);
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
// --snip--
<span class="boring">
</span><span class="boring"> println!("With text:\n{contents}");
</span>}
struct Config {
query: String,
file_path: String,
}
fn parse_config(args: &amp;[String]) -&gt; Config {
let query = args[1].clone();
let file_path = args[2].clone();
Config { query, file_path }
}</code></pre>
<p><span class="caption">示例 12-6重构 <code>parse_config</code> 返回一个 <code>Config</code> 结构体实例</span></p>
<p>新定义的结构体 <code>Config</code> 中包含字段 <code>query</code><code>file_path</code>
<code>parse_config</code> 的签名表明它现在返回一个 <code>Config</code> 值。在之前的 <code>parse_config</code> 函数体中,我们返回了引用 <code>args</code><code>String</code> 值的字符串 slice现在我们定义 <code>Config</code> 来包含拥有所有权的 <code>String</code> 值。<code>main</code> 中的 <code>args</code> 变量是参数值的所有者并只允许 <code>parse_config</code> 函数借用它们,这意味着如果 <code>Config</code> 尝试获取 <code>args</code> 中值的所有权将违反 Rust 的借用规则。</p>
<p>还有许多不同的方式可以处理 <code>String</code> 的数据,而最简单但有些不太高效的方式是调用这些值的 <code>clone</code> 方法。这会生成 <code>Config</code> 实例可以拥有的数据的完整拷贝,不过会比储存字符串数据的引用消耗更多的时间和内存。不过拷贝数据使得代码显得更加直白因为无需管理引用的生命周期,所以在这种情况下牺牲一小部分性能来换取简洁性的取舍是值得的。</p>
<blockquote>
<h4 id="使用-clone-的权衡取舍"><a class="header" href="#使用-clone-的权衡取舍">使用 <code>clone</code> 的权衡取舍</a></h4>
<p>由于其运行时消耗,许多 Rustacean 之间有一个趋势是倾向于避免使用 <code>clone</code> 来解决所有权问题。在关于迭代器的第十三章中,我们将会学习如何更有效率的处理这种情况,不过现在,复制一些字符串来取得进展是没有问题的,因为只会进行一次这样的拷贝,而且文件路径和要搜索的字符串都比较短。在第一轮编写时拥有一个可以工作但有点低效的程序要比尝试过度优化代码更好一些。随着你对 Rust 更加熟练,将能更轻松的直奔合适的方法,不过现在调用 <code>clone</code> 是完全可以接受的。</p>
</blockquote>
<p>我们更新 <code>main</code><code>parse_config</code> 返回的 <code>Config</code> 实例放入变量 <code>config</code> 中,并将之前分别使用 <code>query</code><code>file_path</code> 变量的代码更新为现在的使用 <code>Config</code> 结构体的字段的代码。</p>
<p>现在代码更明确的表现了我们的意图,<code>query</code><code>file_path</code> 是相关联的并且它们的目的是配置程序如何工作。任何使用这些值的代码就知道在 <code>config</code> 实例中对应目的的字段名中寻找它们。</p>
<h3 id="创建一个-config-的构造函数"><a class="header" href="#创建一个-config-的构造函数">创建一个 <code>Config</code> 的构造函数</a></h3>
<p>目前为止,我们将负责解析命令行参数的逻辑从 <code>main</code> 提取到了 <code>parse_config</code> 函数中,这有助于我们看清值 <code>query</code><code>file_path</code> 是相互关联的并应该在代码中表现这种关系。接着我们增加了 <code>Config</code> 结构体来描述 <code>query</code><code>file_path</code> 的相关性,并能够从 <code>parse_config</code> 函数中将这些值的名称作为结构体字段名称返回。</p>
<p>所以现在 <code>parse_config</code> 函数的目的是创建一个 <code>Config</code> 实例,我们可以将 <code>parse_config</code> 从一个普通函数变为一个叫做 <code>new</code> 的与结构体关联的函数。做出这个改变使得代码更符合习惯:可以像标准库中的 <code>String</code> 调用 <code>String::new</code> 来创建一个该类型的实例那样,将 <code>parse_config</code> 变为一个与 <code>Config</code> 关联的 <code>new</code> 函数。示例 12-7 展示了需要做出的修改:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust should_panic noplayground"><span class="boring">use std::env;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span>fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::new(&amp;args);
<span class="boring">
</span><span class="boring"> println!("Searching for {}", config.query);
</span><span class="boring"> println!("In file {}", config.file_path);
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)
</span><span class="boring"> .expect("Should have been able to read the file");
</span><span class="boring">
</span><span class="boring"> println!("With text:\n{contents}");
</span>
// --snip--
}
// --snip--
<span class="boring">struct Config {
</span><span class="boring"> query: String,
</span><span class="boring"> file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span>impl Config {
fn new(args: &amp;[String]) -&gt; Config {
let query = args[1].clone();
let file_path = args[2].clone();
Config { query, file_path }
}
}</code></pre>
<p><span class="caption">示例 12-7<code>parse_config</code> 变为 <code>Config::new</code></span></p>
<p>这里将 <code>main</code> 中调用 <code>parse_config</code> 的地方更新为调用 <code>Config::new</code>。我们将 <code>parse_config</code> 的名字改为 <code>new</code> 并将其移动到 <code>impl</code> 块中,这使得 <code>new</code> 函数与 <code>Config</code> 相关联。再次尝试编译并确保它可以工作。</p>
<h3 id="修复错误处理"><a class="header" href="#修复错误处理">修复错误处理</a></h3>
<p>现在我们开始修复错误处理。回忆一下之前提到过如果 <code>args</code> vector 包含少于 3 个项并尝试访问 vector 中索引 <code>1</code> 或索引 <code>2</code> 的值会造成程序 panic。尝试不带任何参数运行程序这将看起来像这样</p>
<pre><code class="language-console">$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep`
thread 'main' panicked at src/main.rs:27:21:
index out of bounds: the len is 1 but the index is 1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p><code>index out of bounds: the len is 1 but the index is 1</code> 是一个针对程序员的错误信息,然而这并不能真正帮助终端用户理解发生了什么和他们应该做什么。现在就让我们修复它吧。</p>
<h4 id="改善错误信息"><a class="header" href="#改善错误信息">改善错误信息</a></h4>
<p>在示例 12-8 中,在 <code>new</code> 函数中增加了一个检查在访问索引 <code>1</code><code>2</code> 之前检查 slice 是否足够长。如果 slice 不够长,程序会打印一个更好的错误信息并 panic</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let args: Vec&lt;String&gt; = env::args().collect();
</span><span class="boring">
</span><span class="boring"> let config = Config::new(&amp;args);
</span><span class="boring">
</span><span class="boring"> println!("Searching for {}", config.query);
</span><span class="boring"> println!("In file {}", config.file_path);
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)
</span><span class="boring"> .expect("Should have been able to read the file");
</span><span class="boring">
</span><span class="boring"> println!("With text:\n{contents}");
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Config {
</span><span class="boring"> query: String,
</span><span class="boring"> file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span> // --snip--
fn new(args: &amp;[String]) -&gt; Config {
if args.len() &lt; 3 {
panic!("not enough arguments");
}
// --snip--
<span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Config { query, file_path }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-8增加一个参数数量检查</span></p>
<p>这类似于 <a href="ch09-03-to-panic-or-not-to-panic.html#%E5%88%9B%E5%BB%BA%E8%87%AA%E5%AE%9A%E4%B9%89%E7%B1%BB%E5%9E%8B%E8%BF%9B%E8%A1%8C%E6%9C%89%E6%95%88%E6%80%A7%E9%AA%8C%E8%AF%81">示例 9-13 中的 <code>Guess::new</code> 函数</a>,那里如果 <code>value</code> 参数超出了有效值的范围就调用 <code>panic!</code>。不同于检查值的范围,这里检查 <code>args</code> 的长度至少是 <code>3</code>,而函数的剩余部分则可以在假设这个条件成立的基础上运行。如果 <code>args</code> 少于 3 个项,则这个条件将为真,并调用 <code>panic!</code> 立即终止程序。</p>
<p>有了 <code>new</code> 中这几行额外的代码,再次不带任何参数运行程序并看看现在错误看起来像什么:</p>
<pre><code class="language-console">$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep`
thread 'main' panicked at src/main.rs:26:13:
not enough arguments
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>这个输出就好多了,现在有了一个合理的错误信息。然而,还是有一堆额外的信息我们不希望提供给用户。所以在这里使用示例 9-9 中的技术可能不是最好的;正如 <a href="ch09-03-to-panic-or-not-to-panic.html#%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86%E6%8C%87%E5%AF%BC%E5%8E%9F%E5%88%99">第九章</a> 所讲到的一样,<code>panic!</code> 的调用更趋向于程序上的问题而不是使用上的问题。相反我们可以使用第九章学习的另一个技术 —— 返回一个可以表明成功或错误的 <a href="ch09-02-recoverable-errors-with-result.html"><code>Result</code></a></p>
<h4 id="从-new-中返回-result-而不是调用-panic"><a class="header" href="#从-new-中返回-result-而不是调用-panic"><code>new</code> 中返回 <code>Result</code> 而不是调用 <code>panic!</code></a></h4>
<p>我们可以选择返回一个 <code>Result</code> 值,它在成功时会包含一个 <code>Config</code> 的实例,而在错误时会描述问题。我们还将把函数名从<code>new</code>改为<code>build</code>,因为许多程序员希望 <code>new</code> 函数永远不会失败。当 <code>Config::new</code><code>main</code> 交流时,可以使用 <code>Result</code> 类型来表明这里存在问题。接着修改 <code>main</code><code>Err</code> 成员转换为对用户更友好的错误,而不是 <code>panic!</code> 调用产生的关于 <code>thread 'main'</code><code>RUST_BACKTRACE</code> 的文本。</p>
<p>示例 12-9 展示了为了返回 <code>Result</code><code>Config::new</code> 的返回值和函数体中所需的改变。注意这还不能编译,直到下一个示例同时也更新了 <code>main</code> 之后。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::env;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let args: Vec&lt;String&gt; = env::args().collect();
</span><span class="boring">
</span><span class="boring"> let config = Config::new(&amp;args);
</span><span class="boring">
</span><span class="boring"> println!("Searching for {}", config.query);
</span><span class="boring"> println!("In file {}", config.file_path);
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)
</span><span class="boring"> .expect("Should have been able to read the file");
</span><span class="boring">
</span><span class="boring"> println!("With text:\n{contents}");
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Config {
</span><span class="boring"> query: String,
</span><span class="boring"> file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span>impl Config {
fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}</code></pre>
<p><span class="caption">示例 12-9<code>Config::build</code> 中返回 <code>Result</code></span></p>
<p>现在 <code>build</code> 函数返回一个 <code>Result</code>,在成功时带有一个 <code>Config</code> 实例而在出现错误时带有一个 <code>&amp;'static str</code>。回忆一下第十章 “静态生命周期” 中讲到 <code>&amp;'static str</code> 是字符串字面值的类型,也是目前的错误信息。</p>
<p><code>build</code> 函数体中有两处修改:当没有足够参数时不再调用 <code>panic!</code>,而是返回 <code>Err</code> 值。同时我们将 <code>Config</code> 返回值包装进 <code>Ok</code> 成员中。这些修改使得函数符合其新的类型签名。</p>
<p>通过让 <code>Config::build</code> 返回一个 <code>Err</code> 值,这就允许 <code>main</code> 函数处理 <code>build</code> 函数返回的 <code>Result</code> 值并在出现错误的情况更明确的结束进程。</p>
<h4 id="调用-configbuild-并处理错误"><a class="header" href="#调用-configbuild-并处理错误">调用 <code>Config::build</code> 并处理错误</a></h4>
<p>为了处理错误情况并打印一个对用户友好的信息,我们需要像示例 12-10 那样更新 <code>main</code> 函数来处理现在 <code>Config::build</code> 返回的 <code>Result</code>。另外还需要手动实现原先由 <code>panic!</code>负责的工作,即以非零错误码退出命令行工具的工作。非零的退出状态是一个惯例信号,用来告诉调用程序的进程:该程序以错误状态退出了。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::fs;
</span>use std::process;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::build(&amp;args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {err}");
process::exit(1);
});
// --snip--
<span class="boring">
</span><span class="boring"> println!("Searching for {}", config.query);
</span><span class="boring"> println!("In file {}", config.file_path);
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)
</span><span class="boring"> .expect("Should have been able to read the file");
</span><span class="boring">
</span><span class="boring"> println!("With text:\n{contents}");
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Config {
</span><span class="boring"> query: String,
</span><span class="boring"> file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-10如果新建 <code>Config</code> 失败则使用错误码退出</span></p>
<p>在上面的示例中,使用了一个之前没有详细说明的方法:<code>unwrap_or_else</code>,它定义于标准库的 <code>Result&lt;T, E&gt;</code> 上。使用 <code>unwrap_or_else</code> 可以进行一些自定义的非 <code>panic!</code> 的错误处理。当 <code>Result</code><code>Ok</code> 时,这个方法的行为类似于 <code>unwrap</code>:它返回 <code>Ok</code> 内部封装的值。然而,当其值是 <code>Err</code> 时,该方法会调用一个 <strong>闭包</strong><em>closure</em>),也就是一个我们定义的作为参数传递给 <code>unwrap_or_else</code> 的匿名函数。<a href="ch13-00-functional-features.html">第十三章</a> 会更详细的介绍闭包。现在你需要理解的是 <code>unwrap_or_else</code> 会将 <code>Err</code> 的内部值,也就是示例 12-9 中增加的 <code>not enough arguments</code> 静态字符串的情况,传递给闭包中位于两道竖线间的参数 <code>err</code>。闭包中的代码在其运行时可以使用这个 <code>err</code> 值。</p>
<p>我们新增了一个 <code>use</code> 行来从标准库中导入 <code>process</code>。在错误的情况闭包中将被运行的代码只有两行:我们打印出了 <code>err</code> 值,接着调用了 <code>std::process::exit</code><code>process::exit</code> 会立即停止程序并将传递给它的数字作为退出状态码。这类似于示例 12-8 中使用的基于 <code>panic!</code> 的错误处理,除了不会再得到所有的额外输出了。让我们试试:</p>
<pre><code class="language-console">$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/minigrep`
Problem parsing arguments: not enough arguments
</code></pre>
<p>非常好!现在输出对于用户来说就友好多了。</p>
<h3 id="从-main-提取逻辑"><a class="header" href="#从-main-提取逻辑"><code>main</code> 提取逻辑</a></h3>
<p>现在我们完成了配置解析的重构:让我们转向程序的逻辑。正如 <a href="ch12-03-improving-error-handling-and-modularity.html#%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%A1%B9%E7%9B%AE%E7%9A%84%E5%85%B3%E6%B3%A8%E5%88%86%E7%A6%BB">“二进制项目的关注分离”</a> 部分所展开的讨论,我们将提取一个叫做 <code>run</code> 的函数来存放目前 <code>main</code> 函数中不属于设置配置或处理错误的所有逻辑。一旦完成这些,<code>main</code> 函数将简明得足以通过观察来验证,而我们将能够为所有其他逻辑编写测试。</p>
<p>示例 12-11 展示了提取出来的 <code>run</code> 函数。目前我们只进行小的增量式的提取函数的改进。我们仍将在 <em>src/main.rs</em> 中定义这个函数:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::fs;
</span><span class="boring">use std::process;
</span><span class="boring">
</span>fn main() {
// --snip--
<span class="boring"> let args: Vec&lt;String&gt; = env::args().collect();
</span><span class="boring">
</span><span class="boring"> let config = Config::build(&amp;args).unwrap_or_else(|err| {
</span><span class="boring"> println!("Problem parsing arguments: {err}");
</span><span class="boring"> process::exit(1);
</span><span class="boring"> });
</span><span class="boring">
</span> println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
run(config);
}
fn run(config: Config) {
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}
// --snip--
<span class="boring">
</span><span class="boring">struct Config {
</span><span class="boring"> query: String,
</span><span class="boring"> file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-11提取 <code>run</code> 函数来包含剩余的程序逻辑</span></p>
<p>现在 <code>run</code> 函数包含了 <code>main</code> 中从读取文件开始的剩余的所有逻辑。<code>run</code> 函数获取一个 <code>Config</code> 实例作为参数。</p>
<h4 id="从-run-函数中返回错误"><a class="header" href="#从-run-函数中返回错误"><code>run</code> 函数中返回错误</a></h4>
<p>通过将剩余的逻辑分离进 <code>run</code> 函数而不是留在 <code>main</code> 中,就可以像示例 12-9 中的 <code>Config::build</code> 那样改进错误处理。不再通过 <code>expect</code> 允许程序 panic<code>run</code> 函数将会在出错时返回一个 <code>Result&lt;T, E&gt;</code>。这让我们进一步以一种对用户友好的方式统一 <code>main</code> 中的错误处理。示例 12-12 展示了 <code>run</code> 签名和函数体中的改变:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::fs;
</span><span class="boring">use std::process;
</span>use std::error::Error;
// --snip--
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let args: Vec&lt;String&gt; = env::args().collect();
</span><span class="boring">
</span><span class="boring"> let config = Config::build(&amp;args).unwrap_or_else(|err| {
</span><span class="boring"> println!("Problem parsing arguments: {err}");
</span><span class="boring"> process::exit(1);
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> println!("Searching for {}", config.query);
</span><span class="boring"> println!("In file {}", config.file_path);
</span><span class="boring">
</span><span class="boring"> run(config);
</span><span class="boring">}
</span><span class="boring">
</span>fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
let contents = fs::read_to_string(config.file_path)?;
println!("With text:\n{contents}");
Ok(())
}
<span class="boring">
</span><span class="boring">struct Config {
</span><span class="boring"> query: String,
</span><span class="boring"> file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-12修改 <code>run</code> 函数返回 <code>Result</code></span></p>
<p>这里我们做出了三个明显的修改。首先,将 <code>run</code> 函数的返回类型变为 <code>Result&lt;(), Box&lt;dyn Error&gt;&gt;</code>。之前这个函数返回 unit 类型 <code>()</code>,现在它仍然保持作为 <code>Ok</code> 时的返回值。</p>
<p>对于错误类型,使用了 <strong>trait 对象</strong> <code>Box&lt;dyn Error&gt;</code>(在开头使用了 <code>use</code> 语句将 <code>std::error::Error</code> 引入作用域)。<a href="ch18-00-oop.html">第十八章</a> 会涉及 trait 对象。目前只需知道 <code>Box&lt;dyn Error&gt;</code> 意味着函数会返回实现了 <code>Error</code> trait 的类型,不过无需指定具体将会返回的值的类型。这提供了在不同的错误场景可能有不同类型的错误返回值的灵活性。这也就是 <code>dyn</code>,它是 “动态的”“dynamic”的缩写。</p>
<p>第二个改变是去掉了 <code>expect</code> 调用并替换为 <a href="ch09-02-recoverable-errors-with-result.html#%E4%BC%A0%E6%92%AD%E9%94%99%E8%AF%AF%E7%9A%84%E7%AE%80%E5%86%99-%E8%BF%90%E7%AE%97%E7%AC%A6">第九章</a> 讲到的 <code>?</code>。不同于遇到错误就 <code>panic!</code><code>?</code> 会从函数中返回错误值并让调用者来处理它。</p>
<p>第三个修改是现在成功时这个函数会返回一个 <code>Ok</code> 值。因为 <code>run</code> 函数签名中声明成功类型返回值是 <code>()</code>,这意味着需要将 unit 类型值包装进 <code>Ok</code> 值中。<code>Ok(())</code> 一开始看起来有点奇怪,不过这样使用 <code>()</code> 是惯用的做法,表明调用 <code>run</code> 函数只是为了它的副作用;函数并没有返回什么有意义的值。</p>
<p>上述代码能够编译,不过会有一个警告:</p>
<pre><code class="language-console">$ cargo run -- the poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
warning: unused `Result` that must be used
--&gt; src/main.rs:19:5
|
19 | run(config);
| ^^^^^^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
|
19 | let _ = run(config);
| +++++++
warning: `minigrep` (bin "minigrep") generated 1 warning
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.71s
Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
</code></pre>
<p>Rust 提示我们的代码忽略了 <code>Result</code> 值,它可能表明这里存在一个错误。但我们却没有检查这里是否有一个错误,而编译器提醒我们这里应该有一些错误处理代码!现在就让我们修正这个问题。</p>
<h4 id="处理-main-中-run-返回的错误"><a class="header" href="#处理-main-中-run-返回的错误">处理 <code>main</code><code>run</code> 返回的错误</a></h4>
<p>我们将检查错误并使用类似示例 12-10 中 <code>Config::build</code> 处理错误的技术来处理它们,不过有一些细微的不同:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">use std::process;
</span><span class="boring">
</span>fn main() {
// --snip--
<span class="boring"> let args: Vec&lt;String&gt; = env::args().collect();
</span><span class="boring">
</span><span class="boring"> let config = Config::build(&amp;args).unwrap_or_else(|err| {
</span><span class="boring"> println!("Problem parsing arguments: {err}");
</span><span class="boring"> process::exit(1);
</span><span class="boring"> });
</span><span class="boring">
</span> println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
if let Err(e) = run(config) {
println!("Application error: {e}");
process::exit(1);
}
}
<span class="boring">
</span><span class="boring">fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> println!("With text:\n{contents}");
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Config {
</span><span class="boring"> query: String,
</span><span class="boring"> file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>我们使用 <code>if let</code> 来检查 <code>run</code> 是否返回一个 <code>Err</code> 值,不同于 <code>unwrap_or_else</code>,并在出错时调用 <code>process::exit(1)</code><code>run</code> 并不返回像 <code>Config::build</code> 返回的 <code>Config</code> 实例那样需要 <code>unwrap</code> 的值。因为 <code>run</code> 在成功时返回 <code>()</code>,而我们只关心检测错误,所以并不需要 <code>unwrap_or_else</code> 来返回未封装的值,因为它只会是 <code>()</code></p>
<p>不过两个例子中 <code>if let</code><code>unwrap_or_else</code> 的函数体都一样:打印出错误并退出。</p>
<h3 id="将代码拆分到库-crate"><a class="header" href="#将代码拆分到库-crate">将代码拆分到库 crate</a></h3>
<p>现在我们的 <code>minigrep</code> 项目看起来好多了!现在我们将要拆分 <em>src/main.rs</em> 并将一些代码放入 <em>src/lib.rs</em>,这样就能测试它们并拥有一个含有更少功能的 <code>main</code> 函数。</p>
<p>让我们将所有不是 <code>main</code> 函数的代码从 <em>src/main.rs</em> 移动到新文件 <em>src/lib.rs</em> 中:</p>
<ul>
<li><code>run</code> 函数定义</li>
<li>相关的 <code>use</code> 语句</li>
<li><code>Config</code> 的定义</li>
<li><code>Config::build</code> 函数定义</li>
</ul>
<p>现在 <em>src/lib.rs</em> 的内容应该看起来像示例 12-13为了简洁省略了函数体。注意直到下一个示例修改完 <em>src/main.rs</em> 之后,代码还不能编译:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
// --snip--
<span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span> }
}
pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
// --snip--
<span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> println!("With text:\n{contents}");
</span><span class="boring">
</span><span class="boring"> Ok(())
</span>}</code></pre>
<p><span class="caption">示例 12-13<code>Config</code><code>run</code> 移动到 <em>src/lib.rs</em></span></p>
<p>这里使用了公有的 <code>pub</code> 关键字:在 <code>Config</code>、其字段和其 <code>build</code> 方法,以及 <code>run</code> 函数上。现在我们有了一个拥有可以测试的公有 API 的库 crate 了。</p>
<p>现在需要在 <em>src/main.rs</em> 中将移动到 <em>src/lib.rs</em> 的代码引入二进制 crate 的作用域中,如示例 12-14 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use std::env;
use std::process;
use minigrep::Config;
fn main() {
// --snip--
<span class="boring"> let args: Vec&lt;String&gt; = env::args().collect();
</span><span class="boring">
</span><span class="boring"> let config = Config::build(&amp;args).unwrap_or_else(|err| {
</span><span class="boring"> println!("Problem parsing arguments: {err}");
</span><span class="boring"> process::exit(1);
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> println!("Searching for {}", config.query);
</span><span class="boring"> println!("In file {}", config.file_path);
</span><span class="boring">
</span> if let Err(e) = minigrep::run(config) {
// --snip--
<span class="boring"> println!("Application error: {e}");
</span><span class="boring"> process::exit(1);
</span> }
}</code></pre>
<p><span class="caption">示例 12-14<code>minigrep</code> crate 引入 <em>src/main.rs</em> 的作用域中</span></p>
<p>我们添加了一行 <code>use minigrep::Config</code>,它将 <code>Config</code> 类型引入作用域,并使用 crate 名称作为 <code>run</code> 函数的前缀。通过这些重构,所有功能应该能够联系在一起并运行了。运行 <code>cargo run</code> 来确保一切都正确的衔接在一起。</p>
<p>哇哦!我们做了大量的工作,不过我们为将来的成功打下了基础。现在处理错误将更容易,同时代码也更加模块化。从现在开始几乎所有的工作都将在 <em>src/lib.rs</em> 中进行。</p>
<p>让我们利用这些新创建的模块的优势来进行一些在旧代码中难以展开的工作,这些工作在新代码中非常容易实现,那就是:编写测试!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="采用测试驱动开发完善库的功能"><a class="header" href="#采用测试驱动开发完善库的功能">采用测试驱动开发完善库的功能</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch12-04-testing-the-librarys-functionality.md">ch12-04-testing-the-librarys-functionality.md</a>
<br>
commit 8fd2327e4135876b368cc2793eb4a7e455b691f0</p>
</blockquote>
<p>现在我们将逻辑提取到了 <em>src/lib.rs</em> 并将所有的参数解析和错误处理留在了 <em>src/main.rs</em> 中,为代码的核心功能编写测试将更加容易。我们可以直接使用多种参数调用函数并检查返回值而无需从命令行运行二进制文件了。</p>
<p>在这一部分我们将遵循测试驱动开发Test Driven Development, TDD的模式来逐步增加 <code>minigrep</code> 的搜索逻辑。它遵循如下步骤:</p>
<ol>
<li>编写一个失败的测试,并运行它以确保它失败的原因是你所期望的。</li>
<li>编写或修改足够的代码来使新的测试通过。</li>
<li>重构刚刚增加或修改的代码,并确保测试仍然能通过。</li>
<li>从步骤 1 开始重复!</li>
</ol>
<p>虽然这只是众多编写软件的方法之一,不过 TDD 有助于驱动代码的设计。在编写能使测试通过的代码之前编写测试有助于在开发过程中保持高测试覆盖率。</p>
<p>我们将测试驱动实现实际在文件内容中搜索查询字符串并返回匹配的行示例的功能。我们将在一个叫做 <code>search</code> 的函数中增加这些功能。</p>
<h3 id="编写失败测试"><a class="header" href="#编写失败测试">编写失败测试</a></h3>
<p>去掉 <em>src/lib.rs</em><em>src/main.rs</em> 中用于检查程序行为的 <code>println!</code> 语句,因为不再真正需要它们了。接着我们会像 <a href="ch11-01-writing-tests.html#%E6%B5%8B%E8%AF%95%E5%87%BD%E6%95%B0%E5%89%96%E6%9E%90">第十一章</a> 那样增加一个 <code>test</code> 模块和一个测试函数。测试函数指定了 <code>search</code> 函数期望拥有的行为:它会获取一个需要查询的字符串和用来查询的文本,并只会返回包含请求的文本行。示例 12-15 展示了这个测试,它还不能编译:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span>#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}</code></pre>
<p><span class="caption">示例 12-15创建一个我们期望的 <code>search</code> 函数的失败测试</span></p>
<p>这里选择使用 <code>"duct"</code> 作为这个测试中需要搜索的字符串。用来搜索的文本有三行,其中只有一行包含 <code>"duct"</code>。(注意双引号之后的反斜杠,这告诉 Rust 不要在字符串字面值内容的开头加入换行符)我们断言 <code>search</code> 函数的返回值只包含期望的那一行。</p>
<p>我们还不能运行这个测试并看到它失败,因为它甚至都还不能编译:<code>search</code> 函数还不存在呢!根据 TDD 的原则,我们将增加足够的代码来使其能够编译:一个总是会返回空 vector 的 <code>search</code> 函数定义,如示例 12-16 所示。然后这个测试应该能够编译并因为空 vector 并不匹配一个包含一行 <code>"safe, fast, productive."</code> 的 vector 而失败。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span>pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
vec![]
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-16刚好足够使测试通过编译的 <code>search</code> 函数定义</span></p>
<p>注意需要在 <code>search</code> 的签名中定义一个显式生命周期 <code>'a</code> 并用于 <code>contents</code> 参数和返回值。回忆一下 <a href="ch10-03-lifetime-syntax.html">第十章</a> 中讲到生命周期参数指定哪个参数的生命周期与返回值的生命周期相关联。在这个例子中,我们表明返回的 vector 中应该包含引用参数 <code>contents</code>(而不是参数<code>query</code>slice 的字符串 slice。</p>
<p>换句话说,我们告诉 Rust 函数 <code>search</code> 返回的数据将与 <code>search</code> 函数中的参数 <code>contents</code> 的数据存在的一样久。这是非常重要的!为了使这个引用有效那么 <strong></strong> slice 引用的数据也需要保持有效;如果编译器认为我们是在创建 <code>query</code> 而不是 <code>contents</code> 的字符串 slice那么安全检查将是不正确的。</p>
<p>如果尝试不用生命周期编译的话,我们将得到如下错误:</p>
<pre><code class="language-console">$ cargo build
Compiling minigrep v0.1.0 (file:///projects/minigrep)
error[E0106]: missing lifetime specifier
--&gt; src/lib.rs:28:51
|
28 | pub fn search(query: &amp;str, contents: &amp;str) -&gt; Vec&lt;&amp;str&gt; {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents`
help: consider introducing a named lifetime parameter
|
28 | pub fn search&lt;'a&gt;(query: &amp;'a str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
| ++++ ++ ++ ++
For more information about this error, try `rustc --explain E0106`.
error: could not compile `minigrep` (lib) due to 1 previous error
</code></pre>
<p>Rust 不可能知道我们需要的是哪一个参数,所以需要告诉它。因为参数 <code>contents</code> 包含了所有的文本而且我们希望返回匹配的那部分文本,所以我们知道 <code>contents</code> 是应该要使用生命周期语法来与返回值相关联的参数。</p>
<p>其他语言中并不需要你在函数签名中将参数与返回值相关联。所以这么做可能仍然感觉有些陌生,随着时间的推移这将会变得越来越容易。你可能想要将这个例子与第十章中 <a href="ch10-03-lifetime-syntax.html#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E7%A1%AE%E4%BF%9D%E5%BC%95%E7%94%A8%E6%9C%89%E6%95%88">“生命周期确保引用有效”</a> 部分做对比。</p>
<p>现在运行测试:</p>
<pre><code class="language-console">$ cargo test
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.97s
Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 1 test
test tests::one_result ... FAILED
failures:
---- tests::one_result stdout ----
thread 'tests::one_result' panicked at src/lib.rs:44:9:
assertion `left == right` failed
left: ["safe, fast, productive."]
right: []
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::one_result
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>好的,测试失败了,这正是我们所期望的。修改代码来让测试通过吧!</p>
<h3 id="编写使测试通过的代码"><a class="header" href="#编写使测试通过的代码">编写使测试通过的代码</a></h3>
<p>目前测试之所以会失败是因为我们总是返回一个空的 vector。为了修复并实现 <code>search</code>,我们的程序需要遵循如下步骤:</p>
<ul>
<li>遍历内容的每一行文本。</li>
<li>查看这一行是否包含要搜索的字符串。</li>
<li>如果有,将这一行加入列表返回值中。</li>
<li>如果没有,什么也不做。</li>
<li>返回匹配到的结果列表</li>
</ul>
<p>让我们一步一步的来,从遍历每行开始。</p>
<h4 id="使用-lines-方法遍历每一行"><a class="header" href="#使用-lines-方法遍历每一行">使用 <code>lines</code> 方法遍历每一行</a></h4>
<p>Rust 有一个有助于一行一行遍历字符串的方法,出于方便它被命名为 <code>lines</code>,它如示例 12-17 这样工作。注意这还不能编译:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span>pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
for line in contents.lines() {
// do something with line
}
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-17遍历 <code>contents</code> 的每一行</span></p>
<p><code>lines</code> 方法返回一个迭代器。<a href="ch13-02-iterators.html">第十三章</a> 会深入了解迭代器,不过我们已经在 <a href="ch03-05-control-flow.html#%E4%BD%BF%E7%94%A8-for-%E9%81%8D%E5%8E%86%E9%9B%86%E5%90%88">示例 3-5</a> 中见过使用迭代器的方法了,在那里使用了一个 <code>for</code> 循环和迭代器在一个集合的每一项上运行了一些代码。</p>
<h4 id="用查询字符串搜索每一行"><a class="header" href="#用查询字符串搜索每一行">用查询字符串搜索每一行</a></h4>
<p>接下来将会增加检查当前行是否包含查询字符串的功能。幸运的是,字符串类型为此也有一个叫做 <code>contains</code> 的实用方法!如示例 12-18 所示在 <code>search</code> 函数中加入 <code>contains</code> 方法调用。注意这仍然不能编译:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span>pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
for line in contents.lines() {
if line.contains(query) {
// 对文本行进行操作
}
}
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-18增加检查文本行是否包含 <code>query</code> 中字符串的功能</span></p>
<h4 id="存储匹配的行"><a class="header" href="#存储匹配的行">存储匹配的行</a></h4>
<p>为了完成这个函数,我们还需要一个方法来存储包含查询字符串的行。为此可以在 <code>for</code> 循环之前创建一个可变的 vector 并调用 <code>push</code> 方法在 vector 中存放一个 <code>line</code>。在 <code>for</code> 循环之后,返回这个 vector如示例 12-19 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span>pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-19储存匹配的行以便可以返回它们</span></p>
<p>现在 <code>search</code> 函数应该返回只包含 <code>query</code> 的那些行,而测试应该会通过。让我们运行测试:</p>
<pre><code class="language-console">$ cargo test
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `test` profile [unoptimized + debuginfo] target(s) in 1.22s
Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 1 test
test tests::one_result ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests minigrep
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>测试通过了,它可以工作了!</p>
<p>现在正是可以考虑重构的时机,在保证测试通过,保持功能不变的前提下重构 <code>search</code> 函数。<code>search</code> 函数中的代码并不坏,不过并没有利用迭代器的一些实用功能。第十三章将回到这个例子并深入探索迭代器并看看如何改进代码。</p>
<h4 id="在-run-函数中使用-search-函数"><a class="header" href="#在-run-函数中使用-search-函数"><code>run</code> 函数中使用 <code>search</code> 函数</a></h4>
<p>现在 <code>search</code> 函数是可以工作并测试通过了的,我们需要实际在 <code>run</code> 函数中调用 <code>search</code>。需要将 <code>config.query</code> 值和 <code>run</code> 从文件中读取的 <code>contents</code> 传递给 <code>search</code> 函数。接着 <code>run</code> 会打印出 <code>search</code> 返回的每一行:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
let contents = fs::read_to_string(config.file_path)?;
for line in search(&amp;config.query, &amp;contents) {
println!("{line}");
}
Ok(())
}
<span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>这里仍然使用了 <code>for</code> 循环获取了 <code>search</code> 返回的每一行并打印出来。</p>
<p>现在整个程序应该可以工作了!让我们试一试,首先使用一个只会在艾米莉·狄金森的诗中返回一行的单词 “frog”</p>
<pre><code class="language-console">$ cargo run -- frog poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.38s
Running `target/debug/minigrep frog poem.txt`
How public, like a frog
</code></pre>
<p>好的!现在试试一个会匹配多行的单词,比如 “body”</p>
<pre><code class="language-console">$ cargo run -- body poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep body poem.txt`
I'm nobody! Who are you?
Are you nobody, too?
How dreary to be somebody!
</code></pre>
<p>最后,让我们确保搜索一个在诗中哪里都没有的单词时不会得到任何行,比如 "monomorphization"</p>
<pre><code class="language-console">$ cargo run -- monomorphization poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep monomorphization poem.txt`
</code></pre>
<p>非常好!我们创建了一个属于自己的迷你版经典工具,并学习了很多如何组织程序的知识。我们还学习了一些文件输入输出、生命周期、测试和命令行解析的内容。</p>
<p>为了使这个项目更丰满,我们将简要的展示如何处理环境变量和打印到标准错误,这两者在编写命令行程序时都很有用。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="处理环境变量"><a class="header" href="#处理环境变量">处理环境变量</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch12-05-working-with-environment-variables.md">ch12-05-working-with-environment-variables.md</a>
<br>
commit 9c0fa2714859738ff73cbbb829592e4c037d7e46</p>
</blockquote>
<p>我们将增加一个额外的功能来改进 <code>minigrep</code>:用户可以通过设置环境变量来设置搜索是否是大小写敏感的。当然,我们也可以将其设计为一个命令行参数并要求用户每次需要时都加上它,不过在这里我们将使用环境变量。这允许用户设置环境变量一次之后在整个终端会话中所有的搜索都将是大小写不敏感的。</p>
<h3 id="编写一个大小写不敏感-search-函数的失败测试"><a class="header" href="#编写一个大小写不敏感-search-函数的失败测试">编写一个大小写不敏感 <code>search</code> 函数的失败测试</a></h3>
<p>首先我们希望增加一个新函数 <code>search_case_insensitive</code>,并将会在环境变量有值时调用它。这里将继续遵循 TDD 过程,其第一步是再次编写一个失败测试。我们将为新的大小写不敏感搜索函数新增一个测试函数,并将老的测试函数从 <code>one_result</code> 改名为 <code>case_sensitive</code> 来更清楚的表明这两个测试的区别,如示例 12-20 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> for line in search(&amp;config.query, &amp;contents) {
</span><span class="boring"> println!("{line}");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span>#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}</code></pre>
<p><span class="caption">示例 12-20为准备添加的大小写不敏感函数新增失败测试</span></p>
<p>注意我们也改变了老测试中 <code>contents</code> 的值。还新增了一个含有文本 <code>"Duct tape."</code> 的行,它有一个大写的 D这在大小写敏感搜索时不应该匹配 "duct"。我们修改这个测试以确保不会意外破坏已经实现的大小写敏感搜索功能;这个测试现在应该能通过并在处理大小写不敏感搜索时应该能一直通过。</p>
<p>大小写 <strong>不敏感</strong> 搜索的新测试使用 <code>"rUsT"</code> 作为其查询字符串。在我们将要增加的 <code>search_case_insensitive</code> 函数中,<code>"rUsT"</code> 查询应该包含带有一个大写 R 的 <code>"Rust:"</code> 还有 <code>"Trust me."</code> 这两行,即便它们与查询的大小写都不同。这个测试现在不能编译,因为还没有定义 <code>search_case_insensitive</code> 函数。请随意增加一个总是返回空 vector 的骨架实现,正如示例 12-16 中 <code>search</code> 函数为了使测试通过编译并失败时所做的那样。</p>
<h3 id="实现-search_case_insensitive-函数"><a class="header" href="#实现-search_case_insensitive-函数">实现 <code>search_case_insensitive</code> 函数</a></h3>
<p><code>search_case_insensitive</code> 函数,如示例 12-21 所示,将与 <code>search</code> 函数基本相同。唯一的区别是它会将 <code>query</code> 变量和每一 <code>line</code> 都变为小写,这样不管输入参数是大写还是小写,在检查该行是否包含查询字符串时都会是小写。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> for line in search(&amp;config.query, &amp;contents) {
</span><span class="boring"> println!("{line}");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span>pub fn search_case_insensitive&lt;'a&gt;(
query: &amp;str,
contents: &amp;'a str,
) -&gt; Vec&lt;&amp;'a str&gt; {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&amp;query) {
results.push(line);
}
}
results
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_sensitive() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Duct tape.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_insensitive() {
</span><span class="boring"> let query = "rUsT";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Trust me.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(
</span><span class="boring"> vec!["Rust:", "Trust me."],
</span><span class="boring"> search_case_insensitive(query, contents)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-21定义 <code>search_case_insensitive</code> 函数,它在比较查询和每一行之前将它们都转换为小写</span></p>
<p>首先我们将 <code>query</code> 字符串转换为小写,并将其覆盖到同名的变量中。对查询字符串调用 <code>to_lowercase</code> 是必需的,这样不管用户的查询是 <code>"rust"</code><code>"RUST"</code><code>"Rust"</code> 或者 <code>"rUsT"</code>,我们都将其当作 <code>"rust"</code> 处理并对大小写不敏感。虽然 <code>to_lowercase</code> 可以处理基本的 Unicode但它不是 100% 准确。如果编写真实的程序的话,我们还需多做一些工作,不过这一部分是关于环境变量而不是 Unicode 的,所以这样就够了。</p>
<p>注意 <code>query</code> 现在是一个 <code>String</code> 而不是字符串 slice因为调用 <code>to_lowercase</code> 是在创建新数据,而不是引用现有数据。如果查询字符串是 <code>"rUsT"</code>,这个字符串 slice 并不包含可供我们使用的小写的 <code>u</code><code>t</code>,所以必需分配一个包含 <code>"rust"</code> 的新 <code>String</code>。现在当我们将 <code>query</code> 作为一个参数传递给 <code>contains</code> 方法时,需要增加一个 &amp; 因为 <code>contains</code> 的签名被定义为获取一个字符串 slice。</p>
<p>接下来我们对每一 <code>line</code> 都调用 <code>to_lowercase</code> 将其转为小写。现在我们将 <code>line</code><code>query</code> 都转换成了小写,这样就可以不管查询的大小写进行匹配了。</p>
<p>让我们看看这个实现能否通过测试:</p>
<pre><code class="language-console">$ cargo test
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `test` profile [unoptimized + debuginfo] target(s) in 1.33s
Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 2 tests
test tests::case_insensitive ... ok
test tests::case_sensitive ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests minigrep
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>好的!现在,让我们在 <code>run</code> 函数中实际调用新 <code>search_case_insensitive</code> 函数。首先,我们将在 <code>Config</code> 结构体中增加一个配置项来切换大小写敏感和大小写不敏感搜索。增加这些字段会导致编译错误,因为我们还没有在任何地方初始化这些字段:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span>pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
<span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> let results = if config.ignore_case {
</span><span class="boring"> search_case_insensitive(&amp;config.query, &amp;contents)
</span><span class="boring"> } else {
</span><span class="boring"> search(&amp;config.query, &amp;contents)
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> for line in results {
</span><span class="boring"> println!("{line}");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search_case_insensitive&lt;'a&gt;(
</span><span class="boring"> query: &amp;str,
</span><span class="boring"> contents: &amp;'a str,
</span><span class="boring">) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let query = query.to_lowercase();
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.to_lowercase().contains(&amp;query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_sensitive() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Duct tape.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_insensitive() {
</span><span class="boring"> let query = "rUsT";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Trust me.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(
</span><span class="boring"> vec!["Rust:", "Trust me."],
</span><span class="boring"> search_case_insensitive(query, contents)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>这里增加了 <code>ignore_case</code> 字符来存放一个布尔值。接着我们需要 <code>run</code> 函数检查 <code>case_sensitive</code> 字段的值并使用它来决定是否调用 <code>search</code> 函数或 <code>search_case_insensitive</code> 函数,如示例 12-22 所示。注意这还不能编译:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring"> pub ignore_case: bool,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&amp;config.query, &amp;contents)
} else {
search(&amp;config.query, &amp;contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
<span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search_case_insensitive&lt;'a&gt;(
</span><span class="boring"> query: &amp;str,
</span><span class="boring"> contents: &amp;'a str,
</span><span class="boring">) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let query = query.to_lowercase();
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.to_lowercase().contains(&amp;query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_sensitive() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Duct tape.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_insensitive() {
</span><span class="boring"> let query = "rUsT";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Trust me.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(
</span><span class="boring"> vec!["Rust:", "Trust me."],
</span><span class="boring"> search_case_insensitive(query, contents)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-22根据 <code>config.ignore_case</code> 的值调用 <code>search</code><code>search_case_insensitive</code></span></p>
<p>最后需要实际检查环境变量。处理环境变量的函数位于标准库的 <code>env</code> 模块中,所以我们需要在 <em>src/lib.rs</em> 的开头将这个模块引入作用域中。接着使用 <code>env</code> 模块的 <code>var</code> 方法来检查一个叫做 <code>IGNORE_CASE</code> 的环境变量,如示例 12-23 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::env;
// --snip--
<span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring"> pub ignore_case: bool,
</span><span class="boring">}
</span><span class="boring">
</span>impl Config {
pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
<span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> let results = if config.ignore_case {
</span><span class="boring"> search_case_insensitive(&amp;config.query, &amp;contents)
</span><span class="boring"> } else {
</span><span class="boring"> search(&amp;config.query, &amp;contents)
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> for line in results {
</span><span class="boring"> println!("{line}");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search_case_insensitive&lt;'a&gt;(
</span><span class="boring"> query: &amp;str,
</span><span class="boring"> contents: &amp;'a str,
</span><span class="boring">) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let query = query.to_lowercase();
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.to_lowercase().contains(&amp;query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_sensitive() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Duct tape.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_insensitive() {
</span><span class="boring"> let query = "rUsT";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Trust me.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(
</span><span class="boring"> vec!["Rust:", "Trust me."],
</span><span class="boring"> search_case_insensitive(query, contents)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 12-23检查叫做 <code>IGNORE_CASE</code> 的环境变量</span></p>
<p>这里创建了一个新变量 <code>ignore_case</code>。为了设置它的值,需要调用 <code>env::var</code> 函数并传递我们需要寻找的环境变量名称,<code>IGNORE_CASE</code><code>env::var</code> 返回一个 <code>Result</code>,它在环境变量被设置时返回包含其值的 <code>Ok</code> 成员,并在环境变量未被设置时返回 <code>Err</code> 成员。</p>
<p>我们使用 <code>Result</code><code>is_ok</code> 方法来检查环境变量是否被设置,这也就意味着我们 <strong>需要</strong> 进行一个大小写不敏感的搜索。如果<code>IGNORE_CASE</code> 环境变量没有被设置为任何值,<code>is_ok</code> 会返回 false 并将进行大小写敏感的搜索。我们并不关心环境变量所设置的 <strong></strong>,只关心它是否被设置了,所以检查 <code>is_ok</code> 而不是 <code>unwrap</code><code>expect</code> 或任何我们已经见过的 <code>Result</code> 的方法。</p>
<p>我们将变量 <code>ignore_case</code> 的值传递给 <code>Config</code> 实例,这样 <code>run</code> 函数可以读取其值并决定是否调用 <code>search</code> 或者示例 12-22 中实现的 <code>search_case_insensitive</code></p>
<p>让我们试一试吧!首先不设置环境变量并使用查询 <code>to</code> 运行程序,这应该会匹配任何全小写的单词 “to” 的行:</p>
<pre><code class="language-console">$ cargo run -- to poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep to poem.txt`
Are you nobody, too?
How dreary to be somebody!
</code></pre>
<p>看起来程序仍然能够工作!现在将 <code>IGNORE_CASE</code> 设置为 <code>1</code> 并仍使用相同的查询 <code>to</code></p>
<pre><code class="language-console">$ IGNORE_CASE=1 cargo run to poem.txt
</code></pre>
<p>如果你使用 PowerShell则需要用两个命令来分别设置环境变量并运行程序</p>
<pre><code class="language-console">PS&gt; $Env:IGNORE_CASE=1; cargo run to poem.txt
</code></pre>
<p>而这会让 <code>IGNORE_CASE</code> 的效果在当前 shell 会话中持续生效。可以通过 <code>Remove-Item</code> 命令来取消设置:</p>
<pre><code class="language-console">PS&gt; Remove-Item Env:IGNORE_CASE
</code></pre>
<p>这回应该得到包含可能有大写字母的 “to” 的行:</p>
<pre><code class="language-console">Are you nobody, too?
How dreary to be somebody!
To tell your name the livelong day
To an admiring bog!
</code></pre>
<p>好极了,我们也得到了包含 “To” 的行!现在 <code>minigrep</code> 程序可以通过环境变量控制进行大小写不敏感搜索了。现在你知道了如何管理由命令行参数或环境变量设置的选项了!</p>
<p>一些程序允许对相同配置同时使用参数 <strong></strong> 环境变量。在这种情况下,程序来决定参数和环境变量的优先级。作为一个留给你的测试,尝试通过一个命令行参数或一个环境变量来控制大小写敏感搜索。并在运行程序时遇到矛盾值时决定命令行参数和环境变量的优先级。</p>
<p><code>std::env</code> 模块还包含了更多处理环境变量的实用功能;请查看官方文档来了解其可用的功能。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="将错误信息输出到标准错误而不是标准输出"><a class="header" href="#将错误信息输出到标准错误而不是标准输出">将错误信息输出到标准错误而不是标准输出</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch12-06-writing-to-stderr-instead-of-stdout.md">ch12-06-writing-to-stderr-instead-of-stdout.md</a>
<br>
commit 02a168ed346042f07010f8b65b4eeed623dd31d1</p>
</blockquote>
<p>目前为止,我们将所有的输出都通过 <code>println!</code> 写到了终端。大部分终端都提供了两种输出:<strong>标准输出</strong><em>standard output</em><code>stdout</code>)对应一般信息,<strong>标准错误</strong><em>standard error</em><code>stderr</code>)则用于错误信息。这种区别允许用户选择将程序正常输出定向到一个文件中并仍将错误信息打印到屏幕上。</p>
<p>但是 <code>println!</code> 宏只能够打印到标准输出,所以我们必须使用其他方法来打印到标准错误。</p>
<h3 id="检查错误应该写入何处"><a class="header" href="#检查错误应该写入何处">检查错误应该写入何处</a></h3>
<p>首先,让我们观察一下目前 <code>minigrep</code> 打印的所有内容是如何被写入标准输出的,包括那些应该被写入标准错误的错误信息。可以通过将标准输出流重定向到一个文件同时有意产生一个错误来做到这一点。我们没有重定向标准错误流,所以任何发送到标准错误的内容将会继续显示在屏幕上。</p>
<p>命令行程序被期望将错误信息发送到标准错误流,这样即便选择将标准输出流重定向到文件中时仍然能看到错误信息。目前我们的程序并不符合期望;相反我们将看到它将错误信息输出保存到了文件中!</p>
<p>我们通过 <code>&gt;</code> 和文件路径 <em>output.txt</em> 来运行程序,我们期望重定向标准输出流到该文件中。在这里,我们没有传递任何参数,所以会产生一个错误:</p>
<pre><code class="language-console">$ cargo run &gt; output.txt
</code></pre>
<p><code>&gt;</code> 语法告诉 shell 将标准输出的内容写入到 <em>output.txt</em> 文件中而不是屏幕上。我们并没有看到期望的错误信息打印到屏幕上,所以这意味着它一定被写入了文件中。如下是 <em>output.txt</em> 所包含的:</p>
<pre><code class="language-text">Problem parsing arguments: not enough arguments
</code></pre>
<p>是的,错误信息被打印到了标准输出中。像这样的错误信息被打印到标准错误中将会有用得多,将使得只有成功运行所产生的输出才会写入文件。我们接下来就修改。</p>
<h3 id="将错误打印到标准错误"><a class="header" href="#将错误打印到标准错误">将错误打印到标准错误</a></h3>
<p>让我们如示例 12-24 所示的代码改变错误信息是如何被打印的。得益于本章早些时候的重构,所有打印错误信息的代码都位于 <code>main</code> 一个函数中。标准库提供了 <code>eprintln!</code> 宏来打印到标准错误流,所以将两个调用 <code>println!</code> 打印错误信息的位置替换为 <code>eprintln!</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::process;
</span><span class="boring">
</span><span class="boring">use minigrep::Config;
</span><span class="boring">
</span>fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::build(&amp;args).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
if let Err(e) = minigrep::run(config) {
eprintln!("Application error: {e}");
process::exit(1);
}
}</code></pre>
<p><span class="caption">示例 12-24使用 <code>eprintln!</code> 将错误信息写入标准错误而不是标准输出</span></p>
<p>现在我们再次尝试用同样的方式运行程序,不使用任何参数并通过 <code>&gt;</code> 重定向标准输出:</p>
<pre><code class="language-console">$ cargo run &gt; output.txt
Problem parsing arguments: not enough arguments
</code></pre>
<p>现在我们看到了屏幕上的错误信息,同时 <em>output.txt</em> 里什么也没有,这正是命令行程序所期望的行为。</p>
<p>如果使用不会造成错误的参数再次运行程序,不过仍然将标准输出重定向到一个文件,像这样:</p>
<pre><code class="language-console">$ cargo run -- to poem.txt &gt; output.txt
</code></pre>
<p>我们并不会在终端看到任何输出,同时 <code>output.txt</code> 将会包含其结果:</p>
<p><span class="filename">文件名output.txt</span></p>
<pre><code class="language-text">Are you nobody, too?
How dreary to be somebody!
</code></pre>
<p>这一部分展示了现在我们适当的使用了成功时产生的标准输出和错误时产生的标准错误。</p>
<h2 id="总结-11"><a class="header" href="#总结-11">总结</a></h2>
<p>在这一章中,我们回顾了目前为止的一些主要章节并涉及了如何在 Rust 环境中进行常规的 I/O 操作。通过使用命令行参数、文件、环境变量和打印错误的 <code>eprintln!</code> 宏,现在你已经准备好编写命令行程序了。通过结合前几章的知识,你的代码将会是组织良好的,并能有效的将数据存储到合适的数据结构中、更好的处理错误,并且还是经过良好测试的。</p>
<p>接下来,让我们探索一些 Rust 中受函数式编程语言影响的功能:闭包和迭代器。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="rust-中的函数式语言功能迭代器与闭包"><a class="header" href="#rust-中的函数式语言功能迭代器与闭包">Rust 中的函数式语言功能:迭代器与闭包</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch13-00-functional-features.md">ch13-00-functional-features.md</a>
<br>
commit daa268a0cd04ef76a8067a26ed7d28ec2a9336d3</p>
</blockquote>
<p>Rust 的设计灵感来源于很多现存的语言和技术。其中一个显著的影响就是 <strong>函数式编程</strong><em>functional programming</em>)。函数式编程风格通常包含将函数作为参数值或其他函数的返回值、将函数赋值给变量以供之后执行等等。</p>
<p>本章我们不会讨论函数式编程是或不是什么的问题,而是展示 Rust 的一些在功能上与其他被认为是函数式语言类似的特性。</p>
<p>更具体的,我们将要涉及:</p>
<ul>
<li><strong>闭包</strong><em>Closures</em>),一个可以储存在变量里的类似函数的结构</li>
<li><strong>迭代器</strong><em>Iterators</em>),一种处理元素序列的方式</li>
<li>如何使用闭包和迭代器来改进第十二章的 I/O 项目。</li>
<li>闭包和迭代器的性能。(<strong>剧透警告:</strong> 它们的速度超乎你的想象!)</li>
</ul>
<p>我们已经介绍了其它受函数式风格影响的 Rust 功能,比如模式匹配和枚举,这些已经在其他章节中讲到过了。因为掌握闭包和迭代器是编写符合语言风格的高性能 Rust 代码的重要一环,所以我们将专门用一整章来讲解它们。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="闭包可以捕获环境的匿名函数"><a class="header" href="#闭包可以捕获环境的匿名函数">闭包:可以捕获环境的匿名函数</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch13-01-closures.md">ch13-01-closures.md</a>
<br>
commit a2cb72d3ad7584cc1ae3b85f715c877872f5e3ab</p>
</blockquote>
<p>Rust 的 <strong>闭包</strong><em>closures</em>)是可以保存在变量中或作为参数传递给其他函数的匿名函数。你可以在一个地方创建闭包,然后在不同的上下文中执行闭包运算。不同于函数,闭包允许捕获其被定义时所在作用域中的值。我们将展示这些闭包特性如何支持代码复用和行为定制。</p>
<h3 id="闭包会捕获其环境"><a class="header" href="#闭包会捕获其环境">闭包会捕获其环境</a></h3>
<p>我们首先了解如何通过闭包捕获定义它的环境中的值以便之后使用。考虑如下场景:我们的 T 恤公司偶尔会向邮件列表中的某位成员赠送一件限量版的独家 T 恤作为促销。邮件列表中的成员可以选择将他们的喜爱的颜色添加到个人信息中。如果被选中的成员设置了喜爱的颜色,他们将获得那个颜色的 T 恤。如果他没有设置喜爱的颜色,他们会获赠公司当前库存最多的颜色的款式。</p>
<p>有很多种方式来实现这一点。例如,使用有 <code>Red</code><code>Blue</code> 两个成员的 <code>ShirtColor</code> 枚举(出于简单考虑限定为两种颜色)。我们使用 <code>Inventory</code> 结构体来代表公司的库存,它有一个类型为 <code>Vec&lt;ShirtColor&gt;</code><code>shirts</code> 字段表示库存中的衬衫的颜色。<code>Inventory</code> 上定义的 <code>giveaway</code> 方法获取免费衬衫得主所喜爱的颜色(如有),并返回其获得的衬衫的颜色。初始代码如示例 13-1 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust noplayground">#[derive(Debug, PartialEq, Copy, Clone)]
enum ShirtColor {
Red,
Blue,
}
struct Inventory {
shirts: Vec&lt;ShirtColor&gt;,
}
impl Inventory {
fn giveaway(&amp;self, user_preference: Option&lt;ShirtColor&gt;) -&gt; ShirtColor {
user_preference.unwrap_or_else(|| self.most_stocked())
}
fn most_stocked(&amp;self) -&gt; ShirtColor {
let mut num_red = 0;
let mut num_blue = 0;
for color in &amp;self.shirts {
match color {
ShirtColor::Red =&gt; num_red += 1,
ShirtColor::Blue =&gt; num_blue += 1,
}
}
if num_red &gt; num_blue {
ShirtColor::Red
} else {
ShirtColor::Blue
}
}
}
fn main() {
let store = Inventory {
shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue],
};
let user_pref1 = Some(ShirtColor::Red);
let giveaway1 = store.giveaway(user_pref1);
println!(
"The user with preference {:?} gets {:?}",
user_pref1, giveaway1
);
let user_pref2 = None;
let giveaway2 = store.giveaway(user_pref2);
println!(
"The user with preference {:?} gets {:?}",
user_pref2, giveaway2
);
}</code></pre>
<p><span class="caption">示例 13-1衬衫公司赠送场景</span></p>
<p><code>main</code> 函数中定义的 <code>store</code> 还剩下两件蓝衬衫和一件红衬衫,可以在限量版促销活动中赠送。我们通过调用 <code>giveaway</code> 方法,为一个期望红衬衫的用户和一个没有特定偏好的用户进行赠送。</p>
<p>再次强调,这段代码有多种实现方式。这里为了专注于闭包,我们继续使用已经学习过的概念,除了 <code>giveaway</code> 方法体中使用了闭包。在 <code>giveaway</code> 方法中,我们将用户偏好作为 <code>Option&lt;ShirtColor&gt;</code> 类型的参数获取,并在 <code>user_preference</code> 上调用 <code>unwrap_or_else</code> 方法。<a href="https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap_or_else"><code>Option&lt;T&gt;</code> 上的 <code>unwrap_or_else</code> 方法</a> 由标准库定义。它接受一个无参闭包作为参数,该闭包返回一个 <code>T</code> 类型的值(与 <code>Option&lt;T&gt;</code><code>Some</code> 变体中存储的值类型相同,这里是 <code>ShirtColor</code>)。如果 <code>Option&lt;T&gt;</code><code>Some</code> 成员,则 <code>unwrap_or_else</code> 返回 <code>Some</code> 中的值。如果 <code>Option&lt;T&gt;</code><code>None</code> 成员,则 <code>unwrap_or_else</code> 调用闭包并返回闭包的返回值。</p>
<p>我们将闭包表达式 <code>|| self.most_stocked()</code> 作为 <code>unwrap_or_else</code> 的参数。这是一个本身不获取参数的闭包(如果闭包有参数,它们会出现在两道竖杠之间)。闭包体调用了 <code>self.most_stocked()</code>。我们在这里定义了闭包,而 <code>unwrap_or_else</code> 的实现会在之后需要其结果的时候执行闭包。</p>
<p>运行代码会打印出:</p>
<pre><code class="language-console">$ cargo run
Compiling shirt-company v0.1.0 (file:///projects/shirt-company)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s
Running `target/debug/shirt-company`
The user with preference Some(Red) gets Red
The user with preference None gets Blue
</code></pre>
<p>这里有一个有趣的地方是,我们传递了一个闭包,该闭包会在当前的 <code>Inventory</code> 实例上调用 <code>self.most_stocked()</code> 方法。标准库不需要了解我们定义的 <code>Inventory</code><code>ShirtColor</code> 类型,也不需要了解我们在这个场景中要使用的逻辑。闭包捕获了对 <code>self</code>(即 <code>Inventory</code> 实例)的不可变引用,并将其与我们指定的代码一起传递给 <code>unwrap_or_else</code> 方法。相比之下,函数无法以这种方式捕获其环境。</p>
<h3 id="闭包类型推断和注解"><a class="header" href="#闭包类型推断和注解">闭包类型推断和注解</a></h3>
<p>函数与闭包还有更多区别。闭包通常不要求像 <code>fn</code> 函数那样对参数和返回值进行类型注解。函数需要类型注解是因为这些类型是暴露给用户的显式接口的一部分。严格定义这些接口对于确保所有人对函数使用和返回值的类型达成一致理解非常重要。与此相比,闭包并不用于这样暴露在外的接口:它们储存在变量中并被使用,不用命名它们或暴露给库的用户调用。</p>
<p>闭包通常较短,并且只与特定的上下文相关,而不是适用于任意情境。在这些有限的上下文中,编译器可以推断参数和返回值的类型,类似于它推断大多数变量类型的方式(尽管在某些罕见的情况下,编译器也需要闭包的类型注解)。</p>
<p>类似于变量,如果我们希望增加代码的明确性和清晰度,可以添加类型注解,但代价是是会使代码变得比严格必要的更冗长。为示例 13-1 中定义的闭包标注类型看起来如示例 13-2 中的定义一样。这个例子中,我们定义了一个闭包并将它保存在变量中,而不是像示例 13-1 那样在传参的地方定义它。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">use std::thread;
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn generate_workout(intensity: u32, random_number: u32) {
</span> let expensive_closure = |num: u32| -&gt; u32 {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
};
<span class="boring">
</span><span class="boring"> if intensity &lt; 25 {
</span><span class="boring"> println!("Today, do {} pushups!", expensive_closure(intensity));
</span><span class="boring"> println!("Next, do {} situps!", expensive_closure(intensity));
</span><span class="boring"> } else {
</span><span class="boring"> if random_number == 3 {
</span><span class="boring"> println!("Take a break today! Remember to stay hydrated!");
</span><span class="boring"> } else {
</span><span class="boring"> println!(
</span><span class="boring"> "Today, run for {} minutes!",
</span><span class="boring"> expensive_closure(intensity)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let simulated_user_specified_value = 10;
</span><span class="boring"> let simulated_random_number = 7;
</span><span class="boring">
</span><span class="boring"> generate_workout(simulated_user_specified_value, simulated_random_number);
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 13-2为闭包的参数和返回值增加可选的类型注解</span></p>
<p>有了类型注解,闭包的语法看起来就更像函数的语法了。如下是一个对其参数加一的函数的定义与拥有相同行为闭包语法的纵向对比。这里增加了一些空格来对齐相应部分。这展示了除了使用竖线以及一些可选语法外,闭包语法与函数语法有多么地相似:</p>
<pre><code class="language-rust ignore">fn add_one_v1 (x: u32) -&gt; u32 { x + 1 }
let add_one_v2 = |x: u32| -&gt; u32 { x + 1 };
let add_one_v3 = |x| { x + 1 };
let add_one_v4 = |x| x + 1 ;</code></pre>
<p>第一行展示了一个函数定义,第二行展示了一个完整标注的闭包定义。第三行闭包定义中省略了类型注解,而第四行去掉了可选的大括号,因为闭包体只有一个表达式,所以大括号是可选的。这些都是有效的闭包定义,并在调用时产生相同的行为。调用闭包是 <code>add_one_v3</code><code>add_one_v4</code> 能够编译的必要条件,因为类型将从其用法中推断出来。这类似于 <code>let v = Vec::new();</code>Rust 需要类型注解或是某种类型的值被插入到 <code>Vec</code> 中,才能推断其类型。</p>
<p>对于闭包定义,编译器会为每个参数和返回值推断出一个具体类型。例如,示例 13-3 展示了一个简短的闭包定义,该闭包仅仅返回作为参数接收到的值。除了作为示例用途外,这个闭包并不是很实用。注意这个定义没有增加任何类型注解。因为没有类型注解,我们可以使用任意类型来调用这个闭包,我们在这里第一次调用时使用了 <code>String</code> 类型。但是如果我们接着尝试使用整数来调用 <code>example_closure</code>,就会得到一个错误。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let example_closure = |x| x;
let s = example_closure(String::from("hello"));
let n = example_closure(5);
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 13-3尝试调用一个被推断为两个不同类型的闭包</span></p>
<p>编译器给出如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling closure-example v0.1.0 (file:///projects/closure-example)
error[E0308]: mismatched types
--&gt; src/main.rs:5:29
|
5 | let n = example_closure(5);
| --------------- ^- help: try using a conversion method: `.to_string()`
| | |
| | expected `String`, found integer
| arguments to this function are incorrect
|
note: expected because the closure was earlier called with an argument of type `String`
--&gt; src/main.rs:4:29
|
4 | let s = example_closure(String::from("hello"));
| --------------- ^^^^^^^^^^^^^^^^^^^^^ expected because this argument is of type `String`
| |
| in this closure call
note: closure parameter defined here
--&gt; src/main.rs:2:28
|
2 | let example_closure = |x| x;
| ^
For more information about this error, try `rustc --explain E0308`.
error: could not compile `closure-example` (bin "closure-example") due to 1 previous error
</code></pre>
<p>第一次使用 <code>String</code> 值调用 <code>example_closure</code> 时,编译器推断出 <code>x</code> 的类型以及闭包的返回类型为 <code>String</code>。接着这些类型被锁定进闭包 <code>example_closure</code> 中,如果尝试对同一闭包使用不同类型则就会得到类型错误。</p>
<h3 id="捕获引用或者移动所有权"><a class="header" href="#捕获引用或者移动所有权">捕获引用或者移动所有权</a></h3>
<p>闭包可以通过三种方式捕获其环境中的值,它们直接对应到函数获取参数的三种方式:不可变借用、可变借用和获取所有权。闭包将根据函数体中对捕获值的操作来决定使用哪种方式。</p>
<p>在示例 13-4 中定义了一个捕获名为 <code>list</code> 的 vector 的不可变引用的闭包,因为只需不可变引用就能打印其值:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let list = vec![1, 2, 3];
println!("Before defining closure: {list:?}");
let only_borrows = || println!("From closure: {list:?}");
println!("Before calling closure: {list:?}");
only_borrows();
println!("After calling closure: {list:?}");
}</code></pre></pre>
<p><span class="caption">示例 13-4定义并调用一个捕获不可变引用的闭包</span></p>
<p>这个示例也展示了变量可以绑定一个闭包定义,并且我们可以像使用函数名一样,使用变量名和括号来调用该闭包。</p>
<p>因为同时可以有多个 <code>list</code> 的不可变引用,所以在闭包定义之前,闭包定义之后调用之前,闭包调用之后代码仍然可以访问 <code>list</code>。该代码可以编译、运行并输出:</p>
<pre><code class="language-console">$ cargo run
Locking 1 package to latest compatible version
Adding closure-example v0.1.0 (/Users/chris/dev/rust-lang/book/tmp/listings/ch13-functional-features/listing-13-04)
Compiling closure-example v0.1.0 (file:///projects/closure-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/closure-example`
Before defining closure: [1, 2, 3]
Before calling closure: [1, 2, 3]
From closure: [1, 2, 3]
After calling closure: [1, 2, 3]
</code></pre>
<p>接下来在示例 13-5 中,我们修改闭包体让它向 <code>list</code> vector 增加一个元素。闭包现在捕获一个可变引用:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let mut list = vec![1, 2, 3];
println!("Before defining closure: {list:?}");
let mut borrows_mutably = || list.push(7);
borrows_mutably();
println!("After calling closure: {list:?}");
}</code></pre></pre>
<p><span class="caption">示例 13-5定义并调用一个捕获可变引用的闭包</span></p>
<p>代码可以编译、运行并打印:</p>
<pre><code class="language-console">$ cargo run
Locking 1 package to latest compatible version
Adding closure-example v0.1.0 (/Users/chris/dev/rust-lang/book/tmp/listings/ch13-functional-features/listing-13-05)
Compiling closure-example v0.1.0 (file:///projects/closure-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/closure-example`
Before defining closure: [1, 2, 3]
After calling closure: [1, 2, 3, 7]
</code></pre>
<p>注意在 <code>borrows_mutably</code> 闭包的定义和调用之间不再有 <code>println!</code>,这是因为当 <code>borrows_mutably</code> 被定义时,它捕获了对 <code>list</code> 的可变引用。闭包在被调用后就不再被使用,这时可变借用结束。因为当可变借用存在时不允许有其它的借用,所以在闭包定义和调用之间不能有不可变引用来进行打印。可以尝试在这里添加 <code>println!</code> 看看你会得到什么报错信息!</p>
<p>即使闭包体不严格需要所有权,如果希望强制闭包获取它在环境中所使用的值的所有权,可以在参数列表前使用 <code>move</code> 关键字。</p>
<p>当将闭包传递到一个新的线程时,这个技巧特别有用,因为它将数据的所有权移动到新线程中。我们将在第十六章讨论并发时详细讨论线程以及为什么你可能需要使用它们。不过现在,我们先简要探索一下如何使用需要 <code>move</code> 关键字的闭包来生成一个新线程。示例 13-6 展示了如何修改示例 13-4以便在一个新线程中而不是在主线程中打印 vector</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::thread;
fn main() {
let list = vec![1, 2, 3];
println!("Before defining closure: {list:?}");
thread::spawn(move || println!("From thread: {list:?}"))
.join()
.unwrap();
}</code></pre></pre>
<p><span class="caption">示例 13-6使用 <code>move</code> 来强制闭包为线程获取 <code>list</code> 的所有权</span></p>
<p>我们生成了一个新的线程,并给这个线程传递一个闭包作为参数来运行,闭包体打印出列表。在示例 13-4 中,闭包仅通过不可变引用捕获了 <code>list</code>,因为这是打印列表所需的最少的访问权限。这个例子中,尽管闭包体依然只需要不可变引用,我们还是在闭包定义前写上 <code>move</code> 关键字,以确保 <code>list</code> 被移动到闭包中。新线程可能在主线程剩余部分执行完前执行完,也可能在主线程执行完之后执行完。如果主线程维护了 <code>list</code> 的所有权但却在新线程之前结束并且丢弃了 <code>list</code>,则在线程中的不可变引用将失效。因此,编译器要求 <code>list</code> 被移动到在新线程中运行的闭包中,这样引用就是有效的。试着移除 <code>move</code> 关键字,或者在闭包定义后在主线程中使用 <code>list</code>,看看你会得到什么编译器报错!</p>
<p><a id="storing-closures-using-generic-parameters-and-the-fn-traits"></a>
<a id="limitations-of-the-cacher-implementation"></a>
<a id="moving-captured-values-out-of-the-closure-and-the-fn-traits"></a></p>
<h3 id="将被捕获的值移出闭包和-fn-trait"><a class="header" href="#将被捕获的值移出闭包和-fn-trait">将被捕获的值移出闭包和 <code>Fn</code> trait</a></h3>
<p>一旦闭包捕获了定义它的环境中的某个值的引用或所有权(也就影响了什么会被移 <em></em> 闭包,如有),闭包体中的代码则决定了在稍后执行闭包时,这些引用或值将如何处理(也就影响了什么会被移 <em></em> 闭包,如有)。闭包体可以执行以下任一操作:将一个捕获的值移出闭包,修改捕获的值,既不移动也不修改值,或者一开始就不从环境中捕获任何值。</p>
<p>闭包捕获和处理环境中的值的方式会影响闭包实现哪些 trait而 trait 是函数和结构体指定它们可以使用哪些类型闭包的方式。根据闭包体如何处理这些值,闭包会自动、渐进地实现一个、两个或全部三个 <code>Fn</code> trait。</p>
<ol>
<li><code>FnOnce</code> 适用于只能被调用一次的闭包。所有闭包至少都实现了这个 trait因为所有闭包都能被调用。一个会将捕获的值从闭包体中移出的闭包只会实现 <code>FnOnce</code> trait而不会实现其他 <code>Fn</code> 相关的 trait因为它只能被调用一次。</li>
<li><code>FnMut</code> 适用于不会将捕获的值移出闭包体,但可能会修改捕获值的闭包。这类闭包可以被调用多次。</li>
<li><code>Fn</code> 适用于既不将捕获的值移出闭包体,也不修改捕获值的闭包,同时也包括不从环境中捕获任何值的闭包。这类闭包可以被多次调用而不会改变其环境,这在会多次并发调用闭包的场景中十分重要。</li>
</ol>
<p>让我们来看示例 13-1 中使用的在 <code>Option&lt;T&gt;</code> 上的 <code>unwrap_or_else</code> 方法的定义:</p>
<pre><code class="language-rust ignore">impl&lt;T&gt; Option&lt;T&gt; {
pub fn unwrap_or_else&lt;F&gt;(self, f: F) -&gt; T
where
F: FnOnce() -&gt; T
{
match self {
Some(x) =&gt; x,
None =&gt; f(),
}
}
}</code></pre>
<p>回忆一下,<code>T</code> 是表示 <code>Option</code><code>Some</code> 成员中的值的类型的泛型。类型 <code>T</code> 也是 <code>unwrap_or_else</code> 函数的返回值类型:举例来说,在 <code>Option&lt;String&gt;</code> 上调用 <code>unwrap_or_else</code> 会得到一个 <code>String</code></p>
<p>接着注意到 <code>unwrap_or_else</code> 函数有额外的泛型参数 <code>F</code><code>F</code> 是参数 <code>f</code> 的类型,<code>f</code> 是调用 <code>unwrap_or_else</code> 时提供的闭包。</p>
<p>泛型 <code>F</code> 的 trait bound 是 <code>FnOnce() -&gt; T</code>,这意味着 <code>F</code> 必须能够被调用一次,没有参数并返回一个 <code>T</code>。在 trait bound 中使用 <code>FnOnce</code> 表示 <code>unwrap_or_else</code> 最多只会调用 <code>f</code> 一次。在 <code>unwrap_or_else</code> 的函数体中可以看到,如果 <code>Option</code><code>Some</code><code>f</code> 不会被调用。如果 <code>Option</code><code>None</code><code>f</code> 将会被调用一次。由于所有的闭包都实现了 <code>FnOnce</code><code>unwrap_or_else</code> 接受所有三种类型的闭包,十分灵活。</p>
<blockquote>
<p>注意:函数也可以实现所有的三种 <code>Fn</code> traits。如果我们要做的事情不需要从环境中捕获值则可以在需要某种实现了 <code>Fn</code> trait 的东西时使用函数而不是闭包。举个例子,可以在 <code>Option&lt;Vec&lt;T&gt;&gt;</code> 的值上调用 <code>unwrap_or_else(Vec::new)</code>,以便在值为 <code>None</code> 时获取一个新的空的 vector。</p>
</blockquote>
<p>现在让我们来看定义在 slice 上的标准库方法 <code>sort_by_key</code>,看看它与 <code>unwrap_or_else</code> 的区别,以及为什么 <code>sort_by_key</code> 使用 <code>FnMut</code> 而不是 <code>FnOnce</code> 作为 trait bound。这个闭包以一个 slice 中当前被考虑的元素的引用作为参数,并返回一个可以排序的 <code>K</code> 类型的值。当你想按照 slice 中每个元素的某个属性进行排序时,这个函数非常有用。在示例 13-7 中,我们有一个 <code>Rectangle</code> 实例的列表,并使用 <code>sort_by_key</code><code>Rectangle</code><code>width</code> 属性对它们从低到高排序:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust noplayground">#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let mut list = [
Rectangle { width: 10, height: 1 },
Rectangle { width: 3, height: 5 },
Rectangle { width: 7, height: 12 },
];
list.sort_by_key(|r| r.width);
println!("{list:#?}");
}</code></pre>
<p><span class="caption">示例 13-7使用 <code>sort_by_key</code> 对长方形按宽度排序</span></p>
<p>代码输出:</p>
<pre><code class="language-console">$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.41s
Running `target/debug/rectangles`
[
Rectangle {
width: 3,
height: 5,
},
Rectangle {
width: 7,
height: 12,
},
Rectangle {
width: 10,
height: 1,
},
]
</code></pre>
<p><code>sort_by_key</code> 被定义为接收一个 <code>FnMut</code> 闭包的原因是它会多次调用这个闭包:对 slice 中的每个元素调用一次。闭包 <code>|r| r.width</code> 不捕获、修改或将任何东西移出它的环境,所以它满足 trait bound 的要求。</p>
<p>相比之下,示例 13-8 展示了一个只实现了 <code>FnOnce</code> trait 的闭包的例子,因为它从环境中移出了一个值。编译器不允许我们在 <code>sort_by_key</code> 中使用这个闭包:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let mut list = [
Rectangle { width: 10, height: 1 },
Rectangle { width: 3, height: 5 },
Rectangle { width: 7, height: 12 },
];
let mut sort_operations = vec![];
let value = String::from("closure called");
list.sort_by_key(|r| {
sort_operations.push(value);
r.width
});
println!("{list:#?}");
}</code></pre>
<p><span class="caption">示例 13-8尝试在 <code>sort_by_key</code> 上使用一个 <code>FnOnce</code> 闭包</span></p>
<p>这是一个刻意构造的、复杂且无效的方式,试图统计在对 <code>list</code> 进行排序时 <code>sort_by_key</code> 调用闭包的次数。该代码试图通过将闭包环境中的 <code>value</code>(一个 <code>String</code>)插入 <code>sort_operations</code> vector 来实现计数。闭包捕获了 <code>value</code>,然后通过将 <code>value</code> 的所有权转移给 <code>sort_operations</code> vector 的方式将其移出闭包。这个闭包只能被调用一次;尝试第二次调用它将无法工作,因为这时 <code>value</code> 已经不在闭包的环境中,无法被再次插入 <code>sort_operations</code> 中!因而,这个闭包只实现了 <code>FnOnce</code>。当我们尝试编译此代码时,会出现错误提示:<code>value</code> 不能从闭包中移出,因为闭包必须实现 <code>FnMut</code></p>
<pre><code class="language-console">$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure
--&gt; src/main.rs:18:30
|
15 | let value = String::from("closure called");
| ----- captured outer variable
16 |
17 | list.sort_by_key(|r| {
| --- captured by this `FnMut` closure
18 | sort_operations.push(value);
| ^^^^^ move occurs because `value` has type `String`, which does not implement the `Copy` trait
|
help: consider cloning the value if the performance cost is acceptable
|
18 | sort_operations.push(value.clone());
| ++++++++
For more information about this error, try `rustc --explain E0507`.
error: could not compile `rectangles` (bin "rectangles") due to 1 previous error
</code></pre>
<p>报错指向了闭包体中将 <code>value</code> 移出环境的那一行。要修复此问题,我们需要修改闭包体,使其不会将值移出环境。在环境中维护一个计数器,并在闭包体中递增其值,是计算闭包被调用次数的一个更简单直接的方法。示例 13-9 中的闭包可以在 <code>sort_by_key</code> 中使用,因为它只捕获了 <code>num_sort_operations</code> 计数器的可变引用,因此可以被多次调用:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust noplayground">#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let mut list = [
Rectangle { width: 10, height: 1 },
Rectangle { width: 3, height: 5 },
Rectangle { width: 7, height: 12 },
];
let mut num_sort_operations = 0;
list.sort_by_key(|r| {
num_sort_operations += 1;
r.width
});
println!("{list:#?}, sorted in {num_sort_operations} operations");
}</code></pre>
<p><span class="caption">示例 13-9允许在 <code>sort_by_key</code> 上使用一个 <code>FnMut</code> 闭包</span></p>
<p>当定义或使用涉及闭包的函数或类型时,<code>Fn</code> traits 十分重要。在下个小节中,我们将讨论迭代器。许多迭代器方法都接收闭包参数,因此在继续前,请记住这些闭包的细节!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用迭代器处理元素序列"><a class="header" href="#使用迭代器处理元素序列">使用迭代器处理元素序列</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch13-02-iterators.md">ch13-02-iterators.md</a>
<br>
commit eabaaaa90ee6937db3690dc56f739116be55ecb2</p>
</blockquote>
<p>迭代器模式允许你依次对一个序列中的项执行某些操作。<strong>迭代器</strong><em>iterator</em>)负责遍历序列中的每一项并确定序列何时结束的逻辑。使用迭代器时,你无需自己重新实现这些逻辑。</p>
<p>在 Rust 中,迭代器是 <strong>惰性的</strong><em>lazy</em>),这意味着在调用消费迭代器的方法之前不会执行任何操作。例如,示例 13-10 中的代码通过调用定义于 <code>Vec&lt;T&gt;</code> 上的 <code>iter</code> 方法在一个 vector <code>v1</code> 上创建了一个迭代器。这段代码本身并没有执行任何有用的操作。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 13-10创建一个迭代器</span></p>
<p>迭代器被储存在 <code>v1_iter</code> 变量中。一旦创建迭代器之后,可以选择用多种方式利用它。在第三章的示例 3-5 中,我们使用 <code>for</code> 循环来遍历一个数组并在每一个项上执行了一些代码。在底层它隐式地创建并接着消费了一个迭代器,不过直到现在我们都一笔带过了它具体是如何工作的。</p>
<p>示例 13-11 中的例子将迭代器的创建和 <code>for</code> 循环中的使用分开。当 <code>for</code> 循环使用 <code>v1_iter</code> 中的迭代器时,迭代器中的每一个元素都会用于循环的一次迭代,并打印出每个值。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
for val in v1_iter {
println!("Got: {val}");
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 13-11在一个 <code>for</code> 循环中使用迭代器</span></p>
<p>在标准库中没有提供迭代器的语言中,我们可能会使用一个从 0 开始的索引变量,使用这个变量索引 vector 中的值,并循环增加其值直到达到 vector 中的元素总量。</p>
<p>迭代器为我们处理了所有这些逻辑,这减少了重复代码并消除了潜在的混乱。另外,迭代器的实现方式提供了对多种不同的序列使用相同逻辑的灵活性,而不仅仅是像 vector 这样可索引的数据结构。让我们看看迭代器是如何做到这些的。</p>
<h3 id="iterator-trait-和-next-方法"><a class="header" href="#iterator-trait-和-next-方法"><code>Iterator</code> trait 和 <code>next</code> 方法</a></h3>
<p>迭代器都实现了一个叫做 <code>Iterator</code> 的定义于标准库的 trait。这个 trait 的定义看起来像这样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait Iterator {
type Item;
fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt;;
// 此处省略了方法的默认实现
}
<span class="boring">}</span></code></pre></pre>
<p>注意这里有一个我们还未讲到的新语法:<code>type Item</code><code>Self::Item</code>,它们定义了 trait 的 <strong>关联类型</strong><em>associated type</em>)。第二十章会深入讲解关联类型,不过现在只需知道这段代码表明实现 <code>Iterator</code> trait 要求同时定义一个 <code>Item</code> 类型,这个 <code>Item</code> 类型被用作 <code>next</code> 方法的返回值类型。换句话说,<code>Item</code> 类型将是迭代器返回元素的类型。</p>
<p><code>next</code><code>Iterator</code> 实现者被要求定义的唯一方法:<code>next</code> 方法,该方法每次返回迭代器中的一个项,封装在 <code>Some</code> 中,并且当迭代完成时,返回 <code>None</code></p>
<p>可以直接调用迭代器的 <code>next</code> 方法;示例 13-12 展示了对由 vector 创建的迭代器重复调用 <code>next</code> 方法时返回的值。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span> #[test]
fn iterator_demonstration() {
let v1 = vec![1, 2, 3];
let mut v1_iter = v1.iter();
assert_eq!(v1_iter.next(), Some(&amp;1));
assert_eq!(v1_iter.next(), Some(&amp;2));
assert_eq!(v1_iter.next(), Some(&amp;3));
assert_eq!(v1_iter.next(), None);
}
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 13-12在迭代器上直接调用 <code>next</code> 方法</span></p>
<p>注意我们需要将 <code>v1_iter</code> 声明为可变的:在迭代器上调用 <code>next</code> 方法会改变迭代器内部的状态,该状态用于跟踪迭代器在序列中的位置。换句话说,代码 <strong>消费</strong>consume或者说用尽了迭代器。每一次 <code>next</code> 调用都会从迭代器中消费一个项。使用 <code>for</code> 循环时无需使 <code>v1_iter</code> 可变因为 <code>for</code> 循环会获取 <code>v1_iter</code> 的所有权并在后台使 <code>v1_iter</code> 可变。</p>
<p>还需要注意的是,从 <code>next</code> 调用中获取的值是对 vector 中值的不可变引用。<code>iter</code> 方法生成一个不可变引用的迭代器。如果我们需要一个获取 <code>v1</code> 所有权并返回拥有所有权的迭代器,则可以调用 <code>into_iter</code> 而不是 <code>iter</code>。类似地,如果我们希望迭代可变引用,可以调用 <code>iter_mut</code> 而不是 <code>iter</code></p>
<h3 id="消费迭代器的方法"><a class="header" href="#消费迭代器的方法">消费迭代器的方法</a></h3>
<p><code>Iterator</code> trait 有一系列不同的由标准库提供默认实现的方法;你可以在 <code>Iterator</code> trait 的标准库 API 文档中找到所有这些方法。一些方法在其定义中调用了 <code>next</code> 方法,这也就是为什么在实现 <code>Iterator</code> trait 时要求实现 <code>next</code> 方法的原因。</p>
<p>这些调用 <code>next</code> 方法的方法被称为 <strong>消费适配器</strong><em>consuming adaptors</em>),因为调用它们会消耗迭代器。一个消费适配器的例子是 <code>sum</code> 方法。这个方法获取迭代器的所有权并反复调用 <code>next</code> 来遍历迭代器,因而会消费迭代器。在遍历过程中,它将每个项累加到一个总和中,并在迭代完成时返回这个总和。示例 13-13 有一个展示 <code>sum</code> 方法使用的测试:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span> #[test]
fn iterator_sum() {
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
let total: i32 = v1_iter.sum();
assert_eq!(total, 6);
}
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 13-13调用 <code>sum</code> 方法获取迭代器所有项的总和</span></p>
<p>调用 <code>sum</code> 之后不再允许使用 <code>v1_iter</code> 因为调用 <code>sum</code> 时它会获取迭代器的所有权。</p>
<h3 id="产生其他迭代器的方法"><a class="header" href="#产生其他迭代器的方法">产生其他迭代器的方法</a></h3>
<p><code>Iterator</code> trait 中定义了另一类方法,被称为 <strong>迭代器适配器</strong><em>iterator adaptors</em>),它们不会消耗当前的迭代器,而是通过改变原始迭代器的某些方面来生成不同的迭代器。</p>
<p>示例 13-14 展示了一个调用迭代器适配器方法 <code>map</code> 的例子,该方法使用一个闭包对每个元素进行操作。<code>map</code> 方法返回一个新的迭代器,该迭代器生成经过修改的元素。这里的闭包创建了一个新的迭代器,其中 vector 中的每个元素都被加 1。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust not_desired_behavior edition2021"><span class="boring">fn main() {
</span> let v1: Vec&lt;i32&gt; = vec![1, 2, 3];
v1.iter().map(|x| x + 1);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 13-14调用迭代器适配器 <code>map</code> 来创建一个新迭代器</span></p>
<p>不过这些代码会产生一个警告:</p>
<pre><code class="language-console">$ cargo run
Compiling iterators v0.1.0 (file:///projects/iterators)
warning: unused `Map` that must be used
--&gt; src/main.rs:4:5
|
4 | v1.iter().map(|x| x + 1);
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: iterators are lazy and do nothing unless consumed
= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
|
4 | let _ = v1.iter().map(|x| x + 1);
| +++++++
warning: `iterators` (bin "iterators") generated 1 warning
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.47s
Running `target/debug/iterators`
</code></pre>
<p>示例 13-14 中的代码实际上并没有做任何事;所指定的闭包从未被调用过。警告提醒了我们原因所在:迭代器适配器是惰性的,因此我们需要在此处消费迭代器。</p>
<p>为了修复这个警告并消费迭代器,我们将使用第十二章示例 12-1 结合 <code>env::args</code> 使用的 <code>collect</code> 方法。这个方法消费迭代器并将结果收集到一个集合数据类型中。</p>
<p>在示例 13-15 中,我们将遍历由 <code>map</code> 调用生成的迭代器结果收集到一个 vector 中。这个 vector 将包含原始 vector 中每个元素加 1 的结果。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let v1: Vec&lt;i32&gt; = vec![1, 2, 3];
let v2: Vec&lt;_&gt; = v1.iter().map(|x| x + 1).collect();
assert_eq!(v2, vec![2, 3, 4]);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 13-15调用 <code>map</code> 方法创建一个新迭代器,接着调用 <code>collect</code> 方法消费新迭代器并创建一个 vector</span></p>
<p>由于 <code>map</code> 接受一个闭包,因此我们可以指定希望在每个元素上执行的任何操作。这是一个很好的例子,展示了如何通过闭包来自定义某些行为,同时复用 <code>Iterator</code> trait 提供的迭代行为。</p>
<p>可以链式调用多个迭代器适配器来以一种可读的方式进行复杂的操作。不过因为所有的迭代器都是惰性的,你必须调用一个消费适配器方法,才能从这些迭代器适配器的调用中获取结果。</p>
<h3 id="使用捕获其环境的闭包"><a class="header" href="#使用捕获其环境的闭包">使用捕获其环境的闭包</a></h3>
<p>很多迭代器适配器接受闭包作为参数,而我们通常会指定捕获其环境的闭包作为迭代器适配器的参数。</p>
<p>作为一个例子,我们使用 <code>filter</code> 方法来获取一个闭包。该闭包从迭代器中获取一项并返回一个 <code>bool</code>。如果闭包返回 <code>true</code>,其值将会包含在 <code>filter</code> 提供的新迭代器中。如果闭包返回 <code>false</code>,其值不会被包含。</p>
<p>示例 13-16 中使用 <code>filter</code> 和一个捕获环境中变量 <code>shoe_size</code> 的闭包来遍历一个 <code>Shoe</code> 结构体集合。它只会返回指定鞋码的鞋子。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">#[derive(PartialEq, Debug)]
struct Shoe {
size: u32,
style: String,
}
fn shoes_in_size(shoes: Vec&lt;Shoe&gt;, shoe_size: u32) -&gt; Vec&lt;Shoe&gt; {
shoes.into_iter().filter(|s| s.size == shoe_size).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filters_by_size() {
let shoes = vec![
Shoe {
size: 10,
style: String::from("sneaker"),
},
Shoe {
size: 13,
style: String::from("sandal"),
},
Shoe {
size: 10,
style: String::from("boot"),
},
];
let in_my_size = shoes_in_size(shoes, 10);
assert_eq!(
in_my_size,
vec![
Shoe {
size: 10,
style: String::from("sneaker")
},
Shoe {
size: 10,
style: String::from("boot")
},
]
);
}
}</code></pre>
<p><span class="caption">示例 13-16使用 <code>filter</code> 方法和一个捕获 <code>shoe_size</code> 的闭包</span></p>
<p><code>shoes_in_size</code> 函数获取一个鞋子 vector 的所有权和一个鞋码作为参数。它返回一个只包含指定鞋码的鞋子的 vector。</p>
<p><code>shoes_in_size</code> 函数体中调用了 <code>into_iter</code> 来创建一个获取 vector 所有权的迭代器。接着调用 <code>filter</code> 将这个迭代器适配成一个只含有那些闭包返回 <code>true</code> 的元素的新迭代器。</p>
<p>闭包从环境中捕获了 <code>shoe_size</code> 变量并使用其值与每一只鞋的大小作比较,只保留指定鞋码的鞋子。最终,调用 <code>collect</code> 将迭代器适配器返回的值收集进一个 vector 并返回。</p>
<p>这个测试展示当调用 <code>shoes_in_size</code> 时,返回的只会是与我们指定的鞋码相同的鞋子。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="改进-io-项目"><a class="header" href="#改进-io-项目">改进 I/O 项目</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch13-03-improving-our-io-project.md">ch13-03-improving-our-io-project.md</a>
<br>
commit 2cd1b5593d26dc6a03c20f8619187ad4b2485552</p>
</blockquote>
<p>掌握了这些关于迭代器的新知识后,我们可以使用迭代器来改进第十二章中 I/O 项目的实现来使得代码更简洁明了。接下来,让我们看看迭代器如何改进 <code>Config::build</code> 函数和 <code>search</code> 函数的实现。</p>
<h3 id="使用迭代器去除-clone"><a class="header" href="#使用迭代器去除-clone">使用迭代器去除 <code>clone</code></a></h3>
<p>在示例 12-6 中,我们增加了一些代码获取一个 <code>String</code> 类型的 slice 并创建一个 <code>Config</code> 结构体的实例,它们索引 slice 中的值并克隆这些值以便 <code>Config</code> 结构体可以拥有这些值。在示例 13-17 中重现了第十二章结尾示例 12-23 中 <code>Config::build</code> 函数的实现:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring"> pub ignore_case: bool,
</span><span class="boring">}
</span><span class="boring">
</span>impl Config {
pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
<span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> let results = if config.ignore_case {
</span><span class="boring"> search_case_insensitive(&amp;config.query, &amp;contents)
</span><span class="boring"> } else {
</span><span class="boring"> search(&amp;config.query, &amp;contents)
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> for line in results {
</span><span class="boring"> println!("{line}");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search_case_insensitive&lt;'a&gt;(
</span><span class="boring"> query: &amp;str,
</span><span class="boring"> contents: &amp;'a str,
</span><span class="boring">) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let query = query.to_lowercase();
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.to_lowercase().contains(&amp;query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_sensitive() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Duct tape.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_insensitive() {
</span><span class="boring"> let query = "rUsT";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Trust me.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(
</span><span class="boring"> vec!["Rust:", "Trust me."],
</span><span class="boring"> search_case_insensitive(query, contents)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 13-17重现示例 12-23 的 <code>Config::build</code> 函数</span></p>
<p>当时我们说过不必担心低效的 <code>clone</code> 调用,因为我们以后会将其移除。好吧,就是现在!</p>
<p>起初这里需要 <code>clone</code> 的原因是参数 <code>args</code> 中有一个 <code>String</code> 元素的 slice<code>build</code> 函数并不拥有 <code>args</code>。为了能够返回 <code>Config</code> 实例的所有权,我们需要克隆 <code>Config</code> 中字段 <code>query</code><code>file_path</code> 的值,这样 <code>Config</code> 实例就能拥有这些值。</p>
<p>在学习了迭代器之后,我们可以将 <code>build</code> 函数改为获取一个有所有权的迭代器作为参数,而不是借用 slice。我们将使用迭代器功能代替之前检查 slice 长度和索引特定位置的代码。这样可以更清晰地表达 <code>Config::build</code> 函数的操作,因为迭代器会负责访问这些值。</p>
<p>一旦 <code>Config::build</code> 获取了迭代器的所有权并不再使用借用的索引操作,就可以将迭代器中的 <code>String</code> 值移动到 <code>Config</code> 中,而不是调用 <code>clone</code> 分配新的空间。</p>
<h4 id="直接使用返回的迭代器"><a class="header" href="#直接使用返回的迭代器">直接使用返回的迭代器</a></h4>
<p>打开 I/O 项目的 <em>src/main.rs</em> 文件,它看起来应该像这样:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::process;
</span><span class="boring">
</span><span class="boring">use minigrep::Config;
</span><span class="boring">
</span>fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::build(&amp;args).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
// --snip--
<span class="boring">
</span><span class="boring"> if let Err(e) = minigrep::run(config) {
</span><span class="boring"> eprintln!("Application error: {e}");
</span><span class="boring"> process::exit(1);
</span><span class="boring"> }
</span>}</code></pre>
<p>首先我们修改第十二章结尾示例 12-24 中的 <code>main</code> 函数的开头为示例 13-18 中的代码。在更新 <code>Config::build</code> 之前这些代码还不能编译:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::env;
</span><span class="boring">use std::process;
</span><span class="boring">
</span><span class="boring">use minigrep::Config;
</span><span class="boring">
</span>fn main() {
let config = Config::build(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
// --snip--
<span class="boring">
</span><span class="boring"> if let Err(e) = minigrep::run(config) {
</span><span class="boring"> eprintln!("Application error: {e}");
</span><span class="boring"> process::exit(1);
</span><span class="boring"> }
</span>}</code></pre>
<p><span class="caption">示例 13-25<code>env::args</code> 的返回值传递给 <code>Config::build</code></span></p>
<p><code>env::args</code> 函数返回一个迭代器!不同于将迭代器的值收集到一个 vector 中接着传递一个 slice 给 <code>Config::build</code>,现在我们直接将 <code>env::args</code> 返回的迭代器的所有权传递给 <code>Config::build</code></p>
<p>接下来需要更新 <code>Config::build</code> 的定义。在 I/O 项目的 <em>src/lib.rs</em> 中,将 <code>Config::build</code> 的签名改为如示例 13-19 所示。这仍然不能编译因为我们还需更新函数体。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::env;
</span><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring"> pub ignore_case: bool,
</span><span class="boring">}
</span><span class="boring">
</span>impl Config {
pub fn build(
mut args: impl Iterator&lt;Item = String&gt;,
) -&gt; Result&lt;Config, &amp;'static str&gt; {
// --snip--
<span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> let ignore_case = env::var("IGNORE_CASE").is_ok();
</span><span class="boring">
</span><span class="boring"> Ok(Config {
</span><span class="boring"> query,
</span><span class="boring"> file_path,
</span><span class="boring"> ignore_case,
</span><span class="boring"> })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> let results = if config.ignore_case {
</span><span class="boring"> search_case_insensitive(&amp;config.query, &amp;contents)
</span><span class="boring"> } else {
</span><span class="boring"> search(&amp;config.query, &amp;contents)
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> for line in results {
</span><span class="boring"> println!("{line}");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search_case_insensitive&lt;'a&gt;(
</span><span class="boring"> query: &amp;str,
</span><span class="boring"> contents: &amp;'a str,
</span><span class="boring">) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let query = query.to_lowercase();
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.to_lowercase().contains(&amp;query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_sensitive() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Duct tape.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_insensitive() {
</span><span class="boring"> let query = "rUsT";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Trust me.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(
</span><span class="boring"> vec!["Rust:", "Trust me."],
</span><span class="boring"> search_case_insensitive(query, contents)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 13-19以迭代器作为参数更新 <code>Config::build</code> 的签名</span></p>
<p><code>env::args</code> 函数的标准库文档显示,它返回的迭代器的类型为 <code>std::env::Args</code>,并且这个类型实现了 <code>Iterator</code> trait 并返回 <code>String</code> 值。</p>
<p>我们已经更新了 <code>Config::build</code> 函数的签名,因此参数 <code>args</code> 有一个带有 trait bounds <code>impl Iterator&lt;Item = String&gt;</code> 的泛型类型,而不是 <code>&amp;[String]</code>。这里用到了第十章 <a href="ch10-02-traits.html#trait-%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0">“trait 作为参数”</a> 部分讨论过的 <code>impl Trait</code> 语法,这意味着 <code>args</code> 可以是任何实现了 <code>Iterator</code> trait 并返回 <code>String</code>item的类型。</p>
<p>由于我们获取了 <code>args</code> 的所有权,并且将通过迭代来修改 <code>args</code>,因此我们可以在 <code>args</code> 参数的声明中添加 <code>mut</code> 关键字,使其可变。</p>
<h4 id="使用-iterator-trait-代替索引"><a class="header" href="#使用-iterator-trait-代替索引">使用 <code>Iterator</code> trait 代替索引</a></h4>
<p>接下来,我们将修改 <code>Config::build</code> 的函数体。因为 <code>args</code> 实现了 <code>Iterator</code> trait因此我们知道可以对其调用 <code>next</code> 方法!示例 13-20 更新了示例 12-23 中的代码,以使用 <code>next</code> 方法:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">use std::env;
</span><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring"> pub ignore_case: bool,
</span><span class="boring">}
</span><span class="boring">
</span>impl Config {
pub fn build(
mut args: impl Iterator&lt;Item = String&gt;,
) -&gt; Result&lt;Config, &amp;'static str&gt; {
args.next();
let query = match args.next() {
Some(arg) =&gt; arg,
None =&gt; return Err("Didn't get a query string"),
};
let file_path = match args.next() {
Some(arg) =&gt; arg,
None =&gt; return Err("Didn't get a file path"),
};
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
<span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> let results = if config.ignore_case {
</span><span class="boring"> search_case_insensitive(&amp;config.query, &amp;contents)
</span><span class="boring"> } else {
</span><span class="boring"> search(&amp;config.query, &amp;contents)
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> for line in results {
</span><span class="boring"> println!("{line}");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.contains(query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn search_case_insensitive&lt;'a&gt;(
</span><span class="boring"> query: &amp;str,
</span><span class="boring"> contents: &amp;'a str,
</span><span class="boring">) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let query = query.to_lowercase();
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.to_lowercase().contains(&amp;query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_sensitive() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Duct tape.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_insensitive() {
</span><span class="boring"> let query = "rUsT";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Trust me.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(
</span><span class="boring"> vec!["Rust:", "Trust me."],
</span><span class="boring"> search_case_insensitive(query, contents)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 13-20修改 <code>Config::build</code> 的函数体来使用迭代器方法</span></p>
<p>请记住 <code>env::args</code> 返回值的第一个值是程序的名称。我们希望忽略它并获取下一个值,所以首先调用 <code>next</code> 且不对其返回值做任何操作。然后,我们再次调用 <code>next</code> 来获取要放入 <code>Config</code> 结构体的 <code>query</code> 字段的值。如果 <code>next</code> 返回 <code>Some</code>,使用 <code>match</code> 来提取其值。如果它返回 <code>None</code>,则意味着没有提供足够的参数并通过 <code>Err</code> 值提早返回。我们对对 <code>file_path</code> 的值也进行同样的操作。</p>
<h3 id="使用迭代器适配器来使代码更简明"><a class="header" href="#使用迭代器适配器来使代码更简明">使用迭代器适配器来使代码更简明</a></h3>
<p>I/O 项目中其他可以利用迭代器的地方是 <code>search</code> 函数,示例 13-21 中重现了第十二章结尾示例 12-19 中此函数的定义:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> if args.len() &lt; 3 {
</span><span class="boring"> return Err("not enough arguments");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> let query = args[1].clone();
</span><span class="boring"> let file_path = args[2].clone();
</span><span class="boring">
</span><span class="boring"> Ok(Config { query, file_path })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span>pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 13-21示例 12-19 中 <code>search</code> 函数的定义</span></p>
<p>可以通过使用迭代器适配器方法来编写更简明的代码。这样做还可以避免使用一个可变的中间 <code>results</code> vector。函数式编程风格倾向于最小化可变状态的数量来使代码更简洁。去除可变状态可能会使未来的并行搜索优化变得更容易因为我们不必管理对 <code>results</code> vector 的并发访问。示例 13-22 展示了这一变化:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use std::env;
</span><span class="boring">use std::error::Error;
</span><span class="boring">use std::fs;
</span><span class="boring">
</span><span class="boring">pub struct Config {
</span><span class="boring"> pub query: String,
</span><span class="boring"> pub file_path: String,
</span><span class="boring"> pub ignore_case: bool,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Config {
</span><span class="boring"> pub fn build(
</span><span class="boring"> mut args: impl Iterator&lt;Item = String&gt;,
</span><span class="boring"> ) -&gt; Result&lt;Config, &amp;'static str&gt; {
</span><span class="boring"> args.next();
</span><span class="boring">
</span><span class="boring"> let query = match args.next() {
</span><span class="boring"> Some(arg) =&gt; arg,
</span><span class="boring"> None =&gt; return Err("Didn't get a query string"),
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let file_path = match args.next() {
</span><span class="boring"> Some(arg) =&gt; arg,
</span><span class="boring"> None =&gt; return Err("Didn't get a file path"),
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let ignore_case = env::var("IGNORE_CASE").is_ok();
</span><span class="boring">
</span><span class="boring"> Ok(Config {
</span><span class="boring"> query,
</span><span class="boring"> file_path,
</span><span class="boring"> ignore_case,
</span><span class="boring"> })
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
</span><span class="boring"> let contents = fs::read_to_string(config.file_path)?;
</span><span class="boring">
</span><span class="boring"> let results = if config.ignore_case {
</span><span class="boring"> search_case_insensitive(&amp;config.query, &amp;contents)
</span><span class="boring"> } else {
</span><span class="boring"> search(&amp;config.query, &amp;contents)
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> for line in results {
</span><span class="boring"> println!("{line}");
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> Ok(())
</span><span class="boring">}
</span><span class="boring">
</span>pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
contents
.lines()
.filter(|line| line.contains(query))
.collect()
}
<span class="boring">
</span><span class="boring">pub fn search_case_insensitive&lt;'a&gt;(
</span><span class="boring"> query: &amp;str,
</span><span class="boring"> contents: &amp;'a str,
</span><span class="boring">) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> let query = query.to_lowercase();
</span><span class="boring"> let mut results = Vec::new();
</span><span class="boring">
</span><span class="boring"> for line in contents.lines() {
</span><span class="boring"> if line.to_lowercase().contains(&amp;query) {
</span><span class="boring"> results.push(line);
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> results
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_sensitive() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Duct tape.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn case_insensitive() {
</span><span class="boring"> let query = "rUsT";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.
</span><span class="boring">Trust me.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(
</span><span class="boring"> vec!["Rust:", "Trust me."],
</span><span class="boring"> search_case_insensitive(query, contents)
</span><span class="boring"> );
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 13-22<code>search</code> 函数实现中使用迭代器适配器</span></p>
<p>回忆一下,<code>search</code> 函数的目的是返回所有 <code>contents</code> 中包含 <code>query</code> 的行。类似于示例 13-16 中的 <code>filter</code> 例子,这段代码使用 <code>filter</code> 适配器来保留 <code>line.contains(query)</code> 返回 <code>true</code> 的行。接着使用 <code>collect</code> 将匹配行收集到另一个 vector 中。这样就容易多了!尝试对 <code>search_case_insensitive</code> 函数做出同样的使用迭代器方法的修改吧。</p>
<h3 id="选择循环或迭代器"><a class="header" href="#选择循环或迭代器">选择循环或迭代器</a></h3>
<p>接下来的逻辑问题就是在代码中应该选择哪种风格,以及原因:是使用示例 13-21 中的原始实现还是使用示例 13-22 中使用迭代器的版本?大部分 Rust 程序员倾向于使用迭代器风格。开始这有点难以掌握,不过一旦你对不同迭代器的工作方式有了感觉之后,迭代器反而更容易理解。相比摆弄不同的循环并创建新 vector迭代器代码则更关注循环的高层次目的。这抽象掉那些老生常谈的代码这样就更容易看清代码所特有的概念比如迭代器中每个元素必须满足的过滤条件。</p>
<p>不过这两种实现真的完全等价吗?直觉上的假设是更底层的循环会更快一些。让我们聊聊性能吧。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="性能对比循环-vs-迭代器"><a class="header" href="#性能对比循环-vs-迭代器">性能对比:循环 VS 迭代器</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch13-04-performance.md">ch13-04-performance.md</a>
<br>
commit 009fffa4580ffb175f1b8470b5b12e4a63d670e4</p>
</blockquote>
<p>为了决定是否使用循环或迭代器,你需要了解哪个实现更快:使用显式 <code>for</code> 循环的 <code>search</code> 函数版本,还是使用迭代器的版本。</p>
<p>我们进行了一个基准测试,将阿瑟·柯南·道尔的《福尔摩斯探案集》的全部内容加载到一个 <code>String</code> 中,并在内容中查找单词 “the”。以下是使用 <code>for</code> 循环版本和使用迭代器版本的 <code>search</code> 函数的基准测试结果:</p>
<pre><code class="language-text">test bench_search_for ... bench: 19,620,300 ns/iter (+/- 915,700)
test bench_search_iter ... bench: 19,234,900 ns/iter (+/- 657,200)
</code></pre>
<p>结果迭代器版本还要稍微快一点!这里我们不会解释性能测试的代码,我们的目的并不是为了证明它们是完全等同的,而是得出一个怎样比较这两种实现方式性能的基本思路。</p>
<p>对于一个更全面的性能测试,你应该使用不同大小的文本作为 <code>contents</code>,不同的单词以及长度各异的单词作为 <code>query</code>,以及各种其他变化进行检查。关键在于:迭代器,作为一个高级的抽象,被编译成了与手写的底层代码大体一致性能的代码。迭代器是 Rust 的 <strong>零成本抽象</strong><em>zero-cost abstractions</em>之一它意味着抽象并不会引入额外的运行时开销它与本贾尼·斯特劳斯特卢普C++ 的设计和实现者)在 “Foundations of C++”2012中所定义的 <strong>零开销</strong><em>zero-overhead</em>)如出一辙:</p>
<blockquote>
<p>In general, C++ implementations obey the zero-overhead principle: What you don't use, you don't pay for. And further: What you do use, you couldn't hand code any better.</p>
<ul>
<li>Bjarne Stroustrup "Foundations of C++"</li>
</ul>
<p>从整体来说C++ 的实现遵循了零开销原则:你不需要的,无需为它买单。更有甚者的是:你需要的时候,也无法通过手写代码做得更好。</p>
<ul>
<li>本贾尼·斯特劳斯特卢普 "Foundations of C++"</li>
</ul>
</blockquote>
<p>作为另一个例子以下代码取自一个音频解码器。解码算法使用线性预测数学运算linear prediction mathematical operation来根据之前样本的线性函数预测将来的值。这些代码使用迭代器链对作用域中的三个变量进行某种数学计算一个叫 <code>buffer</code> 的数据 slice、一个有 12 个元素的数组 <code>coefficients</code>、和一个代表位数据位移量的 <code>qlp_shift</code>。我们在这个例子中声明了这些变量,但没有为它们赋值;虽然这些代码在其上下文之外没有太多意义,不过仍是一个简明的现实例子,来展示 Rust 如何将高级概念转换为底层代码。</p>
<pre><code class="language-rust ignore">let buffer: &amp;mut [i32];
let coefficients: [i64; 12];
let qlp_shift: i16;
for i in 12..buffer.len() {
let prediction = coefficients.iter()
.zip(&amp;buffer[i - 12..i])
.map(|(&amp;c, &amp;s)| c * s as i64)
.sum::&lt;i64&gt;() &gt;&gt; qlp_shift;
let delta = buffer[i];
buffer[i] = prediction as i32 + delta;
}</code></pre>
<p>为了计算 <code>prediction</code> 的值,这段代码遍历了 <code>coefficients</code> 中的 12 个值,使用 <code>zip</code> 方法将系数与 <code>buffer</code> 的前 12 个值组合在一起。接着将每一对值相乘,再将所有结果相加,然后将总和右移 <code>qlp_shift</code> 位。</p>
<p>像音频解码器这样的程序通常最看重计算的性能。这里,我们创建了一个迭代器,使用了两个适配器,接着消费了其值。那么这段 Rust 代码将会被编译为什么样的汇编代码呢?好吧,在编写本书的这个时候,它被编译成与手写的相同的汇编代码。遍历 <code>coefficients</code> 的值完全用不到循环Rust 知道这里会迭代 12 次所以它“展开”unroll了循环。展开是一种将循环迭代转换为重复代码并移除循环控制代码开销的代码优化技术。</p>
<p>所有的系数都被储存在了寄存器中,这意味着访问它们非常快。这里也没有运行时数组访问边界检查。所有这些 Rust 能够提供的优化使得结果代码极为高效。现在你知道了这些,请放心大胆的使用迭代器和闭包吧!它们使得代码看起来更高级,但并不为此引入运行时性能损失。</p>
<h2 id="总结-12"><a class="header" href="#总结-12">总结</a></h2>
<p>闭包和迭代器是 Rust 受函数式编程语言观念所启发的功能。它们对 Rust 以高性能来明确的表达高级概念的能力有很大贡献。闭包和迭代器的实现达到了不影响运行时性能的程度。这正是 Rust 致力于提供零成本抽象的目标的一部分。</p>
<p>现在我们改进了 I/O 项目的(代码)表现力,那么让我们来看看 <code>cargo</code> 的更多功能,这些功能将帮助我们将项目分享给全世界。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="进一步认识-cargo-和-cratesio"><a class="header" href="#进一步认识-cargo-和-cratesio">进一步认识 Cargo 和 Crates.io</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch14-00-more-about-cargo.md">ch14-00-more-about-cargo.md</a>
<br>
commit 44e31f9f304e0cd9ace01045d17a2aa01a449528</p>
</blockquote>
<p>目前为止我们只使用过 Cargo 构建、运行和测试代码这些最基本的功能,不过它还可以做到更多。本章会讨论 Cargo 其他一些更为高级的功能,我们将展示如何:</p>
<ul>
<li>使用发布配置来自定义构建</li>
<li>将库发布到 <a href="https://crates.io">crates.io</a></li>
<li>使用工作空间来组织更大的项目</li>
<li><a href="https://crates.io">crates.io</a> 安装二进制文件</li>
<li>使用自定义的命令来扩展 Cargo</li>
</ul>
<p>Cargo 的功能不止本章所介绍的,关于其全部功能的详尽解释,请查看 <a href="http://doc.rust-lang.org/cargo/">文档</a></p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="采用发布配置自定义构建"><a class="header" href="#采用发布配置自定义构建">采用发布配置自定义构建</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch14-01-release-profiles.md">ch14-01-release-profiles.md</a>
<br>
commit 44e31f9f304e0cd9ace01045d17a2aa01a449528</p>
</blockquote>
<p>在 Rust 中 <strong>发布配置</strong><em>release profiles</em>)文件是预定义和可定制的,它们包含不同的配置,允许程序员更灵活地控制代码编译的多种选项。每一个配置都相互独立。</p>
<p>Cargo 有两个主要的配置:运行 <code>cargo build</code> 时采用的 <code>dev</code> 配置和运行 <code>cargo build --release</code><code>release</code> 配置。<code>dev</code> 配置为开发定义了良好的默认配置,<code>release</code> 配置则为发布构建定义了良好的默认配置。</p>
<p>这些配置名称可能很眼熟,因为它们出现在构建的输出中:</p>
<pre><code class="language-console">$ cargo build
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
$ cargo build --release
Finished release [optimized] target(s) in 0.0s
</code></pre>
<p>构建输出中的 <code>dev</code><code>release</code> 表明编译器在使用不同的配置。</p>
<p>当项目的 <em>Cargo.toml</em> 文件中没有显式增加任何 <code>[profile.*]</code> 部分的时候Cargo 会对每一个配置都采用默认设置。通过增加任何希望定制的配置对应的 <code>[profile.*]</code> 部分,我们可以选择覆盖任意默认设置的子集。例如,如下是 <code>dev</code><code>release</code> 配置的 <code>opt-level</code> 设置的默认值:</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[profile.dev]
opt-level = 0
[profile.release]
opt-level = 3
</code></pre>
<p><code>opt-level</code> 设置控制 Rust 会对代码进行何种程度的优化。这个配置的值从 0 到 3。越高的优化级别需要更多的时间编译所以如果你在进行开发并经常编译可能会希望在牺牲一些代码性能的情况下减少优化以便编译得快一些。因此 <code>dev</code><code>opt-level</code> 默认为 <code>0</code>。当你准备发布时,花费更多时间在编译上则更好。只需要在发布模式编译一次,而编译出来的程序则会运行很多次,所以发布模式用更长的编译时间换取运行更快的代码。这正是为什么 <code>release</code> 配置的 <code>opt-level</code> 默认为 <code>3</code></p>
<p>我们可以选择通过在 <em>Cargo.toml</em> 增加不同的值来覆盖任何默认设置。比如,如果我们想要在开发配置中使用级别 1 的优化,则可以在 <em>Cargo.toml</em> 中增加这两行:</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[profile.dev]
opt-level = 1
</code></pre>
<p>这会覆盖默认的设置 <code>0</code>。现在运行 <code>cargo build</code>Cargo 将会使用 <code>dev</code> 的默认配置加上定制的 <code>opt-level</code>。因为 <code>opt-level</code> 设置为 <code>1</code>Cargo 会比默认进行更多的优化,但是没有发布构建那么多。</p>
<p>对于每个配置的设置和其默认值的完整列表,请查看 <a href="https://doc.rust-lang.org/cargo/reference/profiles.html">Cargo 的文档</a></p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="将-crate-发布到-cratesio"><a class="header" href="#将-crate-发布到-cratesio">将 crate 发布到 Crates.io</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch14-02-publishing-to-crates-io.md">ch14-02-publishing-to-crates-io.md</a> <br>
commit 3f2a6ef48943ade3e9c0eb23d69e2b8b41f057f1</p>
</blockquote>
<p>我们曾经在项目中使用 <a href="https://crates.io">crates.io</a><!-- ignore --> 上的包作为依赖,不过你也可以通过发布自己的包来向他人分享代码。<a href="https://crates.io">crates.io</a><!-- ignore --> 用来分发包的源代码,所以它主要托管开源代码。</p>
<p>Rust 和 Cargo 有一些帮助他人更方便地找到和使用你发布的包的功能。我们将介绍一些这样的功能,接着讲到如何发布一个包。</p>
<h3 id="编写有用的文档注释"><a class="header" href="#编写有用的文档注释">编写有用的文档注释</a></h3>
<p>准确的包文档有助于其他用户理解如何以及何时使用它们,所以花一些时间编写文档是值得的。第三章中我们讨论了如何使用双斜杠 <code>//</code> 注释 Rust 代码。Rust 也有特定的用于文档的注释类型,通常被称为 <strong>文档注释</strong><em>documentation comments</em>),它们会生成 HTML 文档。这些 HTML 展示公有 API 文档注释的内容,它们意在让对库感兴趣的程序员理解如何 <strong>使用</strong> 这个 crate而不是它是如何被 <strong>实现</strong> 的。</p>
<p>文档注释使用三斜杠 <code>///</code> 而不是双斜杠以支持 Markdown 注解来格式化文本。文档注释就位于需要文档的项的之前。示例 14-1 展示了一个 <code>my_crate</code> crate 中 <code>add_one</code> 函数的文档注释,</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore">/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -&gt; i32 {
x + 1
}</code></pre>
<p><span class="caption">示例 14-1一个函数的文档注释</span></p>
<p>这里,我们提供了一个 <code>add_one</code> 函数工作的描述,接着开始了一个标题为 <code>Examples</code> 的部分,和展示如何使用 <code>add_one</code> 函数的代码。可以运行 <code>cargo doc</code> 来生成这个文档注释的 HTML 文档。这个命令运行由 Rust 分发的工具 <code>rustdoc</code> 并将生成的 HTML 文档放入 <em>target/doc</em> 目录。</p>
<p>为了方便起见,运行 <code>cargo doc --open</code> 会构建当前 crate 文档(同时还有所有 crate 依赖的文档)的 HTML 并在浏览器中打开。导航到 <code>add_one</code> 函数将会发现文档注释的文本是如何渲染的,如图 14-1 所示:</p>
<img alt="`my_crate` 的 `add_one` 函数所渲染的文档注释 HTML" src="img/trpl14-01.png" class="center" />
<p><span class="caption">图 14-1<code>add_one</code> 函数的文档注释 HTML</span></p>
<h4 id="常用文档注释部分"><a class="header" href="#常用文档注释部分">常用(文档注释)部分</a></h4>
<p>示例 14-1 中使用了 <code># Examples</code> Markdown 标题在 HTML 中创建了一个以 “Examples” 为标题的部分。其他一些 crate 作者经常在文档注释中使用的部分有:</p>
<ul>
<li><strong>Panics</strong>:这个函数可能会 <code>panic!</code> 的场景。并不希望程序崩溃的函数调用者应该确保他们不会在这些情况下调用此函数。</li>
<li><strong>Errors</strong>:如果这个函数返回 <code>Result</code>,此部分描述可能会出现何种错误以及什么情况会造成这些错误,这有助于调用者编写代码来采用不同的方式处理不同的错误。</li>
<li><strong>Safety</strong>:如果这个函数使用 <code>unsafe</code> 代码(这会在第二十章讨论),这一部分应该会涉及到期望函数调用者支持的确保 <code>unsafe</code> 块中代码正常工作的不变条件invariants</li>
</ul>
<p>大部分文档注释不需要所有这些部分,不过这是一个提醒你检查调用你代码的用户有兴趣了解的内容的列表。</p>
<h4 id="文档注释作为测试"><a class="header" href="#文档注释作为测试">文档注释作为测试</a></h4>
<p>在文档注释中增加示例代码块是一个清楚的表明如何使用库的方法,这么做还有一个额外的好处:<code>cargo test</code> 也会像测试那样运行文档中的示例代码!没有什么比有例子的文档更好的了,但最糟糕的莫过于写完文档后改动了代码,而导致例子不能正常工作。尝试 <code>cargo test</code> 运行像示例 14-1 中 <code>add_one</code> 函数的文档;应该在测试结果中看到像这样的部分:</p>
<pre><code class="language-text"> Doc-tests my_crate
running 1 test
test src/lib.rs - add_one (line 5) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s
</code></pre>
<p>现在尝试改变函数或例子来使例子中的 <code>assert_eq!</code> 产生 panic。再次运行 <code>cargo test</code>,你将会看到文档测试捕获到了例子与代码不再同步!</p>
<h4 id="注释包含项的结构"><a class="header" href="#注释包含项的结构">注释包含项的结构</a></h4>
<p>文档注释风格 <code>//!</code> 为包含注释的项,而不是位于注释之后的项增加文档。这通常用于 crate 根文件(通常是 <em>src/lib.rs</em>)或模块的根文件为 crate 或模块整体提供文档。</p>
<p>作为一个例子,为了增加描述包含 <code>add_one</code> 函数的 <code>my_crate</code> crate 目的的文档,可以在 <em>src/lib.rs</em> 开头增加以 <code>//!</code> 开头的注释,如示例 14-2 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore">//! # My Crate
//!
//! `my_crate` is a collection of utilities to make performing certain
//! calculations more convenient.
/// Adds one to the number given.
// --snip--
<span class="boring">///
</span><span class="boring">/// # Examples
</span><span class="boring">///
</span><span class="boring">/// ```
</span><span class="boring">/// let arg = 5;
</span><span class="boring">/// let answer = my_crate::add_one(arg);
</span><span class="boring">///
</span><span class="boring">/// assert_eq!(6, answer);
</span><span class="boring">/// ```
</span><span class="boring">pub fn add_one(x: i32) -&gt; i32 {
</span><span class="boring"> x + 1
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 14-2<code>my_crate</code> crate 整体的文档</span></p>
<p>注意 <code>//!</code> 的最后一行之后没有任何代码。因为它们以 <code>//!</code> 开头而不是 <code>///</code>,这是属于包含此注释的项而不是注释之后项的文档。在这个情况下时 <em>src/lib.rs</em> 文件,也就是 crate 根文件。这些注释描述了整个 crate。</p>
<p>如果运行 <code>cargo doc --open</code>,将会发现这些注释显示在 <code>my_crate</code> 文档的首页,位于 crate 中公有项列表之上,如图 14-2 所示:</p>
<img alt="crate 整体注释所渲染的 HTML 文档" src="img/trpl14-02.png" class="center" />
<p><span class="caption">图 14-2包含 <code>my_crate</code> 整体描述的注释所渲染的文档</span></p>
<p>位于项之中的文档注释对于描述 crate 和模块特别有用。使用它们描述其容器整体的目的来帮助 crate 用户理解你的代码组织。</p>
<h3 id="使用-pub-use-导出合适的公有-api"><a class="header" href="#使用-pub-use-导出合适的公有-api">使用 <code>pub use</code> 导出合适的公有 API</a></h3>
<p>公有 API 的结构是你发布 crate 时主要需要考虑的。crate 用户没有你那么熟悉其结构,并且如果模块层级过大他们可能会难以找到所需的部分。</p>
<p>第七章介绍了如何使用 <code>mod</code> 关键字来将代码组织进模块中,如何使用 <code>pub</code> 关键字将项变为公有,和如何使用 <code>use</code> 关键字将项引入作用域。然而你开发时候使用的文件架构可能并不方便用户。你的结构可能是一个包含多个层级的分层结构,不过这对于用户来说并不方便。这是因为想要使用被定义在很深层级中的类型的人可能很难发现这些类型的存在。他们也可能会厌烦要使用 <code>use my_crate::some_module::another_module::UsefulType;</code> 而不是 <code>use my_crate::UsefulType;</code> 来使用类型。</p>
<p>好消息是,即使文件结构对于用户来说 <strong>不是</strong> 很方便,你也无需重新安排内部组织:你可以选择使用 <code>pub use</code> 重导出re-export项来使公有结构不同于私有结构。重导出获取位于一个位置的公有项并将其公开到另一个位置好像它就定义在这个新位置一样。</p>
<p>例如,假设我们创建了一个描述美术信息的库 <code>art</code>。这个库中包含了一个有两个枚举 <code>PrimaryColor</code><code>SecondaryColor</code> 的模块 <code>kinds</code>,以及一个包含函数 <code>mix</code> 的模块 <code>utils</code>,如示例 14-3 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground test_harness">//! # Art
//!
//! A library for modeling artistic concepts.
pub mod kinds {
/// The primary colors according to the RYB color model.
pub enum PrimaryColor {
Red,
Yellow,
Blue,
}
/// The secondary colors according to the RYB color model.
pub enum SecondaryColor {
Orange,
Green,
Purple,
}
}
pub mod utils {
use crate::kinds::*;
/// Combines two primary colors in equal amounts to create
/// a secondary color.
pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -&gt; SecondaryColor {
// --snip--
<span class="boring"> unimplemented!();
</span> }
}</code></pre>
<p><span class="caption">示例 14-3一个库 <code>art</code> 其组织包含 <code>kinds</code><code>utils</code> 模块</span></p>
<p><code>cargo doc</code> 所生成的 crate 文档首页如图 14-3 所示:</p>
<img alt="包含 `kinds` 和 `utils` 模块的 `art`" src="img/trpl14-03.png" class="center" />
<p><span class="caption">图 14-3包含 <code>kinds</code><code>utils</code> 模块的库 <code>art</code> 的文档首页</span></p>
<p>注意 <code>PrimaryColor</code><code>SecondaryColor</code> 类型、以及 <code>mix</code> 函数都没有在首页中列出。我们必须点击 <code>kinds</code><code>utils</code> 才能看到它们。</p>
<p>另一个依赖这个库的 crate 需要 <code>use</code> 语句来导入 <code>art</code> 中的项,这包含指定其当前定义的模块结构。示例 14-4 展示了一个使用 <code>art</code> crate 中 <code>PrimaryColor</code><code>mix</code> 项的 crate 的例子:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use art::kinds::PrimaryColor;
use art::utils::mix;
fn main() {
let red = PrimaryColor::Red;
let yellow = PrimaryColor::Yellow;
mix(red, yellow);
}</code></pre>
<p><span class="caption">示例 14-4一个通过导出内部结构使用 <code>art</code> crate 中项的 crate</span></p>
<p>示例 14-4 中使用 <code>art</code> crate 代码的作者不得不搞清楚 <code>PrimaryColor</code> 位于 <code>kinds</code> 模块而 <code>mix</code> 位于 <code>utils</code> 模块。<code>art</code> crate 的模块结构相比使用它的开发者来说对编写它的开发者更有意义。其内部结构并没有对尝试理解如何使用 <code>art</code> crate 的人提供任何有价值的信息,相反因为不得不搞清楚所需的内容在何处和必须在 <code>use</code> 语句中指定模块名称而显得混乱。</p>
<p>为了从公有 API 中去掉 crate 的内部组织,我们可以采用示例 14-3 中的 <code>art</code> crate 并增加 <code>pub use</code> 语句来重导出项到顶层结构,如示例 14-5 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore">//! # Art
//!
//! A library for modeling artistic concepts.
pub use self::kinds::PrimaryColor;
pub use self::kinds::SecondaryColor;
pub use self::utils::mix;
pub mod kinds {
// --snip--
<span class="boring"> /// The primary colors according to the RYB color model.
</span><span class="boring"> pub enum PrimaryColor {
</span><span class="boring"> Red,
</span><span class="boring"> Yellow,
</span><span class="boring"> Blue,
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> /// The secondary colors according to the RYB color model.
</span><span class="boring"> pub enum SecondaryColor {
</span><span class="boring"> Orange,
</span><span class="boring"> Green,
</span><span class="boring"> Purple,
</span><span class="boring"> }
</span>}
pub mod utils {
// --snip--
<span class="boring"> use crate::kinds::*;
</span><span class="boring">
</span><span class="boring"> /// Combines two primary colors in equal amounts to create
</span><span class="boring"> /// a secondary color.
</span><span class="boring"> pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -&gt; SecondaryColor {
</span><span class="boring"> SecondaryColor::Orange
</span><span class="boring"> }
</span>}</code></pre>
<p><span class="caption">示例 14-5增加 <code>pub use</code> 语句重导出项</span></p>
<p>现在此 crate 由 <code>cargo doc</code> 生成的 API 文档会在首页列出重导出的项以及其链接,如图 14-4 所示,这使得 <code>PrimaryColor</code><code>SecondaryColor</code> 类型和 <code>mix</code> 函数更易于查找。</p>
<img alt="Rendered documentation for the `art` crate with the re-exports on the front page" src="img/trpl14-04.png" class="center" />
<p><span class="caption">图 14-10<code>art</code> 文档的首页,这里列出了重导出的项</span></p>
<p><code>art</code> crate 的用户仍然可以看见和选择使用示例 14-4 中的内部结构,或者可以使用示例 14-5 中更为方便的结构,如示例 14-6 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use art::mix;
use art::PrimaryColor;
fn main() {
// --snip--
<span class="boring"> let red = PrimaryColor::Red;
</span><span class="boring"> let yellow = PrimaryColor::Yellow;
</span><span class="boring"> mix(red, yellow);
</span>}</code></pre>
<p><span class="caption">示例 14-6一个使用 <code>art</code> crate 中重导出项的程序</span></p>
<p>对于有很多嵌套模块的情况,使用 <code>pub use</code> 将类型重导出到顶级结构对于使用 crate 的人来说将会是大为不同的体验。<code>pub use</code> 的另一个常见用法是重导出当前 crate 的依赖的定义使其 crate 定义变成你 crate 公有 API 的一部分。</p>
<p>创建一个有用的公有 API 结构更像是一门艺术而非科学,你可以反复检视它们来找出最适合用户的 API。<code>pub use</code> 提供了解耦组织 crate 内部结构和与终端用户体现的灵活性。观察一些你所安装的 crate 的代码来看看其内部结构是否不同于公有 API。</p>
<h3 id="创建-cratesio-账号"><a class="header" href="#创建-cratesio-账号">创建 Crates.io 账号</a></h3>
<p>在你可以发布任何 crate 之前,需要在 <a href="https://crates.io">crates.io</a><!-- ignore --> 上注册账号并获取一个 API token。为此访问位于 <a href="https://crates.io">crates.io</a><!-- ignore --> 的首页并使用 GitHub 账号登录。(目前 GitHub 账号是必须的,不过将来该网站可能会支持其他创建账号的方法)一旦登录之后,查看位于 <a href="https://crates.io/me/">https://crates.io/me/</a><!-- ignore --> 的账户设置页面并获取 API token。接着使用该 API token 运行 <code>cargo login</code> 命令,像这样:</p>
<pre><code class="language-console">$ cargo login abcdefghijklmnopqrstuvwxyz012345
</code></pre>
<p>这个命令会通知 Cargo 你的 API token 并将其储存在本地的 <em>~/.cargo/credentials</em> 文件中。注意这个 token 是一个 <strong>秘密</strong><strong>secret</strong>)且不应该与其他人共享。如果因为任何原因与他人共享了这个信息,应该立即到 <a href="https://crates.io">crates.io</a><!-- ignore --> 撤销并重新生成一个 token。</p>
<h3 id="向新-crate-添加元信息"><a class="header" href="#向新-crate-添加元信息">向新 crate 添加元信息</a></h3>
<p>比如说你已经有一个希望发布的 crate。在发布之前你需要在 crate 的 <em>Cargo.toml</em> 文件的 <code>[package]</code> 部分增加一些本 crate 的元信息metadata</p>
<p>首先 crate 需要一个唯一的名称。虽然在本地开发 crate 时,可以使用任何你喜欢的名称。不过 <a href="https://crates.io">crates.io</a><!-- ignore --> 上的 crate 名称遵守先到先得的分配原则。一旦某个 crate 名称被使用,其他人就不能再发布这个名称的 crate 了。请搜索你希望使用的名称来找出它是否已被使用。如果没有,修改 <em>Cargo.toml</em><code>[package]</code> 里的名称为你希望用于发布的名称,像这样:</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[package]
name = "guessing_game"
</code></pre>
<p>即使你选择了一个唯一的名称,如果此时尝试运行 <code>cargo publish</code> 发布该 crate 的话,会得到一个警告接着是一个错误:</p>
<pre><code class="language-console">$ cargo publish
Updating crates.io index
warning: manifest has no description, license, license-file, documentation, homepage or repository.
See https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info.
--snip--
error: failed to publish to registry at https://crates.io
Caused by:
the remote server responded with an error: missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for how to upload metadata
</code></pre>
<p>这个错误是因为我们缺少一些关键信息:关于该 crate 用途的描述和用户可能在何种条款下使用该 crate 的 license。在 <em>Cargo.toml</em> 中添加通常是一两句话的描述,因为它将在搜索结果中和你的 crate 一起显示。对于 <code>license</code> 字段,你需要一个 <strong>license 标识符值</strong><em>license identifier value</em>)。<a href="http://spdx.org/licenses/">Linux 基金会的 Software Package Data Exchange (SPDX)</a> 列出了可以使用的标识符。例如,为了指定 crate 使用 MIT License增加 <code>MIT</code> 标识符:</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[package]
name = "guessing_game"
license = "MIT"
</code></pre>
<p>如果你希望使用不存在于 SPDX 的 license则需要将 license 文本放入一个文件,将该文件包含进项目中,接着使用 <code>license-file</code> 来指定文件名而不是使用 <code>license</code> 字段。</p>
<p>关于项目所适用的 license 指导超出了本书的范畴。很多 Rust 社区成员选择与 Rust 自身相同的 license这是一个双许可的 <code>MIT OR Apache-2.0</code>。这个实践展示了也可以通过 <code>OR</code> 分隔为项目指定多个 license 标识符。</p>
<p>那么,有了唯一的名称、版本号、由 <code>cargo new</code> 新建项目时增加的作者信息、描述和所选择的 license已经准备好发布的项目的 <em>Cargo.toml</em> 文件可能看起来像这样:</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
description = "A fun game where you guess what number the computer has chosen."
license = "MIT OR Apache-2.0"
[dependencies]
</code></pre>
<p><a href="http://doc.rust-lang.org/cargo/">Cargo 的文档</a> 描述了其他可以指定的元信息,它们可以帮助你的 crate 更容易被发现和使用!</p>
<h3 id="发布到-cratesio"><a class="header" href="#发布到-cratesio">发布到 Crates.io</a></h3>
<p>现在我们创建了一个账号,保存了 API token为 crate 选择了一个名字,并指定了所需的元数据,你已经准备好发布了!发布 crate 会上传特定版本的 crate 到 <a href="https://crates.io">crates.io</a><!-- ignore --> 以供他人使用。</p>
<p>发布 crate 时请多加小心,因为发布是 <strong>永久性的</strong><em>permanent</em>)。对应版本不可能被覆盖,其代码也不可能被删除。<a href="https://crates.io">crates.io</a><!-- ignore --> 的一个主要目标是作为一个存储代码的永久文档服务器,这样所有依赖 <a href="https://crates.io">crates.io</a><!-- ignore --> 中的 crate 的项目都能一直正常工作。而允许删除版本没办法达成这个目标。然而,可以被发布的版本号却没有限制。</p>
<p>再次运行 <code>cargo publish</code> 命令。这次它应该会成功:</p>
<pre><code class="language-console">$ cargo publish
Updating crates.io index
Packaging guessing_game v0.1.0 (file:///projects/guessing_game)
Verifying guessing_game v0.1.0 (file:///projects/guessing_game)
Compiling guessing_game v0.1.0
(file:///projects/guessing_game/target/package/guessing_game-0.1.0)
Finished dev [unoptimized + debuginfo] target(s) in 0.19s
Uploading guessing_game v0.1.0 (file:///projects/guessing_game)
</code></pre>
<p>恭喜!你现在向 Rust 社区分享了代码,而且任何人都可以轻松的将你的 crate 加入他们项目的依赖。</p>
<h3 id="发布现存-crate-的新版本"><a class="header" href="#发布现存-crate-的新版本">发布现存 crate 的新版本</a></h3>
<p>当你修改了 crate 并准备好发布新版本时,改变 <em>Cargo.toml</em><code>version</code> 所指定的值。请使用 <a href="http://semver.org/">语义化版本规则</a> 来根据修改的类型决定下一个版本号。接着运行 <code>cargo publish</code> 来上传新版本。</p>
<h3 id="使用-cargo-yank-从-cratesio-弃用版本"><a class="header" href="#使用-cargo-yank-从-cratesio-弃用版本">使用 <code>cargo yank</code> 从 Crates.io 弃用版本</a></h3>
<p>虽然你不能删除之前版本的 crate但是可以阻止任何将来的项目将它们加入到依赖中。这在某个版本因为这样或那样的原因被破坏的情况很有用。对于这种情况Cargo 支持 <strong>撤回</strong><em>yanking</em>)某个版本。</p>
<p>撤回某个版本会阻止新项目依赖此版本,不过所有现存此依赖的项目仍然能够下载和依赖这个版本。从本质上说,撤回意味着所有带有 <em>Cargo.lock</em> 的项目的依赖不会被破坏,同时任何新生成的 <em>Cargo.lock</em> 将不能使用被撤回的版本。</p>
<p>为了撤回一个版本的 crate在之前发布 crate 的目录运行 <code>cargo yank</code> 并指定希望撤回的版本。例如,如果我们发布了一个名为 <code>guessing_game</code> 的 crate 的 1.0.1 版本并希望撤回它,在 <code>guessing_game</code> 项目目录运行:</p>
<pre><code class="language-console">$ cargo yank --vers 1.0.1
Updating crates.io index
Yank guessing_game@1.0.1
</code></pre>
<p>也可以撤销撤回操作,并允许项目可以再次开始依赖某个版本,通过在命令上增加 <code>--undo</code></p>
<pre><code class="language-console">$ cargo yank --vers 1.0.1 --undo
Updating crates.io index
Unyank guessing_game@1.0.1
</code></pre>
<p>撤回 <strong>并没有</strong> 删除任何代码。举例来说,撤回功能并不能删除不小心上传的秘密信息。如果出现了这种情况,请立即重新设置这些秘密信息。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="cargo-工作空间"><a class="header" href="#cargo-工作空间">Cargo 工作空间</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch14-03-cargo-workspaces.md">ch14-03-cargo-workspaces.md</a>
<br>
commit 704c51eec2f26a0133ae17a2c01986590c05a045</p>
</blockquote>
<p>第十二章中,我们构建一个包含二进制 crate 和库 crate 的包。你可能会发现,随着项目开发的深入,库 crate 持续增大,而你希望将其进一步拆分成多个库 crate。Cargo 提供了一个叫 <strong>工作空间</strong><em>workspaces</em>)的功能,它可以帮助我们管理多个相关的协同开发的包。</p>
<h3 id="创建工作空间"><a class="header" href="#创建工作空间">创建工作空间</a></h3>
<p><strong>工作空间</strong> 是一系列共享同样的 <em>Cargo.lock</em> 和输出目录的包。让我们使用工作空间创建一个项目 —— 这里采用常见的代码以便可以关注工作空间的结构。有多种组织工作空间的方式,所以我们只展示一个常用方法。我们的工作空间有一个二进制项目和两个库。二进制项目会提供主要功能,并会依赖另两个库。一个库会提供 <code>add_one</code> 方法而第二个会提供 <code>add_two</code> 方法。这三个 crate 将会是相同工作空间的一部分。让我们以新建工作空间目录开始:</p>
<pre><code class="language-console">$ mkdir add
$ cd add
</code></pre>
<p>接着在 <em>add</em> 目录中,创建 <em>Cargo.toml</em> 文件。这个 <em>Cargo.toml</em> 文件配置了整个工作空间。它不会包含 <code>[package]</code> 部分。相反,它以 <code>[workspace]</code> 部分作为开始,并通过指定 <em>adder</em> 的路径来为工作空间增加成员,如下会加入二进制 crate</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[workspace]
members = [
"adder",
]
</code></pre>
<p>接下来,在 <em>add</em> 目录运行 <code>cargo new</code> 新建 <code>adder</code> 二进制 crate</p>
<pre><code class="language-console">$ cargo new adder
Created binary (application) `adder` package
</code></pre>
<p>到此为止,可以运行 <code>cargo build</code> 来构建工作空间。<em>add</em> 目录中的文件应该看起来像这样:</p>
<pre><code class="language-text">├── Cargo.lock
├── Cargo.toml
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
</code></pre>
<p>工作空间在顶级目录有一个 <em>target</em> 目录;<code>adder</code> 并没有自己的 <em>target</em> 目录。即使进入 <em>adder</em> 目录运行 <code>cargo build</code>,构建结果也位于 <em>add/target</em> 而不是 <em>add/adder/target</em>。工作空间中的 crate 之间相互依赖。如果每个 crate 有其自己的 <em>target</em> 目录,为了在自己的 <em>target</em> 目录中生成构建结果,工作空间中的每一个 crate 都不得不相互重新编译其他 crate。通过共享一个 <em>target</em> 目录,工作空间可以避免其他 crate 重复构建。</p>
<h3 id="在工作空间中创建第二个包"><a class="header" href="#在工作空间中创建第二个包">在工作空间中创建第二个包</a></h3>
<p>接下来,让我们在工作空间中指定另一个成员 crate。这个 crate 位于 <em>add_one</em> 目录中,所以修改顶级 <em>Cargo.toml</em> 为也包含 <em>add_one</em> 路径:</p>
<p><span class="filename">文件名Cargo.toml</span></p>
<pre><code class="language-toml">[workspace]
members = [
"adder",
"add_one",
]
</code></pre>
<p>接着新生成一个叫做 <code>add_one</code> 的库:</p>
<pre><code class="language-console">$ cargo new add_one --lib
Created library `add_one` package
</code></pre>
<p>现在 <em>add</em> 目录应该有如下目录和文件:</p>
<pre><code class="language-text">├── Cargo.lock
├── Cargo.toml
├── add_one
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
</code></pre>
<p><em>add_one/src/lib.rs</em> 文件中,增加一个 <code>add_one</code> 函数:</p>
<p><span class="filename">文件名add_one/src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add_one(x: i32) -&gt; i32 {
x + 1
}</code></pre>
<p>现在我们有了二进制 <code>adder</code> 依赖库 crate <code>add_one</code>。首先需要在 <em>adder/Cargo.toml</em> 文件中增加 <code>add_one</code> 作为路径依赖:</p>
<p><span class="filename">文件名adder/Cargo.toml</span></p>
<pre><code class="language-toml">[dependencies]
add_one = { path = "../add_one" }
</code></pre>
<p>cargo 并不假定工作空间中的 Crates 会相互依赖,所以需要明确表明工作空间中 crate 的依赖关系。</p>
<p>接下来,在 <code>adder</code> crate 中使用( <code>add_one</code> crate 中的)函数 <code>add_one</code>。打开 <em>adder/src/main.rs</em> 在顶部增加一行 <code>use</code> 将新 <code>add_one</code> 库 crate 引入作用域。接着修改 <code>main</code> 函数来调用 <code>add_one</code> 函数,如示例 14-7 所示。</p>
<p><span class="filename">文件名adder/src/main.rs</span></p>
<pre><code class="language-rust ignore">use add_one;
fn main() {
let num = 10;
println!("Hello, world! {num} plus one is {}!", add_one::add_one(num));
}</code></pre>
<p><span class="caption">示例 14-7<code>adder</code> crate 中使用 <code>add_one</code> 库 crate</span></p>
<p><em>add</em> 目录中运行 <code>cargo build</code> 来构建工作空间!</p>
<pre><code class="language-console">$ cargo build
Compiling add_one v0.1.0 (file:///projects/add/add_one)
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished dev [unoptimized + debuginfo] target(s) in 0.68s
</code></pre>
<p>为了在顶层 <em>add</em> 目录运行二进制 crate可以通过 <code>-p</code> 参数和包名称来运行 <code>cargo run</code> 指定工作空间中我们希望使用的包:</p>
<pre><code class="language-console">$ cargo run -p adder
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/adder`
Hello, world! 10 plus one is 11!
</code></pre>
<p>这会运行 <em>adder/src/main.rs</em> 中的代码,其依赖 <code>add_one</code> crate</p>
<h4 id="在工作空间中依赖外部包"><a class="header" href="#在工作空间中依赖外部包">在工作空间中依赖外部包</a></h4>
<p>还需注意的是工作空间只在根目录有一个 <em>Cargo.lock</em>,而不是在每一个 crate 目录都有 <em>Cargo.lock</em>。这确保了所有的 crate 都使用完全相同版本的依赖。如果在 <em>Cargo.toml</em><em>add_one/Cargo.toml</em> 中都增加 <code>rand</code> crate则 Cargo 会将其都解析为同一版本并记录到唯一的 <em>Cargo.lock</em> 中。使得工作空间中的所有 crate 都使用相同的依赖意味着其中的 crate 都是相互兼容的。让我们在 <em>add_one/Cargo.toml</em> 中的 <code>[dependencies]</code> 部分增加 <code>rand</code> crate 以便能够在 <code>add_one</code> crate 中使用 <code>rand</code> crate</p>
<p><span class="filename">文件名add_one/Cargo.toml</span></p>
<pre><code class="language-toml">[dependencies]
rand = "0.8.5"
</code></pre>
<p>现在就可以在 <em>add_one/src/lib.rs</em> 中增加 <code>use rand;</code> 了,接着在 <em>add</em> 目录运行 <code>cargo build</code> 构建整个工作空间就会引入并编译 <code>rand</code> crate</p>
<pre><code class="language-console">$ cargo build
Updating crates.io index
Downloaded rand v0.8.5
--snip--
Compiling rand v0.8.5
Compiling add_one v0.1.0 (file:///projects/add/add_one)
warning: unused import: `rand`
--&gt; add_one/src/lib.rs:1:5
|
1 | use rand;
| ^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: `add_one` (lib) generated 1 warning
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished dev [unoptimized + debuginfo] target(s) in 10.18s
</code></pre>
<p>现在顶级的 <em>Cargo.lock</em> 包含了 <code>add_one</code><code>rand</code> 依赖的信息。然而,即使 <code>rand</code> 被用于工作空间的某处,也不能在其他 crate 中使用它,除非也在它们的 <em>Cargo.toml</em> 中加入 <code>rand</code>。例如,如果在顶级的 <code>adder</code> crate 的 <em>adder/src/main.rs</em> 中增加 <code>use rand;</code>,会得到一个错误:</p>
<pre><code class="language-console">$ cargo build
--snip--
Compiling adder v0.1.0 (file:///projects/add/adder)
error[E0432]: unresolved import `rand`
--&gt; adder/src/main.rs:2:5
|
2 | use rand;
| ^^^^ no external crate `rand`
</code></pre>
<p>为了修复这个错误,修改顶级 <code>adder</code> crate 的 <em>Cargo.toml</em> 来表明 <code>rand</code> 也是这个 crate 的依赖。构建 <code>adder</code> crate 会将 <code>rand</code> 加入到 <em>Cargo.lock</em><code>adder</code> 的依赖列表中,但是这并不会下载 <code>rand</code> 的额外拷贝。Cargo 确保了工作空间中任何使用 <code>rand</code> 的 crate 都采用相同的版本,这节省了空间并确保了工作空间中的 crate 将是相互兼容的。</p>
<h4 id="为工作空间增加测试"><a class="header" href="#为工作空间增加测试">为工作空间增加测试</a></h4>
<p>作为另一个提升,让我们为 <code>add_one</code> crate 中的 <code>add_one::add_one</code> 函数增加一个测试:</p>
<p><span class="filename">文件名add_one/src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub fn add_one(x: i32) -&gt; i32 {
x + 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(3, add_one(2));
}
}</code></pre>
<p>在顶级 <em>add</em> 目录运行 <code>cargo test</code>。在像这样的工作空间结构中运行 <code>cargo test</code> 会运行工作空间中所有 crate 的测试。:</p>
<pre><code class="language-console">$ cargo test
Compiling add_one v0.1.0 (file:///projects/add/add_one)
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.27s
Running unittests src/lib.rs (target/debug/deps/add_one-f0253159197f7841)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/main.rs (target/debug/deps/adder-49979ff40686fa8e)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests add_one
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>输出的第一部分显示 <code>add_one</code> crate 的 <code>it_works</code> 测试通过了。下一个部分显示 <code>adder</code> crate 中找到了 0 个测试,最后一部分显示 <code>add_one</code> crate 中有 0 个文档测试。</p>
<p>也可以选择运行工作空间中特定 crate 的测试,通过在根目录使用 <code>-p</code> 参数并指定希望测试的 crate 名称:</p>
<pre><code class="language-console">$ cargo test -p add_one
Finished test [unoptimized + debuginfo] target(s) in 0.00s
Running unittests src/lib.rs (target/debug/deps/add_one-b3235fea9a156f74)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests add_one
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>输出显示了 <code>cargo test</code> 只运行了 <code>add_one</code> crate 的测试而没有运行 <code>adder</code> crate 的测试。</p>
<p>如果你选择向 <a href="https://crates.io/">crates.io</a>发布工作空间中的 crate每一个工作空间中的 crate 需要单独发布。就像 <code>cargo test</code> 一样,可以通过 <code>-p</code> 参数并指定期望发布的 crate 名来发布工作空间中的某个特定的 crate。</p>
<p>现在尝试以类似 <code>add_one</code> crate 的方式向工作空间增加 <code>add_two</code> crate 来作为更多的练习!</p>
<p>随着项目增长,考虑使用工作空间:每一个更小的组件比一大块代码要容易理解。如果它们经常需要同时被修改的话,将 crate 保持在工作空间中更易于协调 crate 的改变。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用-cargo-install-安装二进制文件"><a class="header" href="#使用-cargo-install-安装二进制文件">使用 <code>cargo install</code> 安装二进制文件</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch14-04-installing-binaries.md">ch14-04-installing-binaries.md</a>
<br>
commit 704c51eec2f26a0133ae17a2c01986590c05a045</p>
</blockquote>
<p><code>cargo install</code> 命令用于在本地安装和使用二进制 crate。它并不打算替换系统中的包它意在作为一个方便 Rust 开发者们安装其他人已经在 <a href="https://crates.io/">crates.io</a><!-- ignore --> 上共享的工具的手段。只有拥有二进制目标文件的包能够被安装。<strong>二进制目标</strong> 文件是在 crate 有 <em>src/main.rs</em> 或者其他指定为二进制文件时所创建的可执行程序,这不同于自身不能执行但适合包含在其他程序中的库目标文件。通常 crate 的 <em>README</em> 文件中有该 crate 是库、二进制目标还是两者兼有的信息。</p>
<p>所有来自 <code>cargo install</code> 的二进制文件都安装到 Rust 安装根目录的 <em>bin</em> 文件夹中。如果你是使用 <em>rustup.rs</em> 来安装 Rust 且没有自定义任何配置,这个目录将是 <code>$HOME/.cargo/bin</code>。确保将这个目录添加到 <code>$PATH</code> 环境变量中就能够运行通过 <code>cargo install</code> 安装的程序了。</p>
<p>例如,第十二章提到的叫做 <code>ripgrep</code> 的用于搜索文件的 <code>grep</code> 的 Rust 实现。为了安装 <code>ripgrep</code> 运行如下:</p>
<pre><code class="language-console">$ cargo install ripgrep
Updating crates.io index
Downloaded ripgrep v13.0.0
Downloaded 1 crate (243.3 KB) in 0.88s
Installing ripgrep v13.0.0
--snip--
Compiling ripgrep v13.0.0
Finished release [optimized + debuginfo] target(s) in 3m 10s
Installing ~/.cargo/bin/rg
Installed package `ripgrep v13.0.0` (executable `rg`)
</code></pre>
<p>最后一行输出展示了安装的二进制文件的位置和名称,在这里 <code>ripgrep</code> 被命名为 <code>rg</code>。只要你像上面提到的那样将安装目录加入 <code>$PATH</code>,就可以运行 <code>rg --help</code> 并开始使用一个更快更 Rust 的工具来搜索文件了!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="cargo-自定义扩展命令"><a class="header" href="#cargo-自定义扩展命令">Cargo 自定义扩展命令</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch14-05-extending-cargo.md">ch14-05-extending-cargo.md</a>
<br>
commit c084bdd9ee328e7e774df19882ccc139532e53d8</p>
</blockquote>
<p>Cargo 的设计使得开发者可以通过新的子命令来对 Cargo 进行扩展,而无需修改 Cargo 本身。如果 <code>$PATH</code> 中有类似 <code>cargo-something</code> 的二进制文件,就可以通过 <code>cargo something</code> 来像 Cargo 子命令一样运行它。像这样的自定义命令也可以运行 <code>cargo --list</code> 来展示出来。能够通过 <code>cargo install</code> 向 Cargo 安装扩展并可以如内建 Cargo 工具那样运行它们是 Cargo 设计上的一个非常方便的优点!</p>
<h2 id="总结-13"><a class="header" href="#总结-13">总结</a></h2>
<p>通过 Cargo 和 <a href="https://crates.io/">crates.io</a><!-- ignore --> 来分享代码是使得 Rust 生态环境可以用于许多不同的任务的重要组成部分。Rust 的标准库是小而稳定的,不过 crate 易于分享和使用,并采用一个不同语言自身的时间线来提供改进。不要羞于在 <a href="https://crates.io/">crates.io</a><!-- ignore --> 上共享对你有用的代码,因为它很有可能对别人也很有用!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="智能指针"><a class="header" href="#智能指针">智能指针</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch15-00-smart-pointers.md">ch15-00-smart-pointers.md</a>
<br>
commit 5a3a64d60b0dd786c35ca4daada7a4d20da33e5e</p>
</blockquote>
<p><strong>指针</strong> <em>pointer</em>)是一个包含内存地址的变量的通用概念。这个地址引用,或 “指向”points at一些其他数据。Rust 中最常见的指针是第四章介绍的 <strong>引用</strong><em>reference</em>)。引用以 <code>&amp;</code> 符号为标志并借用了它们所指向的值。除了引用数据没有任何其他特殊功能,也没有额外开销。</p>
<p>另一方面,<strong>智能指针</strong><em>smart pointers</em>)是一类数据结构,它们的表现类似指针,但是也拥有额外的元数据和功能。智能指针的概念并不为 Rust 所独有;其起源于 C++ 并存在于其他语言中。Rust 标准库中定义了多种不同的智能指针,它们提供了多于引用的额外功能。为了探索其基本概念,我们来看看一些智能指针的例子,这包括 <strong>引用计数</strong> <em>reference counting</em>)智能指针类型。这种指针允许数据有多个所有者,它会记录所有者的数量,当没有所有者时清理数据。在 Rust 中因为引用和借用,普通引用和智能指针的一个额外的区别是引用是一类只借用数据的指针;相反,在大部分情况下,智能指针 <strong>拥有</strong> 它们指向的数据。</p>
<p>实际上本书中已经出现过一些智能指针,比如第八章的 <code>String</code><code>Vec&lt;T&gt;</code>,虽然当时并没有这样称呼它们。这些类型都属于智能指针,因为它们拥有一些数据,并允许你修改这些数据。它们也拥有元数据和额外的功能或保证。例如 <code>String</code> 存储了其容量作为元数据,并拥有额外的能力来确保其数据总是有效的 UTF-8 编码。</p>
<p>智能指针通常使用结构体实现。智能指针不同于结构体的地方在于其实现了 <code>Deref</code><code>Drop</code> trait。<code>Deref</code> trait 允许智能指针结构体实例表现的像引用一样,这样就可以编写既用于引用、又用于智能指针的代码。<code>Drop</code> trait 允许我们自定义当智能指针离开作用域时运行的代码。本章会讨论这些 trait 以及为什么对于智能指针来说它们很重要。</p>
<p>考虑到智能指针是一个在 Rust 经常被使用的通用设计模式,本章并不会覆盖所有现存的智能指针。很多库都有自己的智能指针而你也可以编写属于你自己的智能指针。这里将会讲到的是来自标准库中最常用的一些:</p>
<ul>
<li><code>Box&lt;T&gt;</code>,用于在堆上分配值</li>
<li><code>Rc&lt;T&gt;</code>,一个引用计数类型,其数据可以有多个所有者</li>
<li><code>Ref&lt;T&gt;</code><code>RefMut&lt;T&gt;</code>,通过 <code>RefCell&lt;T&gt;</code> 访问。( <code>RefCell&lt;T&gt;</code> 是一个在运行时而不是在编译时执行借用规则的类型)。</li>
</ul>
<p>另外我们会涉及 <strong>内部可变性</strong><em>interior mutability</em>)模式,这是不可变类型暴露出改变其内部值的 API。我们也会讨论 <strong>引用循环</strong><em>reference cycles</em>)会如何泄漏内存,以及如何避免。</p>
<p>让我们开始吧!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用boxt指向堆上的数据"><a class="header" href="#使用boxt指向堆上的数据">使用<code>Box&lt;T&gt;</code>指向堆上的数据</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch15-01-box.md">ch15-01-box.md</a>
<br>
commit 5a3a64d60b0dd786c35ca4daada7a4d20da33e5e</p>
</blockquote>
<p>最简单直接的智能指针是 <em>box</em>,其类型是 <code>Box&lt;T&gt;</code>。box 允许你将一个值放在堆上而不是栈上。留在栈上的则是指向堆数据的指针。如果你想回顾一下栈与堆的区别请参考第四章。</p>
<p>除了数据被储存在堆上而不是栈上之外box 没有性能损失。不过也没有很多额外的功能。它们多用于如下场景:</p>
<ul>
<li>当有一个在编译时未知大小的类型,而又想要在需要确切大小的上下文中使用这个类型值的时候</li>
<li>当有大量数据并希望在确保数据不被拷贝的情况下转移所有权的时候</li>
<li>当希望拥有一个值并只关心它的类型是否实现了特定 trait 而不是其具体类型的时候</li>
</ul>
<p>我们会在 <a href="ch15-01-box.html#box-%E5%85%81%E8%AE%B8%E5%88%9B%E5%BB%BA%E9%80%92%E5%BD%92%E7%B1%BB%E5%9E%8B">“box 允许创建递归类型”</a> 部分展示第一种场景。在第二种情况中,转移大量数据的所有权可能会花费很长的时间,因为数据在栈上进行了拷贝。为了改善这种情况下的性能,可以通过 box 将这些数据储存在堆上。接着,只有少量的指针数据在栈上被拷贝。第三种情况被称为 <strong>trait 对象</strong><em>trait object</em>),第十八章刚好有一整个部分 <a href="ch18-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="使用-boxt-在堆上储存数据"><a class="header" href="#使用-boxt-在堆上储存数据">使用 <code>Box&lt;T&gt;</code> 在堆上储存数据</a></h3>
<p>在讨论 <code>Box&lt;T&gt;</code> 的堆存储用例之前,让我们熟悉一下语法以及如何与储存在 <code>Box&lt;T&gt;</code> 中的值进行交互。</p>
<p>示例 15-1 展示了如何使用 box 在堆上储存一个 <code>i32</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let b = Box::new(5);
println!("b = {b}");
}</code></pre></pre>
<p><span class="caption">示例 15-1使用 box 在堆上储存一个 <code>i32</code></span></p>
<p>这里定义了变量 <code>b</code>,其值是一个指向被分配在堆上的值 <code>5</code><code>Box</code>。这个程序会打印出 <code>b = 5</code>;在这个例子中,我们可以像数据是储存在栈上的那样访问 box 中的数据。正如任何拥有数据所有权的值那样,当像 <code>b</code> 这样的 box 在 <code>main</code> 的末尾离开作用域时,它将被释放。这个释放过程作用于 box 本身(位于栈上)和它所指向的数据(位于堆上)。</p>
<p>将一个单独的值存放在堆上并不是很有意义,所以像示例 15-1 这样单独使用 box 并不常见。将像单个 <code>i32</code> 这样的值储存在栈上,也就是其默认存放的地方在大部分使用场景中更为合适。让我们看看一个不使用 box 时无法定义的类型的例子。</p>
<h3 id="box-允许创建递归类型"><a class="header" href="#box-允许创建递归类型">Box 允许创建递归类型</a></h3>
<p><strong>递归类型</strong><em>recursive type</em>)的值可以拥有另一个同类型的值作为其自身的一部分。但是这会产生一个问题,因为 Rust 需要在编译时知道类型占用多少空间。递归类型的值嵌套理论上可以无限地进行下去,所以 Rust 不知道递归类型需要多少空间。因为 box 有一个已知的大小,所以通过在循环类型定义中插入 box就可以创建递归类型了。</p>
<p>作为一个递归类型的例子,让我们探索一下 <em>cons list</em>。这是一个函数式编程语言中常见的数据类型,来展示这个(递归类型)概念。除了递归之外,我们将要定义的 cons list 类型是很直白的,所以这个例子中的概念,在任何遇到更为复杂的涉及到递归类型的场景时都很实用。</p>
<h4 id="cons-list-的更多内容"><a class="header" href="#cons-list-的更多内容">cons list 的更多内容</a></h4>
<p><em>cons list</em> 是一个来源于 Lisp 编程语言及其方言的数据结构,它由嵌套的列表组成。它的名字来源于 Lisp 中的 <code>cons</code> 函数“construct function" 的缩写),它利用两个参数来构造一个新的列表。通过对一个包含值的列表和另一个值调用 <code>cons</code>,可以构建由递归列表组成的 cons list。</p>
<p>例如这里有一个包含列表 123 的 cons list 的伪代码表示,其每一个列表在一个括号中:</p>
<pre><code class="language-text">(1, (2, (3, Nil)))
</code></pre>
<p>cons list 的每一项都包含两个元素:当前项的值和下一项。其最后一项值包含一个叫做 <code>Nil</code> 的值且没有下一项。cons list 通过递归调用 <code>cons</code> 函数产生。代表递归的终止条件base case的规范名称是 <code>Nil</code>,它宣布列表的终止。注意这不同于第六章中的 “null” 或 “nil” 的概念,它们代表无效或缺失的值。</p>
<p>cons list 并不是一个 Rust 中常见的类型。大部分在 Rust 中需要列表的时候,<code>Vec&lt;T&gt;</code> 是一个更好的选择。其他更为复杂的递归数据类型 <strong>确实</strong> 在 Rust 的很多场景中很有用,不过通过以 cons list 作为开始,我们可以探索如何使用 box 毫不费力的定义一个递归数据类型。</p>
<p>示例 15-2 包含一个 cons list 的枚举定义。注意这还不能编译因为这个类型没有已知的大小,之后我们会展示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">enum List {
Cons(i32, List),
Nil,
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p><span class="caption">示例 15-2第一次尝试定义一个代表 <code>i32</code> 值的 cons list 数据结构的枚举</span></p>
<blockquote>
<p>注意:出于示例的需要我们选择实现一个只存放 <code>i32</code> 值的 cons list。也可以用泛型正如第十章讲到的来定义一个可以存放任何类型值的 cons list 类型。</p>
</blockquote>
<p>使用这个 cons list 来储存列表 <code>1, 2, 3</code> 将看起来如示例 15-3 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">enum List {
</span><span class="boring"> Cons(i32, List),
</span><span class="boring"> Nil,
</span><span class="boring">}
</span><span class="boring">
</span>use crate::List::{Cons, Nil};
fn main() {
let list = Cons(1, Cons(2, Cons(3, Nil)));
}</code></pre>
<p><span class="caption">示例 15-3使用 <code>List</code> 枚举储存列表 <code>1, 2, 3</code></span></p>
<p>第一个 <code>Cons</code> 储存了 <code>1</code> 和另一个 <code>List</code> 值。这个 <code>List</code> 是另一个包含 <code>2</code><code>Cons</code> 值和下一个 <code>List</code> 值。接着又有另一个存放了 <code>3</code><code>Cons</code> 值和最后一个值为 <code>Nil</code><code>List</code>,非递归成员代表了列表的结尾。</p>
<p>如果尝试编译示例 15-3 的代码,会得到如示例 15-4 所示的错误:</p>
<pre><code class="language-console">$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0072]: recursive type `List` has infinite size
--&gt; src/main.rs:1:1
|
1 | enum List {
| ^^^^^^^^^
2 | Cons(i32, List),
| ---- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&amp;`) to break the cycle
|
2 | Cons(i32, Box&lt;List&gt;),
| ++++ +
error[E0391]: cycle detected when computing when `List` needs drop
--&gt; src/main.rs:1:1
|
1 | enum List {
| ^^^^^^^^^
|
= note: ...which immediately requires computing when `List` needs drop again
= note: cycle used when computing whether `List` needs drop
= note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information
Some errors have detailed explanations: E0072, E0391.
For more information about an error, try `rustc --explain E0072`.
error: could not compile `cons-list` (bin "cons-list") due to 2 previous errors
</code></pre>
<p><span class="caption">示例 15-4尝试定义一个递归枚举时得到的错误</span></p>
<p>这个错误表明这个类型 “有无限的大小”。其原因是 <code>List</code> 的一个成员被定义为是递归的:它直接存放了另一个相同类型的值。这意味着 Rust 无法计算为了存放 <code>List</code> 值到底需要多少空间。让我们拆开来看为何会得到这个错误。首先了解一下 Rust 如何决定需要多少空间来存放一个非递归类型。</p>
<h3 id="计算非递归类型的大小"><a class="header" href="#计算非递归类型的大小">计算非递归类型的大小</a></h3>
<p>回忆一下第六章讨论枚举定义时示例 6-2 中定义的 <code>Message</code> 枚举:</p>
<pre><pre class="playground"><code class="language-rust edition2021">enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p>当 Rust 需要知道要为 <code>Message</code> 值分配多少空间时,它可以检查每一个成员并发现 <code>Message::Quit</code> 并不需要任何空间,<code>Message::Move</code> 需要足够储存两个 <code>i32</code> 值的空间,依此类推。因为 enum 实际上只会使用其中的一个成员,所以 <code>Message</code> 值所需的空间等于储存其最大成员的空间大小。</p>
<p>与此相对当 Rust 编译器检查像示例 15-2 中的 <code>List</code> 这样的递归类型时会发生什么呢。编译器尝试计算出储存一个 <code>List</code> 枚举需要多少内存,并开始检查 <code>Cons</code> 成员,那么 <code>Cons</code> 需要的空间等于 <code>i32</code> 的大小加上 <code>List</code> 的大小。为了计算 <code>List</code> 需要多少内存,它检查其成员,从 <code>Cons</code> 成员开始。<code>Cons</code>成员储存了一个 <code>i32</code> 值和一个<code>List</code>值,这样的计算将无限进行下去,如图 15-1 所示:</p>
<img alt="An infinite Cons list" src="img/trpl15-01.svg" class="center" style="width: 50%;" />
<p><span class="caption">图 15-1一个包含无限个 <code>Cons</code> 成员的无限 <code>List</code></span></p>
<h3 id="使用-boxt-给递归类型一个已知的大小"><a class="header" href="#使用-boxt-给递归类型一个已知的大小">使用 <code>Box&lt;T&gt;</code> 给递归类型一个已知的大小</a></h3>
<p>因为 Rust 无法计算出要为定义为递归的类型分配多少空间,所以编译器给出了一个包括了有用建议的错误:</p>
<pre><code class="language-text">help: insert some indirection (e.g., a `Box`, `Rc`, or `&amp;`) to make `List` representable
|
2 | Cons(i32, Box&lt;List&gt;),
| ++++ +
</code></pre>
<p>在建议中“indirection” 意味着不同于直接储存一个值,应该间接的储存一个指向值的指针。</p>
<p>因为 <code>Box&lt;T&gt;</code> 是一个指针,我们总是知道它需要多少空间:指针的大小并不会根据其指向的数据量而改变。这意味着可以将 <code>Box</code> 放入 <code>Cons</code> 成员中而不是直接存放另一个 <code>List</code> 值。<code>Box</code> 会指向另一个位于堆上的 <code>List</code> 值,而不是存放在 <code>Cons</code> 成员中。从概念上讲,我们仍然有一个通过在其中 “存放” 其他列表创建的列表,不过现在实现这个概念的方式更像是一个项挨着另一项,而不是一项包含另一项。</p>
<p>我们可以修改示例 15-2 中 <code>List</code> 枚举的定义和示例 15-3 中对 <code>List</code> 的应用,如示例 15-65 所示,这是可以编译的:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">enum List {
Cons(i32, Box&lt;List&gt;),
Nil,
}
use crate::List::{Cons, Nil};
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
}</code></pre></pre>
<p><span class="caption">示例 15-5为了拥有已知大小而使用 <code>Box&lt;T&gt;</code><code>List</code> 定义</span></p>
<p><code>Cons</code> 成员将会需要一个 <code>i32</code> 的大小加上储存 box 指针数据的空间。<code>Nil</code> 成员不储存值,所以它比 <code>Cons</code> 成员需要更少的空间。现在我们知道了任何 <code>List</code> 值最多需要一个 <code>i32</code> 加上 box 指针数据的大小。通过使用 box打破了这无限递归的连锁这样编译器就能够计算出储存 <code>List</code> 值需要的大小了。图 15-2 展示了现在 <code>Cons</code> 成员看起来像什么:</p>
<img alt="A finite Cons list" src="img/trpl15-02.svg" class="center" />
<p><span class="caption">图 15-2因为 <code>Cons</code> 存放一个 <code>Box</code> 所以 <code>List</code> 不是无限大小的了</span></p>
<p>box 只提供了间接存储和堆分配;它们并没有任何其他特殊的功能,比如我们将会见到的其他智能指针。它们也没有这些特殊功能带来的性能损失,所以它们可以用于像 cons list 这样间接存储是唯一所需功能的场景。我们还将在第十八章看到 box 的更多应用场景。</p>
<p><code>Box&lt;T&gt;</code> 类型是一个智能指针,因为它实现了 <code>Deref</code> trait它允许 <code>Box&lt;T&gt;</code> 值被当作引用对待。当 <code>Box&lt;T&gt;</code> 值离开作用域时,由于 <code>Box&lt;T&gt;</code> 类型 <code>Drop</code> trait 的实现box 所指向的堆数据也会被清除。这两个 trait 对于在本章余下讨论的其他智能指针所提供的功能中,将会更为重要。让我们更详细的探索一下这两个 trait。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="通过-deref-trait-将智能指针当作常规引用处理"><a class="header" href="#通过-deref-trait-将智能指针当作常规引用处理">通过 <code>Deref</code> trait 将智能指针当作常规引用处理</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch15-02-deref.md">ch15-02-deref.md</a>
<br>
commit 0514b1cf34c2eaab8285f43305c10a87f4ce34a0</p>
</blockquote>
<p>实现 <code>Deref</code> trait 允许我们重载 <strong>解引用运算符</strong><em>dereference operator</em><code>*</code>(不要与乘法运算符或通配符相混淆)。通过这种方式实现 <code>Deref</code> trait 的智能指针可以被当作常规引用来对待,可以编写操作引用的代码并用于智能指针。</p>
<p>让我们首先看看解引用运算符如何处理常规引用,接着尝试定义我们自己的类似 <code>Box&lt;T&gt;</code> 的类型并看看为何解引用运算符不能像引用一样工作。我们会探索如何实现 <code>Deref</code> trait 使得智能指针以类似引用的方式工作变为可能。最后,我们会讨论 Rust 的 <strong>Deref 强制转换</strong><em>deref coercions</em>)功能以及它是如何处理引用或智能指针的。</p>
<blockquote>
<p>我们将要构建的 <code>MyBox&lt;T&gt;</code> 类型与真正的 <code>Box&lt;T&gt;</code> 有一个很大的区别:我们的版本不会在堆上储存数据。这个例子重点关注 <code>Deref</code>,所以其数据实际存放在何处,相比其类似指针的行为来说不算重要。</p>
</blockquote>
<h3 id="追踪指针的值"><a class="header" href="#追踪指针的值">追踪指针的值</a></h3>
<p>常规引用是一个指针类型,一种理解指针的方式是将其看成指向储存在其他某处值的箭头。在示例 15-6 中,创建了一个 <code>i32</code> 值的引用,接着使用解引用运算符来跟踪所引用的值:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = 5;
let y = &amp;x;
assert_eq!(5, x);
assert_eq!(5, *y);
}</code></pre></pre>
<p><span class="caption">示例 15-6使用解引用运算符来跟踪 <code>i32</code> 值的引用</span></p>
<p>变量 <code>x</code> 存放了一个 <code>i32</code><code>5</code><code>y</code> 等于 <code>x</code> 的一个引用。可以断言 <code>x</code> 等于 <code>5</code>。然而,如果希望对 <code>y</code> 的值做出断言,必须使用 <code>*y</code> 来追踪引用所指向的值(也就是 <strong>解引用</strong>),这样编译器就可以比较实际的值了。一旦解引用了 <code>y</code>,就可以访问 <code>y</code> 所指向的整型值并可以与 <code>5</code> 做比较。</p>
<p>相反如果尝试编写 <code>assert_eq!(5, y);</code>,则会得到如下编译错误:</p>
<pre><code class="language-console">$ cargo run
Compiling deref-example v0.1.0 (file:///projects/deref-example)
error[E0277]: can't compare `{integer}` with `&amp;{integer}`
--&gt; src/main.rs:6:5
|
6 | assert_eq!(5, y);
| ^^^^^^^^^^^^^^^^ no implementation for `{integer} == &amp;{integer}`
|
= help: the trait `PartialEq&lt;&amp;{integer}&gt;` is not implemented for `{integer}`
= note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0277`.
error: could not compile `deref-example` (bin "deref-example") due to 1 previous error
</code></pre>
<p>不允许比较数字的引用与数字,因为它们是不同的类型。必须使用解引用运算符追踪引用所指向的值。</p>
<h3 id="像引用一样使用-boxt"><a class="header" href="#像引用一样使用-boxt">像引用一样使用 <code>Box&lt;T&gt;</code></a></h3>
<p>可以使用 <code>Box&lt;T&gt;</code> 代替引用来重写示例 15-6 中的代码,示例 15-7 中 <code>Box&lt;T&gt;</code> 上使用的解引用运算符与示例 15-6 中引用上使用的解引用运算符有着一样的功能:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = 5;
let y = Box::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);
}</code></pre></pre>
<p><span class="caption">示例 15-7<code>Box&lt;i32&gt;</code> 上使用解引用运算符</span></p>
<p>示例 15-7 相比示例 15-6 主要不同的地方就是将 <code>y</code> 设置为一个指向 <code>x</code> 值拷贝的 <code>Box&lt;T&gt;</code> 实例,而不是指向 <code>x</code> 值的引用。在最后的断言中,可以使用解引用运算符以 <code>y</code> 为引用时相同的方式追踪 <code>Box&lt;T&gt;</code> 的指针。接下来让我们通过实现自己的类型来探索 <code>Box&lt;T&gt;</code> 能这么做有何特殊之处。</p>
<h3 id="自定义智能指针"><a class="header" href="#自定义智能指针">自定义智能指针</a></h3>
<p>为了体会默认情况下智能指针与引用的不同,让我们创建一个类似于标准库提供的 <code>Box&lt;T&gt;</code> 类型的智能指针。接着学习如何增加使用解引用运算符的功能。</p>
<p>从根本上说,<code>Box&lt;T&gt;</code> 被定义为包含一个元素的元组结构体,所以示例 15-8 以相同的方式定义了 <code>MyBox&lt;T&gt;</code> 类型。我们还定义了 <code>new</code> 函数来对应定义于 <code>Box&lt;T&gt;</code><code>new</code> 函数:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct MyBox&lt;T&gt;(T);
impl&lt;T&gt; MyBox&lt;T&gt; {
fn new(x: T) -&gt; MyBox&lt;T&gt; {
MyBox(x)
}
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 15-8定义 <code>MyBox&lt;T&gt;</code> 类型</span></p>
<p>这里定义了一个结构体 <code>MyBox</code> 并声明了一个泛型参数 <code>T</code>,因为我们希望其可以存放任何类型的值。<code>MyBox</code> 是一个包含 <code>T</code> 类型元素的元组结构体。<code>MyBox::new</code> 函数获取一个 <code>T</code> 类型的参数并返回一个存放传入值的 <code>MyBox</code> 实例。</p>
<p>尝试将示例 15-7 中的代码加入示例 15-8 中并修改 <code>main</code> 使用我们定义的 <code>MyBox&lt;T&gt;</code> 类型代替 <code>Box&lt;T&gt;</code>。示例 15-9 中的代码不能编译,因为 Rust 不知道如何解引用 <code>MyBox</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">struct MyBox&lt;T&gt;(T);
</span><span class="boring">
</span><span class="boring">impl&lt;T&gt; MyBox&lt;T&gt; {
</span><span class="boring"> fn new(x: T) -&gt; MyBox&lt;T&gt; {
</span><span class="boring"> MyBox(x)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let x = 5;
let y = MyBox::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);
}</code></pre>
<p><span class="caption">示例 15-9尝试以使用引用和 <code>Box&lt;T&gt;</code> 相同的方式使用 <code>MyBox&lt;T&gt;</code></span></p>
<p>得到的编译错误是:</p>
<pre><code class="language-console">$ cargo run
Compiling deref-example v0.1.0 (file:///projects/deref-example)
error[E0614]: type `MyBox&lt;{integer}&gt;` cannot be dereferenced
--&gt; src/main.rs:14:19
|
14 | assert_eq!(5, *y);
| ^^
For more information about this error, try `rustc --explain E0614`.
error: could not compile `deref-example` (bin "deref-example") due to 1 previous error
</code></pre>
<p><code>MyBox&lt;T&gt;</code> 类型不能解引用,因为我们尚未在该类型实现这个功能。为了启用 <code>*</code> 运算符的解引用功能,需要实现 <code>Deref</code> trait。</p>
<h3 id="通过实现-deref-trait-将某类型像引用一样处理"><a class="header" href="#通过实现-deref-trait-将某类型像引用一样处理">通过实现 <code>Deref</code> trait 将某类型像引用一样处理</a></h3>
<p>如第十章 <a href="ch10-02-traits.html#%E4%B8%BA%E7%B1%BB%E5%9E%8B%E5%AE%9E%E7%8E%B0-trait">“为类型实现 trait”</a> 部分所讨论的,为了实现 trait需要提供 trait 所需的方法实现。<code>Deref</code> trait由标准库提供要求实现名为 <code>deref</code> 的方法,其借用 <code>self</code> 并返回一个内部数据的引用。示例 15-10 包含定义于 <code>MyBox</code> 之上的 <code>Deref</code> 实现:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::ops::Deref;
impl&lt;T&gt; Deref for MyBox&lt;T&gt; {
type Target = T;
fn deref(&amp;self) -&gt; &amp;Self::Target {
&amp;self.0
}
}
<span class="boring">
</span><span class="boring">struct MyBox&lt;T&gt;(T);
</span><span class="boring">
</span><span class="boring">impl&lt;T&gt; MyBox&lt;T&gt; {
</span><span class="boring"> fn new(x: T) -&gt; MyBox&lt;T&gt; {
</span><span class="boring"> MyBox(x)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let x = 5;
</span><span class="boring"> let y = MyBox::new(x);
</span><span class="boring">
</span><span class="boring"> assert_eq!(5, x);
</span><span class="boring"> assert_eq!(5, *y);
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 15-10<code>MyBox&lt;T&gt;</code> 上的 <code>Deref</code> 实现</span></p>
<p><code>type Target = T;</code> 语法定义了用于此 trait 的关联类型。关联类型是一个稍有不同的定义泛型参数的方式,现在还无需过多的担心它;第二十章会详细介绍。</p>
<p><code>deref</code> 方法体中写入了 <code>&amp;self.0</code>,这样 <code>deref</code> 返回了我希望通过 <code>*</code> 运算符访问的值的引用。回忆一下第五章 <a href="ch05-01-defining-structs.html#%E4%BD%BF%E7%94%A8%E6%B2%A1%E6%9C%89%E5%91%BD%E5%90%8D%E5%AD%97%E6%AE%B5%E7%9A%84%E5%85%83%E7%BB%84%E7%BB%93%E6%9E%84%E4%BD%93%E6%9D%A5%E5%88%9B%E5%BB%BA%E4%B8%8D%E5%90%8C%E7%9A%84%E7%B1%BB%E5%9E%8B">“使用没有命名字段的元组结构体来创建不同的类型”</a> 部分 <code>.0</code> 用来访问元组结构体的第一个元素。示例 15-9 中的 <code>main</code> 函数中对 <code>MyBox&lt;T&gt;</code> 值的 <code>*</code> 调用现在可以编译并能通过断言了!</p>
<p>没有 <code>Deref</code> trait 的话,编译器只会解引用 <code>&amp;</code> 引用类型。<code>deref</code> 方法向编译器提供了获取任何实现了 <code>Deref</code> trait 的类型的值,并且调用这个类型的 <code>deref</code> 方法来获取一个它知道如何解引用的 <code>&amp;</code> 引用的能力。</p>
<p>当我们在示例 15-9 中输入 <code>*y</code>Rust 事实上在底层运行了如下代码:</p>
<pre><code class="language-rust ignore">*(y.deref())</code></pre>
<p>Rust 将 <code>*</code> 运算符替换为先调用 <code>deref</code> 方法再进行普通解引用的操作,如此我们便不用担心是否还需手动调用 <code>deref</code> 方法了。Rust 的这个特性可以让我们写出行为一致的代码,无论是面对的是常规引用还是实现了 <code>Deref</code> 的类型。</p>
<p><code>deref</code> 方法返回值的引用,以及 <code>*(y.deref())</code> 括号外边的普通解引用仍为必须的原因在于所有权。如果 <code>deref</code> 方法直接返回值而不是值的引用,其值(的所有权)将被移出 <code>self</code>。在这里以及大部分使用解引用运算符的情况下我们并不希望获取 <code>MyBox&lt;T&gt;</code> 内部值的所有权。</p>
<p>注意,每次当我们在代码中使用 <code>*</code> 时, <code>*</code> 运算符都被替换成了先调用 <code>deref</code> 方法再接着使用 <code>*</code> 解引用的操作,且只会发生一次,不会对 <code>*</code> 操作符无限递归替换,解引用出上面 <code>i32</code> 类型的值就停止了,这个值与示例 15-9 中 <code>assert_eq!</code><code>5</code> 相匹配。</p>
<h3 id="函数和方法的隐式-deref-强制转换"><a class="header" href="#函数和方法的隐式-deref-强制转换">函数和方法的隐式 Deref 强制转换</a></h3>
<p><strong>Deref 强制转换</strong><em>deref coercions</em>)将实现了 <code>Deref</code> trait 的类型的引用转换为另一种类型的引用。例如Deref 强制转换可以将 <code>&amp;String</code> 转换为 <code>&amp;str</code>,因为 <code>String</code> 实现了 <code>Deref</code> trait 因此可以返回 <code>&amp;str</code>。Deref 强制转换是 Rust 在函数或方法传参上的一种便利操作,并且只能作用于实现了 <code>Deref</code> trait 的类型。当这种特定类型的引用作为实参传递给和形参类型不同的函数或方法时将自动进行。这时会有一系列的 <code>deref</code> 方法被调用,把我们提供的类型转换成了参数所需的类型。</p>
<p>Deref 强制转换的加入使得 Rust 程序员编写函数和方法调用时无需增加过多显式使用 <code>&amp;</code><code>*</code> 的引用和解引用。这个功能也使得我们可以编写更多同时作用于引用或智能指针的代码。</p>
<p>作为展示 Deref 强制转换的实例,让我们使用示例 15-8 中定义的 <code>MyBox&lt;T&gt;</code>,以及示例 15-10 中增加的 <code>Deref</code> 实现。示例 15-11 展示了一个有着字符串 slice 参数的函数定义:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn hello(name: &amp;str) {
println!("Hello, {name}!");
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 15-11<code>hello</code> 函数有着 <code>&amp;str</code> 类型的参数 <code>name</code></span></p>
<p>可以使用字符串 slice 作为参数调用 <code>hello</code> 函数,比如 <code>hello("Rust");</code>。Deref 强制转换使得用 <code>MyBox&lt;String&gt;</code> 类型值的引用调用 <code>hello</code> 成为可能,如示例 15-12 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">use std::ops::Deref;
</span><span class="boring">
</span><span class="boring">impl&lt;T&gt; Deref for MyBox&lt;T&gt; {
</span><span class="boring"> type Target = T;
</span><span class="boring">
</span><span class="boring"> fn deref(&amp;self) -&gt; &amp;T {
</span><span class="boring"> &amp;self.0
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct MyBox&lt;T&gt;(T);
</span><span class="boring">
</span><span class="boring">impl&lt;T&gt; MyBox&lt;T&gt; {
</span><span class="boring"> fn new(x: T) -&gt; MyBox&lt;T&gt; {
</span><span class="boring"> MyBox(x)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn hello(name: &amp;str) {
</span><span class="boring"> println!("Hello, {name}!");
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let m = MyBox::new(String::from("Rust"));
hello(&amp;m);
}</code></pre></pre>
<p><span class="caption">示例 15-12因为 Deref 强制转换,使用 <code>MyBox&lt;String&gt;</code> 的引用调用 <code>hello</code> 是可行的</span></p>
<p>这里使用 <code>&amp;m</code> 调用 <code>hello</code> 函数,其为 <code>MyBox&lt;String&gt;</code> 值的引用。因为示例 15-10 中在 <code>MyBox&lt;T&gt;</code> 上实现了 <code>Deref</code> traitRust 可以通过 <code>deref</code> 调用将 <code>&amp;MyBox&lt;String&gt;</code> 变为 <code>&amp;String</code>。标准库中提供了 <code>String</code> 上的 <code>Deref</code> 实现,其会返回字符串 slice这可以在 <code>Deref</code> 的 API 文档中看到。Rust 再次调用 <code>deref</code><code>&amp;String</code> 变为 <code>&amp;str</code>,这就符合 <code>hello</code> 函数的定义了。</p>
<p>如果 Rust 没有实现 Deref 强制转换,为了使用 <code>&amp;MyBox&lt;String&gt;</code> 类型的值调用 <code>hello</code>,则不得不编写示例 15-13 中的代码来代替示例 15-12</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">use std::ops::Deref;
</span><span class="boring">
</span><span class="boring">impl&lt;T&gt; Deref for MyBox&lt;T&gt; {
</span><span class="boring"> type Target = T;
</span><span class="boring">
</span><span class="boring"> fn deref(&amp;self) -&gt; &amp;T {
</span><span class="boring"> &amp;self.0
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct MyBox&lt;T&gt;(T);
</span><span class="boring">
</span><span class="boring">impl&lt;T&gt; MyBox&lt;T&gt; {
</span><span class="boring"> fn new(x: T) -&gt; MyBox&lt;T&gt; {
</span><span class="boring"> MyBox(x)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn hello(name: &amp;str) {
</span><span class="boring"> println!("Hello, {name}!");
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let m = MyBox::new(String::from("Rust"));
hello(&amp;(*m)[..]);
}</code></pre></pre>
<p><span class="caption">示例 15-13如果 Rust 没有 Deref 强制转换则必须编写的代码</span></p>
<p><code>(*m)</code><code>MyBox&lt;String&gt;</code> 解引用为 <code>String</code>。接着 <code>&amp;</code><code>[..]</code> 获取了整个 <code>String</code> 的字符串 slice 来匹配 <code>hello</code> 的签名。没有 Deref 强制转换所有这些符号混在一起将更难以读写和理解。Deref 强制转换使得 Rust 自动的帮我们处理这些转换。</p>
<p>当所涉及到的类型定义了 <code>Deref</code> traitRust 会分析这些类型并使用任意多次 <code>Deref::deref</code> 调用以获得匹配参数的类型。这些解析都发生在编译时,所以利用 Deref 强制转换并没有运行时损耗!</p>
<h3 id="deref-强制转换如何与可变性交互"><a class="header" href="#deref-强制转换如何与可变性交互">Deref 强制转换如何与可变性交互</a></h3>
<p>类似于如何使用 <code>Deref</code> trait 重载不可变引用的 <code>*</code> 运算符Rust 提供了 <code>DerefMut</code> trait 用于重载可变引用的 <code>*</code> 运算符。</p>
<p>Rust 在发现类型和 trait 实现满足三种情况时会进行 Deref 强制转换:</p>
<ul>
<li><code>T: Deref&lt;Target=U&gt;</code> 时从 <code>&amp;T</code><code>&amp;U</code></li>
<li><code>T: DerefMut&lt;Target=U&gt;</code> 时从 <code>&amp;mut T</code><code>&amp;mut U</code></li>
<li><code>T: Deref&lt;Target=U&gt;</code> 时从 <code>&amp;mut T</code><code>&amp;U</code></li>
</ul>
<p>头两个情况除了第二种实现了可变性之外是相同的:第一种情况表明如果有一个 <code>&amp;T</code>,而 <code>T</code> 实现了返回 <code>U</code> 类型的 <code>Deref</code>,则可以直接得到 <code>&amp;U</code>。第二种情况表明对于可变引用也有着相同的行为。</p>
<p>第三个情况有些微妙Rust 也会将可变引用强转为不可变引用。但是反之是 <strong>不可能</strong>不可变引用永远也不能强转为可变引用。因为根据借用规则如果有一个可变引用其必须是这些数据的唯一引用否则程序将无法编译。将一个可变引用转换为不可变引用永远也不会打破借用规则。将不可变引用转换为可变引用则需要初始的不可变引用是数据唯一的不可变引用而借用规则无法保证这一点。因此Rust 无法假设将不可变引用转换为可变引用是可能的。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用-drop-trait-运行清理代码"><a class="header" href="#使用-drop-trait-运行清理代码">使用 <code>Drop</code> Trait 运行清理代码</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch15-03-drop.md">ch15-03-drop.md</a>
<br>
commit 5a3a64d60b0dd786c35ca4daada7a4d20da33e5e</p>
</blockquote>
<p>对于智能指针模式来说第二个重要的 trait 是 <code>Drop</code>,其允许我们在值要离开作用域时执行一些代码。可以为任何类型提供 <code>Drop</code> trait 的实现,同时所指定的代码被用于释放类似于文件或网络连接的资源。</p>
<p>我们在智能指针上下文中讨论 <code>Drop</code> 是因为其功能几乎总是用于实现智能指针。例如,当 <code>Box&lt;T&gt;</code> 被丢弃时会释放 box 指向的堆空间。</p>
<p>在其他一些语言中的某些类型,我们不得不记住在每次使用完那些类型的智能指针实例后调用清理内存或资源的代码。如果忘记的话,运行代码的系统可能会因为负荷过重而崩溃。在 Rust 中,可以指定每当值离开作用域时被执行的代码,编译器会自动插入这些代码。于是我们就不需要在程序中到处编写在实例结束时清理这些变量的代码 —— 而且还不会泄漏资源。</p>
<p>指定在值离开作用域时应该执行的代码的方式是实现 <code>Drop</code> trait。<code>Drop</code> trait 要求实现一个叫做 <code>drop</code> 的方法,它获取一个 <code>self</code> 的可变引用。为了能够看出 Rust 何时调用 <code>drop</code>,让我们暂时使用 <code>println!</code> 语句实现 <code>drop</code></p>
<p>示例 15-14 展示了唯一定制功能就是当其实例离开作用域时,打印出 <code>Dropping CustomSmartPointer!</code> 的结构体 <code>CustomSmartPointer</code>,这会演示 Rust 何时运行 <code>drop</code> 函数:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&amp;mut self) {
println!("Dropping CustomSmartPointer with data `{}`!", self.data);
}
}
fn main() {
let c = CustomSmartPointer {
data: String::from("my stuff"),
};
let d = CustomSmartPointer {
data: String::from("other stuff"),
};
println!("CustomSmartPointers created.");
}</code></pre></pre>
<p><span class="caption">示例 15-14结构体 <code>CustomSmartPointer</code>,其实现了放置清理代码的 <code>Drop</code> trait</span></p>
<p><code>Drop</code> trait 包含在 prelude 中,所以无需导入它。我们在 <code>CustomSmartPointer</code> 上实现了 <code>Drop</code> trait并提供了一个调用 <code>println!</code><code>drop</code> 方法实现。<code>drop</code> 函数体是放置任何当类型实例离开作用域时期望运行的逻辑的地方。这里选择打印一些文本以可视化地展示 Rust 何时调用 <code>drop</code></p>
<p><code>main</code> 中,我们新建了两个 <code>CustomSmartPointer</code> 实例并打印出了 <code>CustomSmartPointer created.</code>。在 <code>main</code> 的结尾,<code>CustomSmartPointer</code> 的实例会离开作用域,而 Rust 会调用放置于 <code>drop</code> 方法中的代码,打印出最后的信息。注意无需显式调用 <code>drop</code> 方法:</p>
<p>当运行这个程序,会出现如下输出:</p>
<pre><code class="language-console">$ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.60s
Running `target/debug/drop-example`
CustomSmartPointers created.
Dropping CustomSmartPointer with data `other stuff`!
Dropping CustomSmartPointer with data `my stuff`!
</code></pre>
<p>当实例离开作用域 Rust 会自动调用 <code>drop</code>,并调用我们指定的代码。变量以被创建时相反的顺序被丢弃,所以 <code>d</code><code>c</code> 之前被丢弃。这个例子的作用是给了我们一个 drop 方法如何工作的可视化指导,不过通常需要指定类型所需执行的清理代码而不是打印信息。</p>
<h4 id="通过-stdmemdrop-提早丢弃值"><a class="header" href="#通过-stdmemdrop-提早丢弃值">通过 <code>std::mem::drop</code> 提早丢弃值</a></h4>
<p>不幸的是,我们并不能直截了当的禁用 <code>drop</code> 这个功能。通常也不需要禁用 <code>drop</code> ;整个 <code>Drop</code> trait 存在的意义在于其是自动处理的。然而,有时你可能需要提早清理某个值。一个例子是当使用智能指针管理锁时;你可能希望强制运行 <code>drop</code> 方法来释放锁以便作用域中的其他代码可以获取锁。Rust 并不允许我们主动调用 <code>Drop</code> trait 的 <code>drop</code> 方法;当我们希望在作用域结束之前就强制释放变量的话,我们应该使用的是由标准库提供的 <code>std::mem::drop</code></p>
<p>如果我们像是示例 15-14 那样尝试调用 <code>Drop</code> trait 的 <code>drop</code> 方法,就会得到像示例 15-15 那样的编译错误:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">struct CustomSmartPointer {
</span><span class="boring"> data: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Drop for CustomSmartPointer {
</span><span class="boring"> fn drop(&amp;mut self) {
</span><span class="boring"> println!("Dropping CustomSmartPointer with data `{}`!", self.data);
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
println!("CustomSmartPointer created.");
c.drop();
println!("CustomSmartPointer dropped before the end of main.");
}</code></pre>
<p><span class="caption">示例 15-15尝试手动调用 <code>Drop</code> trait 的 <code>drop</code> 方法提早清理</span></p>
<p>如果尝试编译代码会得到如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
error[E0040]: explicit use of destructor method
--&gt; src/main.rs:16:7
|
16 | c.drop();
| ^^^^ explicit destructor calls not allowed
|
help: consider using `drop` function
|
16 | drop(c);
| +++++ ~
For more information about this error, try `rustc --explain E0040`.
error: could not compile `drop-example` (bin "drop-example") due to 1 previous error
</code></pre>
<p>错误信息表明不允许显式调用 <code>drop</code>。错误信息使用了术语 <strong>析构函数</strong><em>destructor</em>),这是一个清理实例的函数的通用编程概念。<strong>析构函数</strong> 对应创建实例的 <strong>构造函数</strong>。Rust 中的 <code>drop</code> 函数就是这么一个析构函数。</p>
<p>Rust 不允许我们显式调用 <code>drop</code> 因为 Rust 仍然会在 <code>main</code> 的结尾对值自动调用 <code>drop</code>,这会导致一个 <em>double free</em> 错误,因为 Rust 会尝试清理相同的值两次。</p>
<p>因为不能禁用当值离开作用域时自动插入的 <code>drop</code>,并且不能显式调用 <code>drop</code>,如果我们需要强制提早清理值,可以使用 <code>std::mem::drop</code> 函数。</p>
<p><code>std::mem::drop</code> 函数不同于 <code>Drop</code> trait 中的 <code>drop</code> 方法。可以通过传递希望强制丢弃的值作为参数。<code>std::mem::drop</code> 位于 prelude所以我们可以修改示例 15-15 中的 <code>main</code> 来调用 <code>drop</code> 函数。如示例 15-16 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct CustomSmartPointer {
</span><span class="boring"> data: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Drop for CustomSmartPointer {
</span><span class="boring"> fn drop(&amp;mut self) {
</span><span class="boring"> println!("Dropping CustomSmartPointer with data `{}`!", self.data);
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
println!("CustomSmartPointer created.");
drop(c);
println!("CustomSmartPointer dropped before the end of main.");
}</code></pre></pre>
<p><span class="caption">示例 15-16: 在值离开作用域之前调用 <code>std::mem::drop</code> 显式清理</span></p>
<p>运行这段代码会打印出如下:</p>
<pre><code class="language-console">$ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.73s
Running `target/debug/drop-example`
CustomSmartPointer created.
Dropping CustomSmartPointer with data `some data`!
CustomSmartPointer dropped before the end of main.
</code></pre>
<p><code>Dropping CustomSmartPointer with data `some data`!</code> 出现在 <code>CustomSmartPointer created.</code><code>CustomSmartPointer dropped before the end of main.</code> 之间,表明了 <code>drop</code> 方法被调用了并在此丢弃了 <code>c</code></p>
<p><code>Drop</code> trait 实现中指定的代码可以用于许多方面,来使得清理变得方便和安全:比如可以用其创建我们自己的内存分配器!通过 <code>Drop</code> trait 和 Rust 所有权系统你无需担心之后的代码清理Rust 会自动考虑这些问题。</p>
<p>我们也无需担心意外的清理掉仍在使用的值,这会造成编译器错误:所有权系统确保引用总是有效的,也会确保 <code>drop</code> 只会在值不再被使用时被调用一次。</p>
<p>现在我们学习了 <code>Box&lt;T&gt;</code> 和一些智能指针的特性,让我们聊聊标准库中定义的其他几种智能指针。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="rct-引用计数智能指针"><a class="header" href="#rct-引用计数智能指针"><code>Rc&lt;T&gt;</code> 引用计数智能指针</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch15-04-rc.md">ch15-04-rc.md</a>
<br>
commit 52fafaaa8e432e84beaaf4ea80ccba880624effd</p>
</blockquote>
<p>大部分情况下所有权是非常明确的:可以准确地知道哪个变量拥有某个值。然而,有些情况单个值可能会有多个所有者。例如,在图数据结构中,多个边可能指向相同的节点,而这个节点从概念上讲为所有指向它的边所拥有。节点在没有任何边指向它从而没有任何所有者之前,都不应该被清理掉。</p>
<p>为了启用多所有权需要显式地使用 Rust 类型 <code>Rc&lt;T&gt;</code>,其为 <strong>引用计数</strong><em>reference counting</em>)的缩写。引用计数意味着记录一个值的引用数量来知晓这个值是否仍在被使用。如果某个值有零个引用,就代表没有任何有效引用并可以被清理。</p>
<p>可以将其想象为客厅中的电视。当一个人进来看电视时,他打开电视。其他人也可以进来看电视。当最后一个人离开房间时,他关掉电视因为它不再被使用了。如果某人在其他人还在看的时候就关掉了电视,正在看电视的人肯定会抓狂的!</p>
<p><code>Rc&lt;T&gt;</code> 用于当我们希望在堆上分配一些内存供程序的多个部分读取,而且无法在编译时确定程序的哪一部分会最后结束使用它的时候。如果确实知道哪部分是最后一个结束使用的话,就可以令其成为数据的所有者,正常的所有权规则就可以在编译时生效。</p>
<p>注意 <code>Rc&lt;T&gt;</code> 只能用于单线程场景;第十六章并发会涉及到如何在多线程程序中进行引用计数。</p>
<h3 id="使用-rct-共享数据"><a class="header" href="#使用-rct-共享数据">使用 <code>Rc&lt;T&gt;</code> 共享数据</a></h3>
<p>让我们回到示例 15-5 中使用 <code>Box&lt;T&gt;</code> 定义 cons list 的例子。这一次,我们希望创建两个共享第三个列表所有权的列表,其概念将会看起来如图 15-3 所示:</p>
<img alt="Two lists that share ownership of a third list" src="img/trpl15-03.svg" class="center" />
<p><span class="caption">图 15-3: 两个列表,<code>b</code><code>c</code>, 共享第三个列表 <code>a</code> 的所有权</span></p>
<p>列表 <code>a</code> 包含 5 之后是 10之后是另两个列表<code>b</code> 从 3 开始而 <code>c</code> 从 4 开始。<code>b</code><code>c</code> 会接上包含 5 和 10 的列表 <code>a</code>。换句话说,这两个列表会尝试共享第一个列表所包含的 5 和 10。</p>
<p>尝试使用 <code>Box&lt;T&gt;</code> 定义的 <code>List</code> 实现并不能工作,如示例 15-17 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">enum List {
Cons(i32, Box&lt;List&gt;),
Nil,
}
use crate::List::{Cons, Nil};
fn main() {
let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
let b = Cons(3, Box::new(a));
let c = Cons(4, Box::new(a));
}</code></pre>
<p><span class="caption">示例 15-17: 展示不能用两个 <code>Box&lt;T&gt;</code> 的列表尝试共享第三个列表的所有权</span></p>
<p>编译会得出如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0382]: use of moved value: `a`
--&gt; src/main.rs:11:30
|
9 | let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
| - move occurs because `a` has type `List`, which does not implement the `Copy` trait
10 | let b = Cons(3, Box::new(a));
| - value moved here
11 | let c = Cons(4, Box::new(a));
| ^ value used here after move
For more information about this error, try `rustc --explain E0382`.
error: could not compile `cons-list` (bin "cons-list") due to 1 previous error
</code></pre>
<p><code>Cons</code> 成员拥有其储存的数据,所以当创建 <code>b</code> 列表时,<code>a</code> 被移动进了 <code>b</code> 这样 <code>b</code> 就拥有了 <code>a</code>。接着当再次尝试使用 <code>a</code> 创建 <code>c</code> 时,这不被允许,因为 <code>a</code> 的所有权已经被移动。</p>
<p>可以改变 <code>Cons</code> 的定义来存放一个引用,不过接着必须指定生命周期参数。通过指定生命周期参数,表明列表中的每一个元素都至少与列表本身存在的一样久。这是示例 15-17 中元素与列表的情况,但并不是所有情况都如此。</p>
<p>相反,我们修改 <code>List</code> 的定义为使用 <code>Rc&lt;T&gt;</code> 代替 <code>Box&lt;T&gt;</code>,如列表 15-18 所示。现在每一个 <code>Cons</code> 变量都包含一个值和一个指向 <code>List</code><code>Rc&lt;T&gt;</code>。当创建 <code>b</code> 时,不同于获取 <code>a</code> 的所有权,这里会克隆 <code>a</code> 所包含的 <code>Rc&lt;List&gt;</code>,这会将引用计数从 1 增加到 2 并允许 <code>a</code><code>b</code> 共享 <code>Rc&lt;List&gt;</code> 中数据的所有权。创建 <code>c</code> 时也会克隆 <code>a</code>,这会将引用计数从 2 增加为 3。每次调用 <code>Rc::clone</code><code>Rc&lt;List&gt;</code> 中数据的引用计数都会增加,直到有零个引用之前其数据都不会被清理。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">enum List {
Cons(i32, Rc&lt;List&gt;),
Nil,
}
use crate::List::{Cons, Nil};
use std::rc::Rc;
fn main() {
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
let b = Cons(3, Rc::clone(&amp;a));
let c = Cons(4, Rc::clone(&amp;a));
}</code></pre></pre>
<p><span class="caption">示例 15-18: 使用 <code>Rc&lt;T&gt;</code> 定义的 <code>List</code></span></p>
<p>需要使用 <code>use</code> 语句将 <code>Rc&lt;T&gt;</code> 引入作用域,因为它不在 prelude 中。在 <code>main</code> 中创建了存放 5 和 10 的列表并将其存放在 <code>a</code> 的新的 <code>Rc&lt;List&gt;</code> 中。接着当创建 <code>b</code><code>c</code> 时,调用 <code>Rc::clone</code> 函数并传递 <code>a</code><code>Rc&lt;List&gt;</code> 的引用作为参数。</p>
<p>也可以调用 <code>a.clone()</code> 而不是 <code>Rc::clone(&amp;a)</code>,不过在这里 Rust 的习惯是使用 <code>Rc::clone</code><code>Rc::clone</code> 的实现并不像大部分类型的 <code>clone</code> 实现那样对所有数据进行深拷贝。<code>Rc::clone</code> 只会增加引用计数,这并不会花费多少时间。深拷贝可能会花费很长时间。通过使用 <code>Rc::clone</code> 进行引用计数,可以明显的区别深拷贝类的克隆和增加引用计数类的克隆。当查找代码中的性能问题时,只需考虑深拷贝类的克隆而无需考虑 <code>Rc::clone</code> 调用。</p>
<h3 id="克隆-rct-会增加引用计数"><a class="header" href="#克隆-rct-会增加引用计数">克隆 <code>Rc&lt;T&gt;</code> 会增加引用计数</a></h3>
<p>让我们修改示例 15-18 的代码以便观察创建和丢弃 <code>a</code><code>Rc&lt;List&gt;</code> 的引用时引用计数的变化。</p>
<p>在示例 15-19 中,修改了 <code>main</code> 以便将列表 <code>c</code> 置于内部作用域中,这样就可以观察当 <code>c</code> 离开作用域时引用计数如何变化。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">enum List {
</span><span class="boring"> Cons(i32, Rc&lt;List&gt;),
</span><span class="boring"> Nil,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">use crate::List::{Cons, Nil};
</span><span class="boring">use std::rc::Rc;
</span><span class="boring">
</span>fn main() {
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
println!("count after creating a = {}", Rc::strong_count(&amp;a));
let b = Cons(3, Rc::clone(&amp;a));
println!("count after creating b = {}", Rc::strong_count(&amp;a));
{
let c = Cons(4, Rc::clone(&amp;a));
println!("count after creating c = {}", Rc::strong_count(&amp;a));
}
println!("count after c goes out of scope = {}", Rc::strong_count(&amp;a));
}</code></pre></pre>
<p><span class="caption">示例 15-19打印出引用计数</span></p>
<p>在程序中每个引用计数变化的点,会打印出引用计数,其值可以通过调用 <code>Rc::strong_count</code> 函数获得。这个函数叫做 <code>strong_count</code> 而不是 <code>count</code> 是因为 <code>Rc&lt;T&gt;</code> 也有 <code>weak_count</code>;在 <a href="ch15-06-reference-cycles.html#%E9%81%BF%E5%85%8D%E5%BC%95%E7%94%A8%E5%BE%AA%E7%8E%AF%E5%B0%86-rct-%E5%8F%98%E4%B8%BA-weakt">“避免引用循环:将 <code>Rc&lt;T&gt;</code> 变为 <code>Weak&lt;T&gt;</code></a> 部分会讲解 <code>weak_count</code> 的用途。</p>
<p>这段代码会打印出:</p>
<pre><code class="language-console">$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.45s
Running `target/debug/cons-list`
count after creating a = 1
count after creating b = 2
count after creating c = 3
count after c goes out of scope = 2
</code></pre>
<p>我们能够看到 <code>a</code><code>Rc&lt;List&gt;</code> 的初始引用计数为 1接着每次调用 <code>clone</code>,计数会增加 1。当 <code>c</code> 离开作用域时,计数减 1。不必像调用 <code>Rc::clone</code> 增加引用计数那样调用一个函数来减少计数;<code>Drop</code> trait 的实现当 <code>Rc&lt;T&gt;</code> 值离开作用域时自动减少引用计数。</p>
<p>从这个例子我们所不能看到的是,在 <code>main</code> 的结尾当 <code>b</code> 然后是 <code>a</code> 离开作用域时,此处计数会是 0同时 <code>Rc&lt;List&gt;</code> 被完全清理。使用 <code>Rc&lt;T&gt;</code> 允许一个值有多个所有者,引用计数则确保只要任何所有者依然存在其值也保持有效。</p>
<p>通过不可变引用, <code>Rc&lt;T&gt;</code> 允许在程序的多个部分之间只读地共享数据。如果 <code>Rc&lt;T&gt;</code> 也允许多个可变引用,则会违反第四章讨论的借用规则之一:相同位置的多个可变借用可能造成数据竞争和不一致。不过可以修改数据是非常有用的!在下一部分,我们将讨论内部可变性模式和 <code>RefCell&lt;T&gt;</code> 类型,它可以与 <code>Rc&lt;T&gt;</code> 结合使用来处理不可变性的限制。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="refcellt-和内部可变性模式"><a class="header" href="#refcellt-和内部可变性模式"><code>RefCell&lt;T&gt;</code> 和内部可变性模式</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch15-05-interior-mutability.md">ch15-05-interior-mutability.md</a>
<br>
commit 5a3a64d60b0dd786c35ca4daada7a4d20da33e5e</p>
</blockquote>
<p><strong>内部可变性</strong><em>Interior mutability</em>)是 Rust 中的一个设计模式,它允许你即使在有不可变引用时也可以改变数据,这通常是借用规则所不允许的。为了改变数据,该模式在数据结构中使用 <code>unsafe</code> 代码来模糊 Rust 通常的可变性和借用规则。不安全代码表明我们在手动检查这些规则而不是让编译器替我们检查。第二十章会更详细地介绍不安全代码。</p>
<p>当可以确保代码在运行时会遵守借用规则,即使编译器不能保证的情况,可以选择使用那些运用内部可变性模式的类型。所涉及的 <code>unsafe</code> 代码将被封装进安全的 API 中,而外部类型仍然是不可变的。</p>
<p>让我们通过遵循内部可变性模式的 <code>RefCell&lt;T&gt;</code> 类型来开始探索。</p>
<h3 id="通过-refcellt-在运行时检查借用规则"><a class="header" href="#通过-refcellt-在运行时检查借用规则">通过 <code>RefCell&lt;T&gt;</code> 在运行时检查借用规则</a></h3>
<p>不同于 <code>Rc&lt;T&gt;</code><code>RefCell&lt;T&gt;</code> 代表其数据的唯一的所有权。那么是什么让 <code>RefCell&lt;T&gt;</code> 不同于像 <code>Box&lt;T&gt;</code> 这样的类型呢?回忆一下第四章所学的借用规则:</p>
<ol>
<li>在任意给定时刻,只能拥有一个可变引用或任意数量的不可变引用 <strong>之一</strong>(而不是两者)。</li>
<li>引用必须总是有效的。</li>
</ol>
<p>对于引用和 <code>Box&lt;T&gt;</code>,借用规则的不可变性作用于编译时。对于 <code>RefCell&lt;T&gt;</code>,这些不可变性作用于 <strong>运行时</strong>。对于引用,如果违反这些规则,会得到一个编译错误。而对于 <code>RefCell&lt;T&gt;</code>,如果违反这些规则程序会 panic 并退出。</p>
<p>在编译时检查借用规则的优势是这些错误将在开发过程的早期被捕获,同时对运行时没有性能影响,因为所有的分析都提前完成了。为此,在编译时检查借用规则是大部分情况的最佳选择,这也正是其为何是 Rust 的默认行为。</p>
<p>相反在运行时检查借用规则的好处则是允许出现特定内存安全的场景,而它们在编译时检查中是不允许的。静态分析,正如 Rust 编译器,是天生保守的。但代码的一些属性不可能通过分析代码发现:其中最著名的就是 <a href="https://zh.wikipedia.org/wiki/%E5%81%9C%E6%9C%BA%E9%97%AE%E9%A2%98">停机问题Halting Problem</a>,这超出了本书的范畴,不过如果你感兴趣的话这是一个值得研究的有趣主题。</p>
<p>因为一些分析是不可能的,如果 Rust 编译器不能通过所有权规则编译,它可能会拒绝一个正确的程序;从这种角度考虑它是保守的。如果 Rust 接受不正确的程序,那么用户也就不会相信 Rust 所做的保证了。然而,如果 Rust 拒绝正确的程序,虽然会给程序员带来不便,但不会带来灾难。<code>RefCell&lt;T&gt;</code> 正是用于当你确信代码遵守借用规则,而编译器不能理解和确定的时候。</p>
<p>类似于 <code>Rc&lt;T&gt;</code><code>RefCell&lt;T&gt;</code> 只能用于单线程场景。如果尝试在多线程上下文中使用<code>RefCell&lt;T&gt;</code>,会得到一个编译错误。第十六章会介绍如何在多线程程序中使用 <code>RefCell&lt;T&gt;</code> 的功能。</p>
<p>如下为选择 <code>Box&lt;T&gt;</code><code>Rc&lt;T&gt;</code><code>RefCell&lt;T&gt;</code> 的理由:</p>
<ul>
<li><code>Rc&lt;T&gt;</code> 允许相同数据有多个所有者;<code>Box&lt;T&gt;</code><code>RefCell&lt;T&gt;</code> 有单一所有者。</li>
<li><code>Box&lt;T&gt;</code> 允许在编译时执行不可变或可变借用检查;<code>Rc&lt;T&gt;</code>仅允许在编译时执行不可变借用检查;<code>RefCell&lt;T&gt;</code> 允许在运行时执行不可变或可变借用检查。</li>
<li>因为 <code>RefCell&lt;T&gt;</code> 允许在运行时执行可变借用检查,所以我们可以在即便 <code>RefCell&lt;T&gt;</code> 自身是不可变的情况下修改其内部的值。</li>
</ul>
<p>在不可变值内部改变值就是 <strong>内部可变性</strong> 模式。让我们看看何时内部可变性是有用的,并讨论这是如何成为可能的。</p>
<h3 id="内部可变性不可变值的可变借用"><a class="header" href="#内部可变性不可变值的可变借用">内部可变性:不可变值的可变借用</a></h3>
<p>借用规则的一个推论是当有一个不可变值时,不能可变地借用它。例如,如下代码不能编译:</p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let x = 5;
let y = &amp;mut x;
}</code></pre>
<p>如果尝试编译,会得到如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling borrowing v0.1.0 (file:///projects/borrowing)
error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable
--&gt; src/main.rs:3:13
|
3 | let y = &amp;mut x;
| ^^^^^^ cannot borrow as mutable
|
help: consider changing this to be mutable
|
2 | let mut x = 5;
| +++
For more information about this error, try `rustc --explain E0596`.
error: could not compile `borrowing` (bin "borrowing") due to 1 previous error
</code></pre>
<p>然而,特定情况下,令一个值在其方法内部能够修改自身,而在其他代码中仍视为不可变,是很有用的。值方法外部的代码就不能修改其值了。<code>RefCell&lt;T&gt;</code> 是一个获得内部可变性的方法。<code>RefCell&lt;T&gt;</code> 并没有完全绕开借用规则,编译器中的借用检查器允许内部可变性并相应地在运行时检查借用规则。如果违反了这些规则,会出现 panic 而不是编译错误。</p>
<p>让我们通过一个实际的例子来探索何处可以使用 <code>RefCell&lt;T&gt;</code> 来修改不可变值并看看为何这么做是有意义的。</p>
<h4 id="内部可变性的用例mock-对象"><a class="header" href="#内部可变性的用例mock-对象">内部可变性的用例mock 对象</a></h4>
<p>有时在测试中程序员会用某个类型替换另一个类型,以便观察特定的行为并断言它是被正确实现的。这个占位符类型被称为 <strong>测试替身</strong>(<em>test double</em>)。就像电影制作中的替身演员 (<em>stunt double</em>) 一样,替代演员完成高难度的场景。测试替身在运行测试时替代某个类型。<strong>mock 对象</strong> 是特定类型的测试替身,它们记录测试过程中发生了什么以便可以断言操作是正确的。</p>
<p>虽然 Rust 中的对象与其他语言中的对象并不是一回事Rust 也没有像其他语言那样在标准库中内建 mock 对象功能,不过我们确实可以创建一个与 mock 对象有着相同功能的结构体。</p>
<p>如下是一个我们想要测试的场景:我们在编写一个记录某个值与最大值的差距的库,并根据当前值与最大值的差距来发送消息。例如,这个库可以用于记录用户所允许的 API 调用数量限额。</p>
<p>该库只提供记录与最大值的差距,以及何种情况发送什么消息的功能。使用此库的程序则期望提供实际发送消息的机制:程序可以选择记录一条消息、发送 email、发送短信等等。库本身无需知道这些细节只需实现其提供的 <code>Messenger</code> trait 即可。示例 15-20 展示了库代码:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub trait Messenger {
fn send(&amp;self, msg: &amp;str);
}
pub struct LimitTracker&lt;'a, T: Messenger&gt; {
messenger: &amp;'a T,
value: usize,
max: usize,
}
impl&lt;'a, T&gt; LimitTracker&lt;'a, T&gt;
where
T: Messenger,
{
pub fn new(messenger: &amp;'a T, max: usize) -&gt; LimitTracker&lt;'a, T&gt; {
LimitTracker {
messenger,
value: 0,
max,
}
}
pub fn set_value(&amp;mut self, value: usize) {
self.value = value;
let percentage_of_max = self.value as f64 / self.max as f64;
if percentage_of_max &gt;= 1.0 {
self.messenger.send("Error: You are over your quota!");
} else if percentage_of_max &gt;= 0.9 {
self.messenger
.send("Urgent warning: You've used up over 90% of your quota!");
} else if percentage_of_max &gt;= 0.75 {
self.messenger
.send("Warning: You've used up over 75% of your quota!");
}
}
}</code></pre>
<p><span class="caption">示例 15-20一个记录某个值与最大值差距的库并根据此值的特定级别发出警告</span></p>
<p>这些代码中一个重要部分是拥有一个方法 <code>send</code><code>Messenger</code> trait其获取一个 <code>self</code> 的不可变引用和文本信息。这个 trait 是 mock 对象所需要实现的接口库,这样 mock 就能像一个真正的对象那样使用了。另一个重要的部分是我们需要测试 <code>LimitTracker</code><code>set_value</code> 方法的行为。可以改变传递的 <code>value</code> 参数的值,不过 <code>set_value</code> 并没有返回任何可供断言的值。我们希望能够说,如果我们创建一个实现了 <code>Messenger</code> trait 和具有特定 <code>max</code> 值的 <code>LimitTracker</code> 时,当传递不同 <code>value</code> 值时,消息发送者应被告知发送合适的消息。</p>
<p>我们所需的 mock 对象是,调用 <code>send</code> 并不实际发送 email 或消息,而是只记录信息被通知要发送了。可以新建一个 mock 对象实例,用其创建 <code>LimitTracker</code>,调用 <code>LimitTracker</code><code>set_value</code> 方法,然后检查 mock 对象是否有我们期望的消息。示例 15-21 展示了一个如此尝试的 mock 对象实现,不过借用检查器并不允许:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">pub trait Messenger {
</span><span class="boring"> fn send(&amp;self, msg: &amp;str);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct LimitTracker&lt;'a, T: Messenger&gt; {
</span><span class="boring"> messenger: &amp;'a T,
</span><span class="boring"> value: usize,
</span><span class="boring"> max: usize,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl&lt;'a, T&gt; LimitTracker&lt;'a, T&gt;
</span><span class="boring">where
</span><span class="boring"> T: Messenger,
</span><span class="boring">{
</span><span class="boring"> pub fn new(messenger: &amp;'a T, max: usize) -&gt; LimitTracker&lt;'a, T&gt; {
</span><span class="boring"> LimitTracker {
</span><span class="boring"> messenger,
</span><span class="boring"> value: 0,
</span><span class="boring"> max,
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn set_value(&amp;mut self, value: usize) {
</span><span class="boring"> self.value = value;
</span><span class="boring">
</span><span class="boring"> let percentage_of_max = self.value as f64 / self.max as f64;
</span><span class="boring">
</span><span class="boring"> if percentage_of_max &gt;= 1.0 {
</span><span class="boring"> self.messenger.send("Error: You are over your quota!");
</span><span class="boring"> } else if percentage_of_max &gt;= 0.9 {
</span><span class="boring"> self.messenger
</span><span class="boring"> .send("Urgent warning: You've used up over 90% of your quota!");
</span><span class="boring"> } else if percentage_of_max &gt;= 0.75 {
</span><span class="boring"> self.messenger
</span><span class="boring"> .send("Warning: You've used up over 75% of your quota!");
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>#[cfg(test)]
mod tests {
use super::*;
struct MockMessenger {
sent_messages: Vec&lt;String&gt;,
}
impl MockMessenger {
fn new() -&gt; MockMessenger {
MockMessenger {
sent_messages: vec![],
}
}
}
impl Messenger for MockMessenger {
fn send(&amp;self, message: &amp;str) {
self.sent_messages.push(String::from(message));
}
}
#[test]
fn it_sends_an_over_75_percent_warning_message() {
let mock_messenger = MockMessenger::new();
let mut limit_tracker = LimitTracker::new(&amp;mock_messenger, 100);
limit_tracker.set_value(80);
assert_eq!(mock_messenger.sent_messages.len(), 1);
}
}</code></pre>
<p><span class="caption">示例 15-21尝试实现 <code>MockMessenger</code>,借用检查器不允许这么做</span></p>
<p>测试代码定义了一个 <code>MockMessenger</code> 结构体,其 <code>sent_messages</code> 字段为一个 <code>String</code> 值的 <code>Vec</code> 用来记录被告知发送的消息。我们还定义了一个关联函数 <code>new</code> 以便于新建从空消息列表开始的 <code>MockMessenger</code> 值。接着为 <code>MockMessenger</code> 实现 <code>Messenger</code> trait 这样就可以为 <code>LimitTracker</code> 提供一个 <code>MockMessenger</code>。在 <code>send</code> 方法的定义中,获取传入的消息作为参数并储存在 <code>MockMessenger</code><code>sent_messages</code> 列表中。</p>
<p>在测试中,我们测试了当 <code>LimitTracker</code> 被告知将 <code>value</code> 设置为超过 <code>max</code> 值 75% 的某个值。首先新建一个 <code>MockMessenger</code>,其从空消息列表开始。接着新建一个 <code>LimitTracker</code> 并传递新建 <code>MockMessenger</code> 的引用和 <code>max</code> 值 100。我们使用值 80 调用 <code>LimitTracker</code><code>set_value</code> 方法,这超过了 100 的 75%。接着断言 <code>MockMessenger</code> 中记录的消息列表应该有一条消息。</p>
<p>然而,这个测试是有问题的:</p>
<pre><code class="language-console">$ cargo test
Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker)
error[E0596]: cannot borrow `self.sent_messages` as mutable, as it is behind a `&amp;` reference
--&gt; src/lib.rs:58:13
|
58 | self.sent_messages.push(String::from(message));
| ^^^^^^^^^^^^^^^^^^ `self` is a `&amp;` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference in the `impl` method and the `trait` definition
|
2 ~ fn send(&amp;mut self, msg: &amp;str);
3 | }
...
56 | impl Messenger for MockMessenger {
57 ~ fn send(&amp;mut self, message: &amp;str) {
|
For more information about this error, try `rustc --explain E0596`.
error: could not compile `limit-tracker` (lib test) due to 1 previous error
</code></pre>
<p>不能修改 <code>MockMessenger</code> 来记录消息,因为 <code>send</code> 方法获取了 <code>self</code> 的不可变引用。我们也不能参考错误文本的建议使用 <code>&amp;mut self</code> 替代,因为这样 <code>send</code> 的签名就不符合 <code>Messenger</code> trait 定义中的签名了(可以试着这么改,看看会出现什么错误信息)。</p>
<p>这正是内部可变性的用武之地!我们将通过 <code>RefCell</code> 来储存 <code>sent_messages</code>,然后 <code>send</code> 将能够修改 <code>sent_messages</code> 并储存消息。示例 15-22 展示了代码:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Messenger {
</span><span class="boring"> fn send(&amp;self, msg: &amp;str);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct LimitTracker&lt;'a, T: Messenger&gt; {
</span><span class="boring"> messenger: &amp;'a T,
</span><span class="boring"> value: usize,
</span><span class="boring"> max: usize,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl&lt;'a, T&gt; LimitTracker&lt;'a, T&gt;
</span><span class="boring">where
</span><span class="boring"> T: Messenger,
</span><span class="boring">{
</span><span class="boring"> pub fn new(messenger: &amp;'a T, max: usize) -&gt; LimitTracker&lt;'a, T&gt; {
</span><span class="boring"> LimitTracker {
</span><span class="boring"> messenger,
</span><span class="boring"> value: 0,
</span><span class="boring"> max,
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn set_value(&amp;mut self, value: usize) {
</span><span class="boring"> self.value = value;
</span><span class="boring">
</span><span class="boring"> let percentage_of_max = self.value as f64 / self.max as f64;
</span><span class="boring">
</span><span class="boring"> if percentage_of_max &gt;= 1.0 {
</span><span class="boring"> self.messenger.send("Error: You are over your quota!");
</span><span class="boring"> } else if percentage_of_max &gt;= 0.9 {
</span><span class="boring"> self.messenger
</span><span class="boring"> .send("Urgent warning: You've used up over 90% of your quota!");
</span><span class="boring"> } else if percentage_of_max &gt;= 0.75 {
</span><span class="boring"> self.messenger
</span><span class="boring"> .send("Warning: You've used up over 75% of your quota!");
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
struct MockMessenger {
sent_messages: RefCell&lt;Vec&lt;String&gt;&gt;,
}
impl MockMessenger {
fn new() -&gt; MockMessenger {
MockMessenger {
sent_messages: RefCell::new(vec![]),
}
}
}
impl Messenger for MockMessenger {
fn send(&amp;self, message: &amp;str) {
self.sent_messages.borrow_mut().push(String::from(message));
}
}
#[test]
fn it_sends_an_over_75_percent_warning_message() {
// --snip--
<span class="boring"> let mock_messenger = MockMessenger::new();
</span><span class="boring"> let mut limit_tracker = LimitTracker::new(&amp;mock_messenger, 100);
</span><span class="boring">
</span><span class="boring"> limit_tracker.set_value(80);
</span>
assert_eq!(mock_messenger.sent_messages.borrow().len(), 1);
}
}</code></pre>
<p><span class="caption">示例 15-22使用 <code>RefCell&lt;T&gt;</code> 能够在外部值被认为是不可变的情况下修改内部值</span></p>
<p>现在 <code>sent_messages</code> 字段的类型是 <code>RefCell&lt;Vec&lt;String&gt;&gt;</code> 而不是 <code>Vec&lt;String&gt;</code>。在 <code>new</code> 函数中新建了一个 <code>RefCell&lt;Vec&lt;String&gt;&gt;</code> 实例替代空 vector。</p>
<p>对于 <code>send</code> 方法的实现,第一个参数仍为 <code>self</code> 的不可变借用,这是符合方法定义的。我们调用 <code>self.sent_messages</code><code>RefCell</code><code>borrow_mut</code> 方法来获取 <code>RefCell</code> 中值的可变引用,这是一个 vector。接着可以对 vector 的可变引用调用 <code>push</code> 以便记录测试过程中看到的消息。</p>
<p>最后必须做出的修改位于断言中:为了看到其内部 vector 中有多少个项,需要调用 <code>RefCell</code><code>borrow</code> 以获取 vector 的不可变引用。</p>
<p>现在我们见识了如何使用 <code>RefCell&lt;T&gt;</code>,让我们研究一下它怎样工作的!</p>
<h3 id="refcellt-在运行时记录借用"><a class="header" href="#refcellt-在运行时记录借用"><code>RefCell&lt;T&gt;</code> 在运行时记录借用</a></h3>
<p>当创建不可变和可变引用时,我们分别使用 <code>&amp;</code><code>&amp;mut</code> 语法。对于 <code>RefCell&lt;T&gt;</code> 来说,则是 <code>borrow</code><code>borrow_mut</code> 方法,这属于 <code>RefCell&lt;T&gt;</code> 安全 API 的一部分。<code>borrow</code> 方法返回 <code>Ref&lt;T&gt;</code> 类型的智能指针,<code>borrow_mut</code> 方法返回 <code>RefMut&lt;T&gt;</code> 类型的智能指针。这两个类型都实现了 <code>Deref</code>,所以可以当作常规引用对待。</p>
<p><code>RefCell&lt;T&gt;</code> 记录当前有多少个活动的 <code>Ref&lt;T&gt;</code><code>RefMut&lt;T&gt;</code> 智能指针。每次调用 <code>borrow</code><code>RefCell&lt;T&gt;</code> 将活动的不可变借用计数加一。当 <code>Ref&lt;T&gt;</code> 值离开作用域时,不可变借用计数减一。就像编译时借用规则一样,<code>RefCell&lt;T&gt;</code> 在任何时候只允许有多个不可变借用或一个可变借用。</p>
<p>如果我们尝试违反这些规则,相比引用时的编译时错误,<code>RefCell&lt;T&gt;</code> 的实现会在运行时出现 panic。示例 15-23 展示了对示例 15-22 中 <code>send</code> 实现的修改,这里我们故意尝试在相同作用域创建两个可变借用以便演示 <code>RefCell&lt;T&gt;</code> 不允许我们在运行时这么做:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore panics"><span class="boring">pub trait Messenger {
</span><span class="boring"> fn send(&amp;self, msg: &amp;str);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct LimitTracker&lt;'a, T: Messenger&gt; {
</span><span class="boring"> messenger: &amp;'a T,
</span><span class="boring"> value: usize,
</span><span class="boring"> max: usize,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl&lt;'a, T&gt; LimitTracker&lt;'a, T&gt;
</span><span class="boring">where
</span><span class="boring"> T: Messenger,
</span><span class="boring">{
</span><span class="boring"> pub fn new(messenger: &amp;'a T, max: usize) -&gt; LimitTracker&lt;'a, T&gt; {
</span><span class="boring"> LimitTracker {
</span><span class="boring"> messenger,
</span><span class="boring"> value: 0,
</span><span class="boring"> max,
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn set_value(&amp;mut self, value: usize) {
</span><span class="boring"> self.value = value;
</span><span class="boring">
</span><span class="boring"> let percentage_of_max = self.value as f64 / self.max as f64;
</span><span class="boring">
</span><span class="boring"> if percentage_of_max &gt;= 1.0 {
</span><span class="boring"> self.messenger.send("Error: You are over your quota!");
</span><span class="boring"> } else if percentage_of_max &gt;= 0.9 {
</span><span class="boring"> self.messenger
</span><span class="boring"> .send("Urgent warning: You've used up over 90% of your quota!");
</span><span class="boring"> } else if percentage_of_max &gt;= 0.75 {
</span><span class="boring"> self.messenger
</span><span class="boring"> .send("Warning: You've used up over 75% of your quota!");
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring"> use std::cell::RefCell;
</span><span class="boring">
</span><span class="boring"> struct MockMessenger {
</span><span class="boring"> sent_messages: RefCell&lt;Vec&lt;String&gt;&gt;,
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> impl MockMessenger {
</span><span class="boring"> fn new() -&gt; MockMessenger {
</span><span class="boring"> MockMessenger {
</span><span class="boring"> sent_messages: RefCell::new(vec![]),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span> impl Messenger for MockMessenger {
fn send(&amp;self, message: &amp;str) {
let mut one_borrow = self.sent_messages.borrow_mut();
let mut two_borrow = self.sent_messages.borrow_mut();
one_borrow.push(String::from(message));
two_borrow.push(String::from(message));
}
}
<span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn it_sends_an_over_75_percent_warning_message() {
</span><span class="boring"> let mock_messenger = MockMessenger::new();
</span><span class="boring"> let mut limit_tracker = LimitTracker::new(&amp;mock_messenger, 100);
</span><span class="boring">
</span><span class="boring"> limit_tracker.set_value(80);
</span><span class="boring">
</span><span class="boring"> assert_eq!(mock_messenger.sent_messages.borrow().len(), 1);
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 15-23在同一作用域中创建两个可变引用并观察 <code>RefCell&lt;T&gt;</code> panic</span></p>
<p>这里为 <code>borrow_mut</code> 返回的 <code>RefMut</code> 智能指针创建了 <code>one_borrow</code> 变量。接着用相同的方式在变量 <code>two_borrow</code> 创建了另一个可变借用。这会在相同作用域中创建两个可变引用,这是不允许的。当运行库的测试时,示例 15-23 编译时不会有任何错误,不过测试会失败:</p>
<pre><code class="language-console">$ cargo test
Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.91s
Running unittests src/lib.rs (target/debug/deps/limit_tracker-e599811fa246dbde)
running 1 test
test tests::it_sends_an_over_75_percent_warning_message ... FAILED
failures:
---- tests::it_sends_an_over_75_percent_warning_message stdout ----
thread 'tests::it_sends_an_over_75_percent_warning_message' panicked at src/lib.rs:60:53:
already borrowed: BorrowMutError
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::it_sends_an_over_75_percent_warning_message
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
</code></pre>
<p>注意代码 panic 和信息 <code>already borrowed: BorrowMutError</code>。这也就是 <code>RefCell&lt;T&gt;</code> 如何在运行时处理违反借用规则的情况。</p>
<p>像我们这里这样选择在运行时捕获借用错误而不是编译时意味着会发现在开发过程的后期才会发现的潜在错误,甚至有可能发布到生产环境才会发现。还会因为在运行时而不是编译时记录借用而导致少量的运行时性能惩罚。然而,使用 <code>RefCell</code> 使得在只允许不可变值的上下文中编写修改自身以记录消息的 mock 对象成为可能。虽然有取舍,但是我们可以选择使用 <code>RefCell&lt;T&gt;</code> 来获得比常规引用所能提供的更多的功能。</p>
<h3 id="结合-rct-和-refcellt-来拥有多个可变数据所有者"><a class="header" href="#结合-rct-和-refcellt-来拥有多个可变数据所有者">结合 <code>Rc&lt;T&gt;</code><code>RefCell&lt;T&gt;</code> 来拥有多个可变数据所有者</a></h3>
<p><code>RefCell&lt;T&gt;</code> 的一个常见用法是与 <code>Rc&lt;T&gt;</code> 结合。回忆一下 <code>Rc&lt;T&gt;</code> 允许对相同数据有多个所有者,不过只能提供数据的不可变访问。如果有一个储存了 <code>RefCell&lt;T&gt;</code><code>Rc&lt;T&gt;</code> 的话,就可以得到有多个所有者 <strong>并且</strong> 可以修改的值了!</p>
<p>例如,回忆示例 15-18 的 cons list 的例子中使用 <code>Rc&lt;T&gt;</code> 使得多个列表共享另一个列表的所有权。因为 <code>Rc&lt;T&gt;</code> 只存放不可变值,所以一旦创建了这些列表值后就不能修改。让我们加入 <code>RefCell&lt;T&gt;</code> 来获得修改列表中值的能力。示例 15-24 展示了通过在 <code>Cons</code> 定义中使用 <code>RefCell&lt;T&gt;</code>,我们就允许修改所有列表中的值了:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)]
enum List {
Cons(Rc&lt;RefCell&lt;i32&gt;&gt;, Rc&lt;List&gt;),
Nil,
}
use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let value = Rc::new(RefCell::new(5));
let a = Rc::new(Cons(Rc::clone(&amp;value), Rc::new(Nil)));
let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&amp;a));
let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&amp;a));
*value.borrow_mut() += 10;
println!("a after = {a:?}");
println!("b after = {b:?}");
println!("c after = {c:?}");
}</code></pre></pre>
<p><span class="caption">示例 15-24使用 <code>Rc&lt;RefCell&lt;i32&gt;&gt;</code> 创建可以修改的 <code>List</code></span></p>
<p>这里创建了一个 <code>Rc&lt;RefCell&lt;i32&gt;&gt;</code> 实例并储存在变量 <code>value</code> 中以便之后直接访问。接着在 <code>a</code> 中用包含 <code>value</code><code>Cons</code> 成员创建了一个 <code>List</code>。需要克隆 <code>value</code> 以便 <code>a</code><code>value</code> 都能拥有其内部值 <code>5</code> 的所有权,而不是将所有权从 <code>value</code> 移动到 <code>a</code> 或者让 <code>a</code> 借用 <code>value</code></p>
<p>我们将列表 <code>a</code> 封装进了 <code>Rc&lt;T&gt;</code> 这样当创建列表 <code>b</code><code>c</code> 时,它们都可以引用 <code>a</code>,正如示例 15-18 一样。</p>
<p>一旦创建了列表 <code>a</code><code>b</code><code>c</code>,我们将 <code>value</code> 的值加 10。为此对 <code>value</code> 调用了 <code>borrow_mut</code>,这里使用了第五章讨论的自动解引用功能(<a href="ch05-03-method-syntax.html#--%E8%BF%90%E7%AE%97%E7%AC%A6%E5%88%B0%E5%93%AA%E5%8E%BB%E4%BA%86"><code>-&gt;</code> 运算符到哪去了?”</a> 部分)来解引用 <code>Rc&lt;T&gt;</code> 以获取其内部的 <code>RefCell&lt;T&gt;</code> 值。<code>borrow_mut</code> 方法返回 <code>RefMut&lt;T&gt;</code> 智能指针,可以对其使用解引用运算符并修改其内部值。</p>
<p>当我们打印出 <code>a</code><code>b</code><code>c</code> 时,可以看到它们都拥有修改后的值 15 而不是 5</p>
<pre><code class="language-console">$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.63s
Running `target/debug/cons-list`
a after = Cons(RefCell { value: 15 }, Nil)
b after = Cons(RefCell { value: 3 }, Cons(RefCell { value: 15 }, Nil))
c after = Cons(RefCell { value: 4 }, Cons(RefCell { value: 15 }, Nil))
</code></pre>
<p>这是非常巧妙的!通过使用 <code>RefCell&lt;T&gt;</code>,我们可以拥有一个表面上不可变的 <code>List</code>,不过可以使用 <code>RefCell&lt;T&gt;</code> 中提供内部可变性的方法来在需要时修改数据。<code>RefCell&lt;T&gt;</code> 的运行时借用规则检查也确实保护我们免于出现数据竞争——有时为了数据结构的灵活性而付出一些性能是值得的。注意 <code>RefCell&lt;T&gt;</code> 不能用于多线程代码!<code>Mutex&lt;T&gt;</code> 是一个线程安全版本的 <code>RefCell&lt;T&gt;</code> ,我们会在第十六章讨论 <code>Mutex&lt;T&gt;</code></p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="引用循环与内存泄漏"><a class="header" href="#引用循环与内存泄漏">引用循环与内存泄漏</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch15-06-reference-cycles.md">ch15-06-reference-cycles.md</a>
<br>
commit c06006157b14b3d47b5c716fc392b77f3b2e21ce</p>
</blockquote>
<p>Rust 的内存安全性保证使其难以意外地制造永远也不会被清理的内存(被称为 <strong>内存泄漏</strong><em>memory leak</em>但并不是不可能。Rust 并不保证完全防止内存泄漏,这意味着内存泄漏在 Rust 中被认为是内存安全的。这一点可以通过 <code>Rc&lt;T&gt;</code><code>RefCell&lt;T&gt;</code> 看出:创建引用循环的可能性是存在的。这会造成内存泄漏,因为每一项的引用计数永远也到不了 0持有的数据也就永远不会被释放。</p>
<h3 id="制造引用循环"><a class="header" href="#制造引用循环">制造引用循环</a></h3>
<p>让我们看看引用循环是如何发生的以及如何避免它。以示例 15-25 中的 <code>List</code> 枚举和 <code>tail</code> 方法的定义开始:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
enum List {
Cons(i32, RefCell&lt;Rc&lt;List&gt;&gt;),
Nil,
}
impl List {
fn tail(&amp;self) -&gt; Option&lt;&amp;RefCell&lt;Rc&lt;List&gt;&gt;&gt; {
match self {
Cons(_, item) =&gt; Some(item),
Nil =&gt; None,
}
}
}
fn main() {}</code></pre></pre>
<p><span class="caption">示例 15-25: 一个存放 <code>RefCell</code> 的 cons list 定义,这样可以修改 <code>Cons</code> 成员所引用的数据</span></p>
<p>这里采用了示例 15-5 中 <code>List</code> 定义的另一种变体。现在 <code>Cons</code> 成员的第二个元素是 <code>RefCell&lt;Rc&lt;List&gt;&gt;</code>,这意味着不同于像示例 15-24 那样能够修改 <code>i32</code> 的值,我们希望能够修改 <code>Cons</code> 成员所指向的 <code>List</code>。这里还增加了一个 <code>tail</code> 方法来方便我们在有 <code>Cons</code> 成员的时候访问其第二项。</p>
<p>在示例 15-26 中增加了一个 <code>main</code> 函数,其使用了示例 15-25 中的定义。这些代码在 <code>a</code> 中创建了一个列表,一个指向 <code>a</code> 中列表的 <code>b</code> 列表,接着修改 <code>a</code> 中的列表指向 <code>b</code> 中的列表,这会创建一个引用循环。在这个过程的多个位置有 <code>println!</code> 语句展示引用计数。</p>
<p><span class="filename">文件src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">use crate::List::{Cons, Nil};
</span><span class="boring">use std::cell::RefCell;
</span><span class="boring">use std::rc::Rc;
</span><span class="boring">
</span><span class="boring">#[derive(Debug)]
</span><span class="boring">enum List {
</span><span class="boring"> Cons(i32, RefCell&lt;Rc&lt;List&gt;&gt;),
</span><span class="boring"> Nil,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl List {
</span><span class="boring"> fn tail(&amp;self) -&gt; Option&lt;&amp;RefCell&lt;Rc&lt;List&gt;&gt;&gt; {
</span><span class="boring"> match self {
</span><span class="boring"> Cons(_, item) =&gt; Some(item),
</span><span class="boring"> Nil =&gt; None,
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));
println!("a initial rc count = {}", Rc::strong_count(&amp;a));
println!("a next item = {:?}", a.tail());
let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&amp;a))));
println!("a rc count after b creation = {}", Rc::strong_count(&amp;a));
println!("b initial rc count = {}", Rc::strong_count(&amp;b));
println!("b next item = {:?}", b.tail());
if let Some(link) = a.tail() {
*link.borrow_mut() = Rc::clone(&amp;b);
}
println!("b rc count after changing a = {}", Rc::strong_count(&amp;b));
println!("a rc count after changing a = {}", Rc::strong_count(&amp;a));
// Uncomment the next line to see that we have a cycle;
// it will overflow the stack
// println!("a next item = {:?}", a.tail());
}</code></pre></pre>
<p><span class="caption">示例 15-26创建一个引用循环两个 <code>List</code> 值互相指向彼此</span></p>
<p>这里在变量 <code>a</code> 中创建了一个 <code>Rc&lt;List&gt;</code> 实例来存放初值为 <code>5, Nil</code><code>List</code> 值。接着在变量 <code>b</code> 中创建了存放包含值 10 和指向列表 <code>a</code><code>List</code> 的另一个 <code>Rc&lt;List&gt;</code> 实例。</p>
<p>最后,修改 <code>a</code> 使其指向 <code>b</code> 而不是 <code>Nil</code>,这就创建了一个循环。为此需要使用 <code>tail</code> 方法获取 <code>a</code><code>RefCell&lt;Rc&lt;List&gt;&gt;</code> 的引用,并放入变量 <code>link</code> 中。接着使用 <code>RefCell&lt;Rc&lt;List&gt;&gt;</code><code>borrow_mut</code> 方法将其值从存放 <code>Nil</code><code>Rc&lt;List&gt;</code> 修改为 <code>b</code> 中的 <code>Rc&lt;List&gt;</code></p>
<p>如果保持最后的 <code>println!</code> 行注释并运行代码,会得到如下输出:</p>
<pre><code class="language-console">$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.53s
Running `target/debug/cons-list`
a initial rc count = 1
a next item = Some(RefCell { value: Nil })
a rc count after b creation = 2
b initial rc count = 1
b next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) })
b rc count after changing a = 2
a rc count after changing a = 2
</code></pre>
<p>可以看到将列表 <code>a</code> 修改为指向 <code>b</code> 之后, <code>a</code><code>b</code> 中的 <code>Rc&lt;List&gt;</code> 实例的引用计数都是 2。在 <code>main</code> 的结尾Rust 丢弃 <code>b</code>,这会使 <code>b</code> <code>Rc&lt;List&gt;</code> 实例的引用计数从 2 减为 1。然而<code>b</code> <code>Rc&lt;List&gt;</code> 不能被回收,因为其引用计数是 1 而不是 0。接下来 Rust 会丢弃 <code>a</code><code>a</code> <code>Rc&lt;List&gt;</code> 实例的引用计数从 2 减为 1。这个实例也不能被回收因为 <code>b</code> <code>Rc&lt;List&gt;</code> 实例依然引用它,所以其引用计数是 1。这些列表的内存将永远保持未被回收的状态。为了更形象的展示我们创建了一个如图 15-4 所示的引用循环:</p>
<img alt="Reference cycle of lists" src="img/trpl15-04.svg" class="center" />
<p><span class="caption">图 15-4: 列表 <code>a</code><code>b</code> 彼此互相指向形成引用循环</span></p>
<p>如果取消最后 <code>println!</code> 的注释并运行程序Rust 会尝试打印出 <code>a</code> 指向 <code>b</code> 指向 <code>a</code> 这样的循环直到栈溢出。</p>
<p>相比真实世界的程序,这个例子中创建引用循环的结果并不可怕。创建了引用循环之后程序立刻就结束了。如果在更为复杂的程序中并在循环里分配了很多内存并占有很长时间,这个程序会使用多于它所需要的内存,并有可能压垮系统并造成没有内存可供使用。</p>
<p>创建引用循环并不容易,但也不是不可能。如果你有包含 <code>Rc&lt;T&gt;</code><code>RefCell&lt;T&gt;</code> 值或类似的嵌套结合了内部可变性和引用计数的类型,请务必小心确保你没有形成一个引用循环;你无法指望 Rust 帮你捕获它们。创建引用循环是一个程序上的逻辑 bug你应该使用自动化测试、代码评审和其他软件开发最佳实践来使其最小化。</p>
<p>另一个解决方案是重新组织数据结构,使得一部分引用拥有所有权而另一部分没有。换句话说,循环将由一些拥有所有权的关系和一些无所有权的关系组成,只有所有权关系才能影响值是否可以被丢弃。在示例 15-25 中,我们总是希望 <code>Cons</code> 成员拥有其列表,所以重新组织数据结构是不可能的。让我们看看一个由父节点和子节点构成的图的例子,观察何时是使用无所有权的关系来避免引用循环的合适时机。</p>
<h3 id="避免引用循环将-rct-变为-weakt"><a class="header" href="#避免引用循环将-rct-变为-weakt">避免引用循环:将 <code>Rc&lt;T&gt;</code> 变为 <code>Weak&lt;T&gt;</code></a></h3>
<p>到目前为止,我们已经展示了调用 <code>Rc::clone</code> 会增加 <code>Rc&lt;T&gt;</code> 实例的 <code>strong_count</code>,和只在其 <code>strong_count</code> 为 0 时才会被清理的 <code>Rc&lt;T&gt;</code> 实例。你也可以通过调用 <code>Rc::downgrade</code> 并传递 <code>Rc&lt;T&gt;</code> 实例的引用来创建其值的 <strong>弱引用</strong><em>weak reference</em>)。强引用代表如何共享 <code>Rc&lt;T&gt;</code> 实例的所有权。弱引用并不属于所有权关系,当 <code>Rc&lt;T&gt;</code> 实例被清理时其计数没有影响。它们不会造成引用循环,因为任何涉及弱引用的循环会在其相关的值的强引用计数为 0 时被打断。</p>
<p>调用 <code>Rc::downgrade</code> 时会得到 <code>Weak&lt;T&gt;</code> 类型的智能指针。不同于将 <code>Rc&lt;T&gt;</code> 实例的 <code>strong_count</code> 加 1调用 <code>Rc::downgrade</code> 会将 <code>weak_count</code> 加 1。<code>Rc&lt;T&gt;</code> 类型使用 <code>weak_count</code> 来记录其存在多少个 <code>Weak&lt;T&gt;</code> 引用,类似于 <code>strong_count</code>。其区别在于 <code>weak_count</code> 无需计数为 0 就能使 <code>Rc&lt;T&gt;</code> 实例被清理。</p>
<p>强引用代表如何共享 <code>Rc&lt;T&gt;</code> 实例的所有权,但弱引用并不属于所有权关系。它们不会造成引用循环,因为任何弱引用的循环会在其相关的强引用计数为 0 时被打断。</p>
<p>因为 <code>Weak&lt;T&gt;</code> 引用的值可能已经被丢弃了,为了使用 <code>Weak&lt;T&gt;</code> 所指向的值,我们必须确保其值仍然有效。为此可以调用 <code>Weak&lt;T&gt;</code> 实例的 <code>upgrade</code> 方法,这会返回 <code>Option&lt;Rc&lt;T&gt;&gt;</code>。如果 <code>Rc&lt;T&gt;</code> 值还未被丢弃,则结果是 <code>Some</code>;如果 <code>Rc&lt;T&gt;</code> 已被丢弃,则结果是 <code>None</code>。因为 <code>upgrade</code> 返回一个 <code>Option&lt;Rc&lt;T&gt;&gt;</code>Rust 会确保处理 <code>Some</code><code>None</code> 的情况,所以它不会返回非法指针。</p>
<p>我们会创建一个某项知道其子项和父项的树形结构的例子,而不是只知道其下一项的列表。</p>
<h4 id="创建树形数据结构带有子节点的-node"><a class="header" href="#创建树形数据结构带有子节点的-node">创建树形数据结构:带有子节点的 <code>Node</code></a></h4>
<p>在最开始,我们将会构建一个带有子节点的树。让我们创建一个用于存放其拥有所有权的 <code>i32</code> 值和其子节点引用的 <code>Node</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
struct Node {
value: i32,
children: RefCell&lt;Vec&lt;Rc&lt;Node&gt;&gt;&gt;,
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let leaf = Rc::new(Node {
</span><span class="boring"> value: 3,
</span><span class="boring"> children: RefCell::new(vec![]),
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> let branch = Rc::new(Node {
</span><span class="boring"> value: 5,
</span><span class="boring"> children: RefCell::new(vec![Rc::clone(&amp;leaf)]),
</span><span class="boring"> });
</span><span class="boring">}</span></code></pre></pre>
<p>我们希望 <code>Node</code> 能够拥有其子节点,同时也希望能将所有权共享给变量,以便可以直接访问树中的每一个 <code>Node</code>,为此 <code>Vec&lt;T&gt;</code> 的项的类型被定义为 <code>Rc&lt;Node&gt;</code>。我们还希望能修改其他节点的子节点,所以 <code>children</code><code>Vec&lt;Rc&lt;Node&gt;&gt;</code> 被放进了 <code>RefCell&lt;T&gt;</code></p>
<p>接下来,使用此结构体定义来创建一个叫做 <code>leaf</code> 的带有值 3 且没有子节点的 <code>Node</code> 实例,和另一个带有值 5 并以 <code>leaf</code> 作为子节点的实例 <code>branch</code>,如示例 15-27 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">use std::cell::RefCell;
</span><span class="boring">use std::rc::Rc;
</span><span class="boring">
</span><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Node {
</span><span class="boring"> value: i32,
</span><span class="boring"> children: RefCell&lt;Vec&lt;Rc&lt;Node&gt;&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let leaf = Rc::new(Node {
value: 3,
children: RefCell::new(vec![]),
});
let branch = Rc::new(Node {
value: 5,
children: RefCell::new(vec![Rc::clone(&amp;leaf)]),
});
}</code></pre></pre>
<p><span class="caption">示例 15-27创建没有子节点的 <code>leaf</code> 节点和以 <code>leaf</code> 作为子节点的 <code>branch</code> 节点</span></p>
<p>这里克隆了 <code>leaf</code> 中的 <code>Rc&lt;Node&gt;</code> 并储存在 <code>branch</code> 中,这意味着 <code>leaf</code> 中的 <code>Node</code> 现在有两个所有者:<code>leaf</code><code>branch</code>。可以通过 <code>branch.children</code><code>branch</code> 中获得 <code>leaf</code>,不过无法从 <code>leaf</code><code>branch</code><code>leaf</code> 没有到 <code>branch</code> 的引用且并不知道它们相互关联。我们希望 <code>leaf</code> 知道 <code>branch</code> 是其父节点。稍后我们会这么做。</p>
<h4 id="增加从子到父的引用"><a class="header" href="#增加从子到父的引用">增加从子到父的引用</a></h4>
<p>为了使子节点知道其父节点,需要在 <code>Node</code> 结构体定义中增加一个 <code>parent</code> 字段。问题是 <code>parent</code> 的类型应该是什么。我们知道其不能包含 <code>Rc&lt;T&gt;</code>,因为这样 <code>leaf.parent</code> 将会指向 <code>branch</code><code>branch.children</code> 会包含 <code>leaf</code> 的指针,这会形成引用循环,会造成其 <code>strong_count</code> 永远也不会为 0。</p>
<p>现在换一种方式思考这个关系,父节点应该拥有其子节点:如果父节点被丢弃了,其子节点也应该被丢弃。然而子节点不应该拥有其父节点:如果丢弃子节点,其父节点应该依然存在。这正是弱引用的例子!</p>
<p>所以 <code>parent</code> 使用 <code>Weak&lt;T&gt;</code> 类型而不是 <code>Rc&lt;T&gt;</code>,具体来说是 <code>RefCell&lt;Weak&lt;Node&gt;&gt;</code>。现在 <code>Node</code> 结构体定义看起来像这样:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::cell::RefCell;
use std::rc::{Rc, Weak};
#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell&lt;Weak&lt;Node&gt;&gt;,
children: RefCell&lt;Vec&lt;Rc&lt;Node&gt;&gt;&gt;,
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let leaf = Rc::new(Node {
</span><span class="boring"> value: 3,
</span><span class="boring"> parent: RefCell::new(Weak::new()),
</span><span class="boring"> children: RefCell::new(vec![]),
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
</span><span class="boring">
</span><span class="boring"> let branch = Rc::new(Node {
</span><span class="boring"> value: 5,
</span><span class="boring"> parent: RefCell::new(Weak::new()),
</span><span class="boring"> children: RefCell::new(vec![Rc::clone(&amp;leaf)]),
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> *leaf.parent.borrow_mut() = Rc::downgrade(&amp;branch);
</span><span class="boring">
</span><span class="boring"> println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
</span><span class="boring">}</span></code></pre></pre>
<p>这样,一个节点就能够引用其父节点,但不拥有其父节点。在示例 15-28 中,我们更新 <code>main</code> 来使用新定义以便 <code>leaf</code> 节点可以通过 <code>branch</code> 引用其父节点:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">use std::cell::RefCell;
</span><span class="boring">use std::rc::{Rc, Weak};
</span><span class="boring">
</span><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Node {
</span><span class="boring"> value: i32,
</span><span class="boring"> parent: RefCell&lt;Weak&lt;Node&gt;&gt;,
</span><span class="boring"> children: RefCell&lt;Vec&lt;Rc&lt;Node&gt;&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let leaf = Rc::new(Node {
value: 3,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
});
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
let branch = Rc::new(Node {
value: 5,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(&amp;leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&amp;branch);
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
}</code></pre></pre>
<p><span class="caption">示例 15-28一个 <code>leaf</code> 节点,其拥有指向其父节点 <code>branch</code><code>Weak</code> 引用</span></p>
<p>创建 <code>leaf</code> 节点类似于示例 15-27除了 <code>parent</code> 字段有所不同:<code>leaf</code> 开始时没有父节点,所以我们新建了一个空的 <code>Weak</code> 引用实例。</p>
<p>此时,当尝试使用 <code>upgrade</code> 方法获取 <code>leaf</code> 的父节点引用时,会得到一个 <code>None</code> 值。如第一个 <code>println!</code> 输出所示:</p>
<pre><code class="language-text">leaf parent = None
</code></pre>
<p>当创建 <code>branch</code> 节点时,其也会新建一个 <code>Weak&lt;Node&gt;</code> 引用,因为 <code>branch</code> 并没有父节点。<code>leaf</code> 仍然作为 <code>branch</code> 的一个子节点。一旦在 <code>branch</code> 中有了 <code>Node</code> 实例,就可以修改 <code>leaf</code> 使其拥有指向父节点的 <code>Weak&lt;Node&gt;</code> 引用。这里使用了 <code>leaf</code><code>parent</code> 字段里的 <code>RefCell&lt;Weak&lt;Node&gt;&gt;</code><code>borrow_mut</code> 方法,接着使用了 <code>Rc::downgrade</code> 函数来从 <code>branch</code> 中的 <code>Rc&lt;Node&gt;</code> 值创建了一个指向 <code>branch</code><code>Weak&lt;Node&gt;</code> 引用。</p>
<p>当再次打印出 <code>leaf</code> 的父节点时,这一次将会得到存放了 <code>branch</code><code>Some</code> 值:现在 <code>leaf</code> 可以访问其父节点了!当打印出 <code>leaf</code> 时,我们也避免了如示例 15-26 中最终会导致栈溢出的循环:<code>Weak&lt;Node&gt;</code> 引用被打印为 <code>(Weak)</code></p>
<pre><code class="language-text">leaf parent = Some(Node { value: 5, parent: RefCell { value: (Weak) },
children: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) },
children: RefCell { value: [] } }] } })
</code></pre>
<p>没有无限的输出表明这段代码并没有造成引用循环。这一点也可以从观察 <code>Rc::strong_count</code><code>Rc::weak_count</code> 调用的结果看出。</p>
<h4 id="可视化-strong_count-和-weak_count-的改变"><a class="header" href="#可视化-strong_count-和-weak_count-的改变">可视化 <code>strong_count</code><code>weak_count</code> 的改变</a></h4>
<p>让我们通过创建了一个新的内部作用域并将 <code>branch</code> 的创建放入其中,来观察 <code>Rc&lt;Node&gt;</code> 实例的 <code>strong_count</code><code>weak_count</code> 值的变化。这会展示当 <code>branch</code> 创建和离开作用域被丢弃时会发生什么。这些修改如示例 15-29 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">use std::cell::RefCell;
</span><span class="boring">use std::rc::{Rc, Weak};
</span><span class="boring">
</span><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Node {
</span><span class="boring"> value: i32,
</span><span class="boring"> parent: RefCell&lt;Weak&lt;Node&gt;&gt;,
</span><span class="boring"> children: RefCell&lt;Vec&lt;Rc&lt;Node&gt;&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let leaf = Rc::new(Node {
value: 3,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
});
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(&amp;leaf),
Rc::weak_count(&amp;leaf),
);
{
let branch = Rc::new(Node {
value: 5,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(&amp;leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&amp;branch);
println!(
"branch strong = {}, weak = {}",
Rc::strong_count(&amp;branch),
Rc::weak_count(&amp;branch),
);
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(&amp;leaf),
Rc::weak_count(&amp;leaf),
);
}
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(&amp;leaf),
Rc::weak_count(&amp;leaf),
);
}</code></pre></pre>
<p><span class="caption">示例 15-29在内部作用域创建 <code>branch</code> 并检查其强弱引用计数</span></p>
<p>一旦创建了 <code>leaf</code>,其 <code>Rc&lt;Node&gt;</code> 的强引用计数为 1弱引用计数为 0。在内部作用域中创建了 <code>branch</code> 并与 <code>leaf</code> 相关联,此时 <code>branch</code><code>Rc&lt;Node&gt;</code> 的强引用计数为 1弱引用计数为 1因为 <code>leaf.parent</code> 通过 <code>Weak&lt;Node&gt;</code> 指向 <code>branch</code>)。这里 <code>leaf</code> 的强引用计数为 2因为现在 <code>branch</code><code>branch.children</code> 中储存了 <code>leaf</code><code>Rc&lt;Node&gt;</code> 的拷贝,不过弱引用计数仍然为 0。</p>
<p>当内部作用域结束时,<code>branch</code> 离开作用域,<code>Rc&lt;Node&gt;</code> 的强引用计数减少为 0所以其 <code>Node</code> 被丢弃。来自 <code>leaf.parent</code> 的弱引用计数 1 与 <code>Node</code> 是否被丢弃无关,所以并没有产生任何内存泄漏!</p>
<p>如果在内部作用域结束后尝试访问 <code>leaf</code> 的父节点,会再次得到 <code>None</code>。在程序的结尾,<code>leaf</code><code>Rc&lt;Node&gt;</code> 的强引用计数为 1弱引用计数为 0因为现在 <code>leaf</code> 又是 <code>Rc&lt;Node&gt;</code> 唯一的引用了。</p>
<p>所有这些管理计数和值的逻辑都内建于 <code>Rc&lt;T&gt;</code><code>Weak&lt;T&gt;</code> 以及它们的 <code>Drop</code> trait 实现中。通过在 <code>Node</code> 定义中指定从子节点到父节点的关系为一个<code>Weak&lt;T&gt;</code>引用,就能够拥有父节点和子节点之间的双向引用而不会造成引用循环和内存泄漏。</p>
<h2 id="总结-14"><a class="header" href="#总结-14">总结</a></h2>
<p>这一章涵盖了如何使用智能指针来做出不同于 Rust 常规引用默认所提供的保证与取舍。<code>Box&lt;T&gt;</code> 有一个已知的大小并指向分配在堆上的数据。<code>Rc&lt;T&gt;</code> 记录了堆上数据的引用数量以便可以拥有多个所有者。<code>RefCell&lt;T&gt;</code> 和其内部可变性提供了一个可以用于当需要不可变类型但是需要改变其内部值能力的类型,并在运行时而不是编译时检查借用规则。</p>
<p>我们还介绍了提供了很多智能指针功能的 trait <code>Deref</code><code>Drop</code>。同时探索了会造成内存泄漏的引用循环,以及如何使用 <code>Weak&lt;T&gt;</code> 来避免它们。</p>
<p>如果本章内容引起了你的兴趣并希望现在就实现你自己的智能指针的话,请阅读 <a href="https://doc.rust-lang.org/nomicon/index.html">“The Rustonomicon”</a> 来获取更多有用的信息。</p>
<p>接下来,让我们谈谈 Rust 的并发。届时甚至还会学习到一些新的对并发有帮助的智能指针。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="无畏并发"><a class="header" href="#无畏并发">无畏并发</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch16-00-concurrency.md">ch16-00-concurrency.md</a>
<br>
commit 1fedfc4b96c2017f64ecfcf41a0a07e2e815f24f</p>
</blockquote>
<p>安全且高效地处理并发编程是 Rust 的另一个主要目标。<strong>并发编程</strong><em>Concurrent programming</em>),代表程序的不同部分相互独立地执行,而 <strong>并行编程</strong><em>parallel programming</em>代表程序不同部分同时执行这两个概念随着计算机越来越多的利用多处理器的优势而显得愈发重要。由于历史原因在此类上下文中编程一直是困难且容易出错的Rust 希望能改变这一点。</p>
<p>起初Rust 团队认为确保内存安全和防止并发问题是两个分别需要不同方法应对的挑战。随着时间的推移,团队发现所有权和类型系统是一系列解决内存安全 <strong></strong> 并发问题的强有力的工具!通过利用所有权和类型检查,在 Rust 中很多并发错误都是 <strong>编译时</strong> 错误,而非运行时错误。因此,相比花费大量时间尝试重现运行时并发 bug 出现的特定情况Rust 会拒绝编译不正确的代码并提供解释问题的错误信息。因此,你可以在开发时修复代码,而不是在部署到生产环境后修复代码。我们给 Rust 的这一部分起了一个绰号 <strong>无畏并发</strong><em>fearless concurrency</em>)。无畏并发令你的代码免于出现诡异的 bug 并可以轻松重构且无需担心会引入新的 bug。</p>
<blockquote>
<p>注意:出于简洁的考虑,我们将很多问题归类为 <strong>并发</strong>,而不是更准确的区分 <strong>并发和(或)并行</strong>。如果这是一本专注于并发和/或并行的书,我们肯定会更加精确的。对于本章,当我们谈到 <strong>并发</strong> 时,请自行脑内替换为 <strong>并发和(或)并行</strong></p>
</blockquote>
<p>很多语言所提供的处理并发问题的解决方法都非常有特色。例如Erlang 有着优雅的消息传递并发功能但只有模糊不清的在线程间共享状态的方法。对于高级语言来说只实现可能解决方案的子集是一个合理的策略因为高级语言所许诺的价值来源于牺牲一些控制来换取抽象。然而对于底层语言则期望提供在任何给定的情况下有着最高的性能且对硬件有更少的抽象。因此Rust 提供了多种工具,以符合实际情况和需求的方式来为问题建模。</p>
<p>如下是本章将要涉及到的内容:</p>
<ul>
<li>如何创建线程来同时运行多段代码。</li>
<li><strong>消息传递</strong><em>Message passing</em>并发其中信道channel被用来在线程间传递消息。</li>
<li><strong>共享状态</strong><em>Shared state</em>)并发,其中多个线程可以访问同一片数据。</li>
<li><code>Sync</code><code>Send</code> trait将 Rust 的并发保证扩展到用户定义的以及标准库提供的类型中。</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用线程同时运行代码"><a class="header" href="#使用线程同时运行代码">使用线程同时运行代码</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch16-01-threads.md">ch16-01-threads.md</a>
<br>
commit 8aecae3efe5ca8f79f055b70f05d9a3f990bce7b</p>
</blockquote>
<p>在大部分现代操作系统中,已执行程序的代码在一个 <strong>进程</strong><em>process</em>)中运行,操作系统则会负责管理多个进程。在程序内部,也可以拥有多个同时运行的独立部分。这些运行这些独立部分的功能被称为 <strong>线程</strong><em>threads</em>。例如web 服务器可以有多个线程以便可以同时响应多个请求。</p>
<p>将程序中的计算拆分进多个线程可以改善性能,因为程序可以同时进行多个任务,不过这也会增加复杂性。因为线程是同时运行的,所以无法预先保证不同线程中的代码的执行顺序。这会导致诸如此类的问题:</p>
<ul>
<li>竞态条件Race conditions多个线程以不一致的顺序访问数据或资源</li>
<li>死锁Deadlocks两个线程相互等待对方这会阻止两者继续运行</li>
<li>只会发生在特定情况且难以稳定重现和修复的 bug</li>
</ul>
<p>Rust 尝试减轻使用线程的负面影响。不过在多线程上下文中编程仍需格外小心,同时其所要求的代码结构也不同于运行于单线程的程序。</p>
<p>编程语言有一些不同的方法来实现线程,而且很多操作系统提供了创建新线程的 API。Rust 标准库使用 <em>1:1</em> 线程实现,这代表程序的每一个语言级线程使用一个系统线程。有一些 crate 实现了其他有着不同于 1:1 模型取舍的线程模型。</p>
<h3 id="使用-spawn-创建新线程"><a class="header" href="#使用-spawn-创建新线程">使用 <code>spawn</code> 创建新线程</a></h3>
<p>为了创建一个新线程,需要调用 <code>thread::spawn</code> 函数并传递一个闭包(第十三章学习了闭包),并在其中包含希望在新线程运行的代码。示例 16-1 中的例子在主线程打印了一些文本而另一些文本则由新线程打印:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
for i in 1..10 {
println!("hi number {i} from the spawned thread!");
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {i} from the main thread!");
thread::sleep(Duration::from_millis(1));
}
}</code></pre></pre>
<p><span class="caption">示例 16-1: 创建一个打印某些内容的新线程,但是主线程打印其它内容</span></p>
<p>注意当 Rust 程序的主线程结束时,新线程也会结束,而不管其是否执行完毕。这个程序的输出可能每次都略有不同,不过它大体上看起来像这样:</p>
<pre><code class="language-text">hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
</code></pre>
<p><code>thread::sleep</code> 调用强制线程停止执行一小段时间,这会允许其他不同的线程运行。这些线程可能会轮流运行,不过并不保证如此:这依赖操作系统如何调度线程。在这里,主线程首先打印,即便新创建线程的打印语句位于程序的开头,甚至即便我们告诉新建的线程打印直到 <code>i</code> 等于 9它在主线程结束之前也只打印到了 5。</p>
<p>如果运行代码只看到了主线程的输出,或没有出现重叠打印的现象,尝试增大区间 (变量 <code>i</code> 的范围) 来增加操作系统切换线程的机会。</p>
<h4 id="使用-join-等待所有线程结束"><a class="header" href="#使用-join-等待所有线程结束">使用 <code>join</code> 等待所有线程结束</a></h4>
<p>由于主线程结束,示例 16-1 中的代码大部分时候不光会提早结束新建线程,因为无法保证线程运行的顺序,我们甚至不能实际保证新建线程会被执行!</p>
<p>可以通过将 <code>thread::spawn</code> 的返回值储存在变量中来修复新建线程部分没有执行或者完全没有执行的问题。<code>thread::spawn</code> 的返回值类型是 <code>JoinHandle</code><code>JoinHandle</code> 是一个拥有所有权的值,当对其调用 <code>join</code> 方法时,它会等待其线程结束。示例 16-2 展示了如何使用示例 16-1 中创建的线程的 <code>JoinHandle</code> 并调用 <code>join</code> 来确保新建线程在 <code>main</code> 退出前结束运行:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {i} from the spawned thread!");
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {i} from the main thread!");
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap();
}</code></pre></pre>
<p><span class="caption">示例 16-2: 从 <code>thread::spawn</code> 保存一个 <code>JoinHandle</code> 以确保该线程能够运行至结束</span></p>
<p>通过调用 handle 的 <code>join</code> 会阻塞当前线程直到 handle 所代表的线程结束。<strong>阻塞</strong><em>Blocking</em>)线程意味着阻止该线程执行工作或退出。因为我们将 <code>join</code> 调用放在了主线程的 <code>for</code> 循环之后,运行示例 16-2 应该会产生类似这样的输出:</p>
<pre><code class="language-text">hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 1 from the spawned thread!
hi number 3 from the main thread!
hi number 2 from the spawned thread!
hi number 4 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
</code></pre>
<p>这两个线程仍然会交替执行,不过主线程会由于 <code>handle.join()</code> 调用会等待直到新建线程执行完毕。</p>
<p>不过让我们看看将 <code>handle.join()</code> 移动到 <code>main</code><code>for</code> 循环之前会发生什么,如下:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {i} from the spawned thread!");
thread::sleep(Duration::from_millis(1));
}
});
handle.join().unwrap();
for i in 1..5 {
println!("hi number {i} from the main thread!");
thread::sleep(Duration::from_millis(1));
}
}</code></pre></pre>
<p>主线程会等待直到新建线程执行完毕之后才开始执行 <code>for</code> 循环,所以输出将不会交替出现,如下所示:</p>
<pre><code class="language-text">hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 3 from the main thread!
hi number 4 from the main thread!
</code></pre>
<p>诸如将 <code>join</code> 放置于何处这样的小细节,会影响线程是否同时运行。</p>
<h3 id="将-move-闭包与线程一同使用"><a class="header" href="#将-move-闭包与线程一同使用"><code>move</code> 闭包与线程一同使用</a></h3>
<p><code>move</code> 关键字经常用于传递给 <code>thread::spawn</code> 的闭包,因为闭包会获取从环境中取得的值的所有权,因此会将这些值的所有权从一个线程传送到另一个线程。在第十三章 <a href="ch13-01-closures.html#%E9%97%AD%E5%8C%85%E4%BC%9A%E6%8D%95%E8%8E%B7%E5%85%B6%E7%8E%AF%E5%A2%83">“闭包会捕获其环境”</a> 部分讨论了闭包上下文中的 <code>move</code>。现在我们会更专注于 <code>move</code><code>thread::spawn</code> 之间的交互。</p>
<p>在第十三章中,我们讲到可以在参数列表前使用 <code>move</code> 关键字强制闭包获取其使用的环境值的所有权。这个技巧在创建新线程将值的所有权从一个线程移动到另一个线程时最为实用。</p>
<p>注意示例 16-1 中传递给 <code>thread::spawn</code> 的闭包并没有任何参数:并没有在新建线程代码中使用任何主线程的数据。为了在新建线程中使用来自于主线程的数据,需要新建线程的闭包获取它需要的值。示例 16-3 展示了一个尝试在主线程中创建一个 vector 并用于新建线程的例子,不过这么写还不能工作,如下所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("Here's a vector: {v:?}");
});
handle.join().unwrap();
}</code></pre>
<p><span class="caption">示例 16-3: 尝试在另一个线程使用主线程创建的 vector</span></p>
<p>闭包使用了 <code>v</code>,所以闭包会捕获 <code>v</code> 并使其成为闭包环境的一部分。因为 <code>thread::spawn</code> 在一个新线程中运行这个闭包,所以可以在新线程中访问 <code>v</code>。然而当编译这个例子时,会得到如下错误:</p>
<pre><code class="language-console">$ cargo run
Compiling threads v0.1.0 (file:///projects/threads)
error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
--&gt; src/main.rs:6:32
|
6 | let handle = thread::spawn(|| {
| ^^ may outlive borrowed value `v`
7 | println!("Here's a vector: {v:?}");
| - `v` is borrowed here
|
note: function requires argument type to outlive `'static`
--&gt; src/main.rs:6:18
|
6 | let handle = thread::spawn(|| {
| __________________^
7 | | println!("Here's a vector: {v:?}");
8 | | });
| |______^
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
|
6 | let handle = thread::spawn(move || {
| ++++
For more information about this error, try `rustc --explain E0373`.
error: could not compile `threads` (bin "threads") due to 1 previous error
</code></pre>
<p>Rust 会 <strong>推断</strong> 如何捕获 <code>v</code>,因为 <code>println!</code> 只需要 <code>v</code> 的引用,闭包尝试借用 <code>v</code>。然而这有一个问题Rust 不知道这个新建线程会执行多久,所以无法知晓对 <code>v</code> 的引用是否一直有效。</p>
<p>示例 16-4 展示了一个 <code>v</code> 的引用很有可能不再有效的场景:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("Here's a vector: {v:?}");
});
drop(v); // oh no!
handle.join().unwrap();
}</code></pre>
<p><span class="caption">示例 16-4: 一个具有闭包的线程,尝试使用一个在主线程中被回收的引用 <code>v</code></span></p>
<p>如果 Rust 允许这段代码运行,则新建线程则可能会立刻被转移到后台并完全没有机会运行。新建线程内部有一个 <code>v</code> 的引用,不过主线程立刻就使用第十五章讨论的 <code>drop</code> 丢弃了 <code>v</code>。接着当新建线程开始执行,<code>v</code> 已不再有效,所以其引用也是无效的。噢,这太糟了!</p>
<p>为了修复示例 16-3 的编译错误,我们可以听取错误信息的建议:</p>
<pre><code class="language-text">help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
|
6 | let handle = thread::spawn(move || {
| ++++
</code></pre>
<p>通过在闭包之前增加 <code>move</code> 关键字,我们强制闭包获取其使用的值的所有权,而不是任由 Rust 推断它应该借用值。示例 16-5 中展示的对示例 16-3 代码的修改,可以按照我们的预期编译并运行:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("Here's a vector: {v:?}");
});
handle.join().unwrap();
}</code></pre></pre>
<p><span class="caption">示例 16-5: 使用 <code>move</code> 关键字强制获取它使用的值的所有权</span></p>
<p>我们可能希望尝试同样的方法来修复示例 16-4 中的代码,其主线程使用 <code>move</code> 闭包调用了 <code>drop</code>。然而这个修复行不通,因为示例 16-4 所尝试的操作由于一个不同的原因而不被允许。如果为闭包增加 <code>move</code>,将会把 <code>v</code> 移动进闭包的环境中,如此将不能在主线程中对其调用 <code>drop</code> 了。我们会得到如下不同的编译错误:</p>
<pre><code class="language-console">$ cargo run
Compiling threads v0.1.0 (file:///projects/threads)
error[E0382]: use of moved value: `v`
--&gt; src/main.rs:10:10
|
4 | let v = vec![1, 2, 3];
| - move occurs because `v` has type `Vec&lt;i32&gt;`, which does not implement the `Copy` trait
5 |
6 | let handle = thread::spawn(move || {
| ------- value moved into closure here
7 | println!("Here's a vector: {v:?}");
| - variable moved due to use in closure
...
10 | drop(v); // oh no!
| ^ value used here after move
For more information about this error, try `rustc --explain E0382`.
error: could not compile `threads` (bin "threads") due to 1 previous error
</code></pre>
<p>Rust 的所有权规则又一次帮助了我们!示例 16-3 中的错误是因为 Rust 是保守的并只会为线程借用 <code>v</code>,这意味着主线程理论上可能使新建线程的引用无效。通过告诉 Rust 将 <code>v</code> 的所有权移动到新建线程,我们向 Rust 保证主线程不会再使用 <code>v</code>。如果对示例 16-4 也做出如此修改,那么当在主线程中使用 <code>v</code> 时就会违反所有权规则。 <code>move</code> 关键字覆盖了 Rust 默认保守的借用,但它不允许我们违反所有权规则。</p>
<p>现在我们对线程和线程 API 有了基本的了解,让我们讨论一下使用线程实际可以 <strong></strong> 什么吧。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用消息传递在线程间传送数据"><a class="header" href="#使用消息传递在线程间传送数据">使用消息传递在线程间传送数据</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch16-02-message-passing.md">ch16-02-message-passing.md</a>
<br>
commit 36383b4da21dbd0a0781473bc8ad7ef0ed1b6751</p>
</blockquote>
<p>一个日益流行的确保安全并发的方式是 <strong>消息传递</strong><em>message passing</em>),这里线程或 actor 通过发送包含数据的消息来相互沟通。这个思想来源于 <a href="https://golang.org/doc/effective_go.html#concurrency">Go 编程语言文档中</a> 的口号“不要通过共享内存来通讯而是通过通讯来共享内存。”“Do not communicate by sharing memory; instead, share memory by communicating.”)</p>
<p>为了实现消息传递并发Rust 标准库提供了一个 <strong>信道</strong><em>channel</em>)实现。信道是一个通用编程概念,表示数据从一个线程发送到另一个线程。</p>
<p>你可以将编程中的信道想象为一个水流的渠道,比如河流或小溪。如果你将诸如橡皮鸭或小船之类的东西放入其中,它们会顺流而下到达下游。</p>
<p>编程中的信息渠道信道有两部分组成一个发送者transmitter和一个接收者receiver。发送者位于上游位置在这里可以将橡皮鸭放入河中接收者则位于下游橡皮鸭最终会漂流至此。代码中的一部分调用发送者的方法以及希望发送的数据另一部分则检查接收端收到的消息。当发送者或接收者任一被丢弃时可以认为信道被 <strong>关闭</strong><em>closed</em>)了。</p>
<p>这里,我们将开发一个程序,它会在一个线程生成值向信道发送,而在另一个线程会接收值并打印出来。这里会通过信道在线程间发送简单值来演示这个功能。一旦你熟悉了这项技术,你就可以将信道用于任何相互通信的任何线程,例如一个聊天系统,或利用很多线程进行分布式计算并将部分计算结果发送给一个线程进行聚合。</p>
<p>首先,在示例 16-6 中,创建了一个信道但没有做任何事。注意这还不能编译,因为 Rust 不知道我们想要在信道中发送什么类型:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
}</code></pre>
<p><span class="caption">示例 16-6: 创建一个信道,并将其两端赋值给 <code>tx</code><code>rx</code></span></p>
<p>这里使用 <code>mpsc::channel</code> 函数创建一个新的信道;<code>mpsc</code><strong>多个生产者,单个消费者</strong><em>multiple producer, single consumer</em>的缩写。简而言之Rust 标准库实现信道的方式意味着一个信道可以有多个产生值的 <strong>发送</strong><em>sending</em>)端,但只能有一个消费这些值的 <strong>接收</strong><em>receiving</em>)端。想象一下多条小河小溪最终汇聚成大河:所有通过这些小河发出的东西最后都会来到下游的大河。目前我们以单个生产者开始,但是当示例可以工作后会增加多个生产者。</p>
<p><code>mpsc::channel</code> 函数返回一个元组:第一个元素是发送端 -- 发送者,而第二个元素是接收端 -- 接收者。由于历史原因,<code>tx</code><code>rx</code> 通常作为 <strong>发送者</strong><em>transmitter</em>)和 <strong>接收者</strong><em>receiver</em>)的缩写,所以这就是我们将用来绑定这两端变量的名字。这里使用了一个 <code>let</code> 语句和模式来解构了此元组;第十九章会讨论 <code>let</code> 语句中的模式和解构。现在只需知道使用 <code>let</code> 语句是一个方便提取 <code>mpsc::channel</code> 返回的元组中一部分的手段。</p>
<p>让我们将发送端移动到一个新建线程中并发送一个字符串,这样新建线程就可以和主线程通讯了,如示例 16-7 所示。这类似于在河的上游扔下一只橡皮鸭或从一个线程向另一个线程发送聊天信息:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
}</code></pre></pre>
<p><span class="caption">示例 16-7: 将 <code>tx</code> 移动到一个新建的线程中并发送 “hi”</span></p>
<p>这里再次使用 <code>thread::spawn</code> 来创建一个新线程并使用 <code>move</code><code>tx</code> 移动到闭包中这样新建线程就拥有 <code>tx</code> 了。新建线程需要拥有信道的发送端以便能向信道发送消息。信道的发送端有一个 <code>send</code> 方法用来获取需要放入信道的值。<code>send</code> 方法返回一个 <code>Result&lt;T, E&gt;</code> 类型,所以如果接收端已经被丢弃了,将没有发送值的目标,所以发送操作会返回错误。在这个例子中,出错的时候调用 <code>unwrap</code> 产生 panic。不过对于一个真实程序需要合理地处理它回到第九章复习正确处理错误的策略。</p>
<p>在示例 16-8 中,我们在主线程中从信道的接收者获取值。这类似于在河的下游捞起橡皮鸭或接收聊天信息:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {received}");
}</code></pre></pre>
<p><span class="caption">示例 16-8: 在主线程中接收并打印内容 “hi”</span></p>
<p>信道的接收者有两个有用的方法:<code>recv</code><code>try_recv</code>。这里,我们使用了 <code>recv</code>,它是 <em>receive</em> 的缩写。这个方法会阻塞主线程执行直到从信道中接收一个值。一旦发送了一个值,<code>recv</code> 会在一个 <code>Result&lt;T, E&gt;</code> 中返回它。当信道发送端关闭,<code>recv</code> 会返回一个错误表明不会再有新的值到来了。</p>
<p><code>try_recv</code> 不会阻塞,相反它立刻返回一个 <code>Result&lt;T, E&gt;</code><code>Ok</code> 值包含可用的信息,而 <code>Err</code> 值代表此时没有任何消息。如果线程在等待消息过程中还有其他工作时使用 <code>try_recv</code> 很有用:可以编写一个循环来频繁调用 <code>try_recv</code>,在有可用消息时进行处理,其余时候则处理一会其他工作直到再次检查。</p>
<p>出于简单的考虑,这个例子使用了 <code>recv</code>;主线程中除了等待消息之外没有任何其他工作,所以阻塞主线程是合适的。</p>
<p>如果运行示例 16-8 中的代码,我们将会看到主线程打印出这个值:</p>
<pre><code class="language-text">Got: hi
</code></pre>
<p>完美!</p>
<h3 id="信道与所有权转移"><a class="header" href="#信道与所有权转移">信道与所有权转移</a></h3>
<p>所有权规则在消息传递中扮演了重要角色,其有助于我们编写安全的并发代码。防止并发编程中的错误是在 Rust 程序中考虑所有权的一大优势。现在让我们做一个试验来看看信道与所有权如何一同协作以避免产生问题:我们将尝试在新建线程中的信道中发送完 <code>val</code><strong>之后</strong> 再使用它。尝试编译示例 16-9 中的代码并看看为何这是不允许的:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
println!("val is {val}");
});
let received = rx.recv().unwrap();
println!("Got: {received}");
}</code></pre>
<p><span class="caption">示例 16-9: 在我们已经发送到信道中后,尝试使用 <code>val</code> 引用</span></p>
<p>这里尝试在通过 <code>tx.send</code> 发送 <code>val</code> 到信道中之后将其打印出来。允许这么做是一个坏主意:一旦将值发送到另一个线程后,那个线程可能会在我们再次使用它之前就将其修改或者丢弃。其他线程对值可能的修改会由于不一致或不存在的数据而导致错误或意外的结果。然而,尝试编译示例 16-9 的代码时Rust 会给出一个错误:</p>
<pre><code class="language-console">$ cargo run
Compiling message-passing v0.1.0 (file:///projects/message-passing)
error[E0382]: borrow of moved value: `val`
--&gt; src/main.rs:10:26
|
8 | let val = String::from("hi");
| --- move occurs because `val` has type `String`, which does not implement the `Copy` trait
9 | tx.send(val).unwrap();
| --- value moved here
10 | println!("val is {val}");
| ^^^^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0382`.
error: could not compile `message-passing` (bin "message-passing") due to 1 previous error
</code></pre>
<p>我们的并发错误会造成一个编译时错误。<code>send</code> 函数获取其参数的所有权并移动这个值归接收者所有。这可以防止在发送后再次意外地使用这个值;所有权系统检查一切是否合乎规则。</p>
<h3 id="发送多个值并观察接收者的等待"><a class="header" href="#发送多个值并观察接收者的等待">发送多个值并观察接收者的等待</a></h3>
<p>示例 16-8 中的代码可以编译和运行,不过它并没有明确的告诉我们两个独立的线程通过信道相互通讯。示例 16-10 则有一些改进会证明示例 16-8 中的代码是并发执行的:新建线程现在会发送多个消息并在每个消息之间暂停一秒钟。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust noplayground">use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {received}");
}
}</code></pre>
<p><span class="caption">示例 16-10: 发送多个消息,并在每次发送后暂停一段时间</span></p>
<p>这一次,在新建线程中有一个字符串 vector 希望发送到主线程。我们遍历它们,单独的发送每一个字符串并通过一个 <code>Duration</code> 值调用 <code>thread::sleep</code> 函数来暂停一秒。</p>
<p>在主线程中,不再显式调用 <code>recv</code> 函数:而是将 <code>rx</code> 当作一个迭代器。对于每一个接收到的值,我们将其打印出来。当信道被关闭时,迭代器也将结束。</p>
<p>当运行示例 16-10 中的代码时,将看到如下输出,每一行都会暂停一秒:</p>
<pre><code class="language-text">Got: hi
Got: from
Got: the
Got: thread
</code></pre>
<p>因为主线程中的 <code>for</code> 循环里并没有任何暂停或等待的代码,所以可以说主线程是在等待从新建线程中接收值。</p>
<h3 id="通过克隆发送者来创建多个生产者"><a class="header" href="#通过克隆发送者来创建多个生产者">通过克隆发送者来创建多个生产者</a></h3>
<p>之前我们提到了<code>mpsc</code><em>multiple producer, single consumer</em> 的缩写。可以运用 <code>mpsc</code> 来扩展示例 16-10 中的代码来创建向同一接收者发送值的多个线程。这可以通过克隆发送者来做到,如示例 16-11 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">use std::sync::mpsc;
</span><span class="boring">use std::thread;
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span> // --snip--
let (tx, rx) = mpsc::channel();
let tx1 = tx.clone();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx1.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
thread::spawn(move || {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {received}");
}
// --snip--
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 16-11: 从多个生产者发送多个消息</span></p>
<p>这一次,在创建新线程之前,我们对发送者调用了 <code>clone</code> 方法。这会给我们一个可以传递给第一个新建线程的发送端句柄。我们会将原始的信道发送端传递给第二个新建线程。这样就会有两个线程,每个线程将向信道的接收端发送不同的消息。</p>
<p>如果运行这些代码,你 <strong>可能</strong> 会看到这样的输出:</p>
<pre><code class="language-text">Got: hi
Got: more
Got: from
Got: messages
Got: for
Got: the
Got: thread
Got: you
</code></pre>
<p>虽然你可能会看到这些值以不同的顺序出现;这依赖于你的系统。这也就是并发既有趣又困难的原因。如果通过 <code>thread::sleep</code> 做实验,在不同的线程中提供不同的值,就会发现它们的运行更加不确定,且每次都会产生不同的输出。</p>
<p>现在我们见识过了信道如何工作,再看看另一种不同的并发方式吧。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="共享状态的并发"><a class="header" href="#共享状态的并发">共享状态的并发</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch16-03-shared-state.md">ch16-03-shared-state.md</a>
<br>
commit 856d89c53a6d69470bb5669c773fdfe6aab6fcc9</p>
</blockquote>
<p>消息传递是一个很好的处理并发的方式,但并不是唯一一个。另一种方式是让多个线程访问同一块内存中的数据(共享状态)。再考虑一下 Go 语言文档中的这句口号“不要通过共享内存来通讯”“do not communicate by sharing memory.”</p>
<p>通过共享内存进行通信,会是什么样的代码?此外,为什么喜欢消息传递的人会警告:谨慎使用内存共享?</p>
<p>在某种程度上,任何编程语言中的信道都类似于单所有权,因为一旦将一个值传送到信道中,将无法再使用这个值。共享内存类似于多所有权:多个线程可以同时访问相同的内存位置。在 15 章中我们介绍了智能指针可以实现多所有权然而这会增加额外的复杂性因为需要管理多个所有者。Rust 的类型系统和所有权规则在正确管理这些问题上提供了极大的帮助:举个例子,让我们来看看 <strong>互斥器</strong>,一个较常见的共享内存并发原语。</p>
<h3 id="使用互斥器实现同一时刻只允许一个线程访问数据"><a class="header" href="#使用互斥器实现同一时刻只允许一个线程访问数据">使用互斥器,实现同一时刻只允许一个线程访问数据</a></h3>
<p><strong>互斥器</strong><em>mutex</em>)是 互相排斥(<em>mutual exclusion</em>)的缩写。在同一时刻,其只允许一个线程对数据拥有访问权。为了访问互斥器中的数据,线程首先需要通过获取互斥器的 <strong></strong><em>lock</em>)来表明其希望访问数据。锁是一个数据结构,作为互斥器的一部分,它记录谁有数据的专属访问权。因此我们讲,互斥器通过锁系统 <strong>保护</strong><em>guarding</em>)其数据。</p>
<p>互斥器以难以使用著称(译注:原文指互斥器在其他编程语言中难以使用),因为你必须记住:</p>
<ol>
<li>在使用数据之前,必须获取锁。</li>
<li>使用完被互斥器所保护的数据之后,必须解锁数据,这样其他线程才能够获取锁。</li>
</ol>
<p>作为一个现实中互斥器的例子,想象一下在某个会议的一次小组座谈会中,只有一个麦克风。如果一位成员要发言,他必须请求或表示希望使用麦克风。得到了麦克风后,他可以畅所欲言,讲完后再将麦克风交给下一位希望讲话的成员。如果一位成员结束发言后忘记将麦克风交还,其他人将无法发言。如果对共享麦克风的管理出现了问题,座谈会将无法正常进行!</p>
<p>正确的管理互斥器异常复杂,这也是许多人之所以热衷于信道的原因。然而,在 Rust 中,得益于类型系统和所有权,我们不会在锁和解锁上出错。</p>
<h3 id="mutext的-api"><a class="header" href="#mutext的-api"><code>Mutex&lt;T&gt;</code>的 API</a></h3>
<p>我们先从在单线程环境中使用互斥器开始,作为展示其用法的一个例子,如示例 16-12 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
println!("m = {m:?}");
}</code></pre></pre>
<p><span class="caption">示例 16-12: 出于简单的考虑,在一个单线程上下文中探索 <code>Mutex&lt;T&gt;</code> 的 API</span></p>
<p>像很多类型一样,我们使用关联函数 <code>new</code> 来创建一个 <code>Mutex&lt;T&gt;</code>。使用 <code>lock</code> 方法来获取锁,从而可以访问互斥器中的数据。这个调用会阻塞当前线程,直到我们拥有锁为止。</p>
<p>如果另一个线程拥有锁,并且那个线程 panic 了,则 <code>lock</code> 调用会失败。在这种情况下,没人能够再获取锁,所以我们调用 <code>unwrap</code>,使当前线程 panic。</p>
<p>一旦获取了锁,就可以将返回值(命名为 <code>num</code>)视为一个其内部数据(<code>i32</code>)的可变引用了。类型系统确保了我们在使用 <code>m</code> 中的值之前获取锁。<code>m</code> 的类型是 <code>Mutex&lt;i32&gt;</code> 而不是 <code>i32</code>,所以 <strong>必须</strong> 获取锁才能使用这个 <code>i32</code> 值。我们是不会忘记这么做的,因为如果没有获取锁,类型系统就不允许访问内部的 <code>i32</code> 值。</p>
<p>正如你所猜想的,<code>Mutex&lt;T&gt;</code> 是一个智能指针。更准确的说,<code>lock</code> 调用 <strong>返回</strong> 一个叫做 <code>MutexGuard</code> 的智能指针。这个智能指针实现了 <code>Deref</code> 来指向其内部数据;它也实现了 <code>Drop</code>,当 <code>MutexGuard</code> 离开作用域时,自动释放锁(发生在示例 16-12 内部作用域的结尾)。有了这个特性,就不会有忘记释放锁的潜在风险(忘记释放锁会使互斥器无法再被其它线程使用),因为锁的释放是自动发生的。</p>
<p>释放锁之后,我们可以打印出互斥器内部的 <code>i32</code> 值,并发现我们刚刚已经将其值改为 6。</p>
<h4 id="在线程间共享-mutext"><a class="header" href="#在线程间共享-mutext">在线程间共享 <code>Mutex&lt;T&gt;</code></a></h4>
<p>现在让我们尝试使用 <code>Mutex&lt;T&gt;</code> 在多个线程间共享同一个值。我们将启动 10 个线程,并在各个线程中对同一个计数器值加 1这样计数器将从 0 变为 10。示例 16-13 中的例子会出现编译错误,而我们将通过这些错误来学习如何使用 <code>Mutex&lt;T&gt;</code>,以及 Rust 又是如何帮助我们正确使用的。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Mutex::new(0);
let mut handles = vec![];
for _ in 0..10 {
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}</code></pre>
<p><span class="caption">示例 16-13: 程序启动了 10 个线程,每个线程都通过 <code>Mutex&lt;T&gt;</code> 来增加计数器的值</span></p>
<p>这里创建了一个 <code>counter</code> 变量来存放内含 <code>i32</code><code>Mutex&lt;T&gt;</code>,类似示例 16-12 那样。接下来我们遍历整数区间,创建了 10 个线程。我们使用了 <code>thread::spawn</code>,并为所有线程传入了相同的闭包:它们每一个都将调用 <code>lock</code> 方法来获取 <code>Mutex&lt;T&gt;</code> 上的锁,接着将互斥器中的值加一。当一个线程结束执行,<code>num</code> 会离开闭包作用域并释放锁,这样另一个线程就可以获取它了。</p>
<p>在主线程中,我们像示例 16-2 那样收集了所有的 <code>JoinHandle</code>,并调用它们的 <code>join</code> 方法来等待所有线程结束。然后,主线程会获取锁,并打印出程序的结果。</p>
<p>之前提示过,这个例子不能编译,让我们看看为什么!</p>
<pre><code class="language-console">$ cargo run
Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0382]: borrow of moved value: `counter`
--&gt; src/main.rs:21:29
|
5 | let counter = Mutex::new(0);
| ------- move occurs because `counter` has type `Mutex&lt;i32&gt;`, which does not implement the `Copy` trait
...
8 | for _ in 0..10 {
| -------------- inside of this loop
9 | let handle = thread::spawn(move || {
| ------- value moved into closure here, in previous iteration of loop
...
21 | println!("Result: {}", *counter.lock().unwrap());
| ^^^^^^^ value borrowed here after move
|
help: consider moving the expression out of the loop so it is only moved once
|
8 ~ let mut value = counter.lock();
9 ~ for _ in 0..10 {
10 | let handle = thread::spawn(move || {
11 ~ let mut num = value.unwrap();
|
For more information about this error, try `rustc --explain E0382`.
error: could not compile `shared-state` (bin "shared-state") due to 1 previous error
</code></pre>
<p>错误信息表明 <code>counter</code> 值在上一次循环中被移动了。所以 Rust 告诉我们,不能将 <code>counter</code> 锁的所有权移动到多个线程中。让我们通过一个第 15 章讨论过的多所有权手段,来修复这个编译错误。</p>
<h4 id="多线程和多所有权"><a class="header" href="#多线程和多所有权">多线程和多所有权</a></h4>
<p>在第 15 章中,我们用智能指针 <code>Rc&lt;T&gt;</code> 来创建引用计数,使得一个值有了多个所有者。让我们做同样的事,看看会发生什么。将示例 16-14 中的 <code>Mutex&lt;T&gt;</code> 封装进 <code>Rc&lt;T&gt;</code>并在将所有权移入线程之前克隆clone <code>Rc&lt;T&gt;</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Rc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Rc::clone(&amp;counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}</code></pre>
<p><span class="caption">示例 16-14: 尝试使用 <code>Rc&lt;T&gt;</code> 来允许多个线程拥有 <code>Mutex&lt;T&gt;</code></span></p>
<p>再一次编译并...出现了不同的错误!编译器真是教会了我们很多!</p>
<pre><code class="language-console">$ cargo run
Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0277]: `Rc&lt;Mutex&lt;i32&gt;&gt;` cannot be sent between threads safely
--&gt; src/main.rs:11:36
|
11 | let handle = thread::spawn(move || {
| ------------- ^------
| | |
| ______________________|_____________within this `{closure@src/main.rs:11:36: 11:43}`
| | |
| | required by a bound introduced by this call
12 | | let mut num = counter.lock().unwrap();
13 | |
14 | | *num += 1;
15 | | });
| |_________^ `Rc&lt;Mutex&lt;i32&gt;&gt;` cannot be sent between threads safely
|
= help: within `{closure@src/main.rs:11:36: 11:43}`, the trait `Send` is not implemented for `Rc&lt;Mutex&lt;i32&gt;&gt;`, which is required by `{closure@src/main.rs:11:36: 11:43}: Send`
note: required because it's used within this closure
--&gt; src/main.rs:11:36
|
11 | let handle = thread::spawn(move || {
| ^^^^^^^
note: required by a bound in `spawn`
--&gt; /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/std/src/thread/mod.rs:688:1
For more information about this error, try `rustc --explain E0277`.
error: could not compile `shared-state` (bin "shared-state") due to 1 previous error
</code></pre>
<p>哇哦,错误信息太长不看!划重点:第一行错误表明 <code>Rc&lt;Mutex&lt;i32&gt;&gt;</code> 不能在线程间安全传递(<code>`Rc&lt;Mutex&lt;i32&gt;&gt;` cannot be sent between threads safely</code>);编译器也指出了原因:<code>Rc&lt;Mutex&lt;i32&gt;&gt;</code> 没有实现 <code>Send</code> trait<code>the trait `Send` is not implemented for `Rc&lt;Mutex&lt;i32&gt;&gt;`</code>)。下一节我们会讲到 <code>Send</code>:这是一个确保所使用的类型可以用于并发环境的 trait。</p>
<p>不幸的是,<code>Rc&lt;T&gt;</code> 并不能安全的在线程间共享。当 <code>Rc&lt;T&gt;</code> 管理引用计数时,它必须在每一个 <code>clone</code> 调用时增加计数,并在每一个克隆体被丢弃时减少计数。<code>Rc&lt;T&gt;</code> 并没有使用任何并发原语,无法确保改变计数的操作不会被其他线程打断。这可能使计数出错,并导致诡异的 bug比如可能会造成内存泄漏或在使用结束之前就丢弃一个值。我们所需要的是一个与 <code>Rc&lt;T&gt;</code> 完全一致,又以线程安全的方式改变引用计数的类型。</p>
<h4 id="原子引用计数-arct"><a class="header" href="#原子引用计数-arct">原子引用计数 <code>Arc&lt;T&gt;</code></a></h4>
<p>所幸 <code>Arc&lt;T&gt;</code> 正是这么一个类似 <code>Rc&lt;T&gt;</code> 并可以安全的用于并发环境的类型。字母 “a” 代表 <strong>原子性</strong><em>atomic</em>),所以这是一个 <strong>原子引用计数</strong><em>atomically reference counted</em>)类型。<strong>原子类型</strong> (Atomics) 是另一类这里还未涉及到的并发原语:请查看标准库中 <a href="https://doc.rust-lang.org/std/sync/atomic/index.html"><code>std::sync::atomic</code></a> 的文档来获取更多细节。目前我们只需要知道:原子类型就像基本类型一样,可以安全的在线程间共享。</p>
<p>你可能会好奇,为什么不是所有的基本类型都是原子性的?为什么标准库中的类型没有全部默认使用 <code>Arc&lt;T&gt;</code> 实现?原因在于,线程安全会造成性能损失,我们希望只在必要时才为此买单。如果只是在单线程中对值进行操作,原子性提供的保证并无必要,而不加入原子性可以使代码运行得更快。</p>
<p>回到之前的例子:<code>Arc&lt;T&gt;</code><code>Rc&lt;T&gt;</code> 有着相同的 API所以我们只需修改程序中的 <code>use</code> 行、<code>new</code> 调用和 <code>clone</code> 调用。示例 16-15 中的代码最终可以编译和运行:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&amp;counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}</code></pre></pre>
<p><span class="caption">示例 16-15: 使用 <code>Arc&lt;T&gt;</code> 包装一个 <code>Mutex&lt;T&gt;</code> 能够实现在多线程之间共享所有权</span></p>
<p>这会打印出:</p>
<pre><code class="language-text">Result: 10
</code></pre>
<p>成功了!我们从 0 数到了 10这好像没啥大不了的不过一路上我们确实学习了很多关于 <code>Mutex&lt;T&gt;</code> 和线程安全的内容!这个例子中构建的结构可以用于比增加计数更为复杂的操作。使用这个策略,我们可将计算任务分成独立的部分,并分散到多个线程中,接着使用 <code>Mutex&lt;T&gt;</code> 使用各自的运算结果来更新最终的结果。</p>
<p>注意,对于简单的数值运算,<a href="https://doc.rust-lang.org/std/sync/atomic/index.html">标准库中 <code>std::sync::atomic</code> 模块</a> 提供了比 <code>Mutex&lt;T&gt;</code> 更简单的类型。针对基本类型,这些类型提供了安全、并发、原子的操作。在上面的例子中,为了专注于讲明白 <code>Mutex&lt;T&gt;</code> 的用法,我们才选择在基本类型上使用 <code>Mutex&lt;T&gt;</code>。(译注:对于上面例子中出现的 <code>i32</code> 加法操作,更好的做法是使用 <code>AtomicI32</code> 类型来完成。具体参考文档。)</p>
<h3 id="refcelltrct-与-mutextarct-的相似性"><a class="header" href="#refcelltrct-与-mutextarct-的相似性"><code>RefCell&lt;T&gt;</code>/<code>Rc&lt;T&gt;</code><code>Mutex&lt;T&gt;</code>/<code>Arc&lt;T&gt;</code> 的相似性</a></h3>
<p>你可能注意到了,尽管 <code>counter</code> 是不可变的,我们仍然可以获取其内部值的可变引用;这意味着 <code>Mutex&lt;T&gt;</code> 提供了内部可变性,就像 <code>Cell</code> 系列类型那样。使用 <code>RefCell&lt;T&gt;</code> 可以改变 <code>Rc&lt;T&gt;</code> 中内容(在 15 章中讲到过),同样地,使用 <code>Mutex&lt;T&gt;</code> 我们也可以改变 <code>Arc&lt;T&gt;</code> 中的内容。</p>
<p>另一个值得注意的细节是Rust 不能完全避免使用 <code>Mutex&lt;T&gt;</code> 所带来的逻辑错误。回忆一下,第 15 章中讲过,使用 <code>Rc&lt;T&gt;</code> 就有造成引用循环的风险:两个 <code>Rc&lt;T&gt;</code> 值相互引用,造成内存泄漏。同理,<code>Mutex&lt;T&gt;</code> 也有造成 <strong>死锁</strong><em>deadlock</em>)的风险:当某个操作需要锁住两个资源,而两个线程分别持有两个资源的其中一个锁时,它们会永远相互等待。如果你对这个话题感兴趣,尝试编写一个带有死锁的 Rust 程序,接着研究别的语言中使用互斥器的死锁规避策略,并尝试在 Rust 中实现它们。标准库中 <code>Mutex&lt;T&gt;</code><code>MutexGuard</code> 的 API 文档会提供有用的信息。</p>
<p>接下来,为了丰富本章的内容,让我们讨论一下 <code>Send</code><code>Sync</code> trait以及如何对自定义类型使用它们。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用-sync-和-send-trait-的可扩展并发"><a class="header" href="#使用-sync-和-send-trait-的可扩展并发">使用 <code>Sync</code><code>Send</code> trait 的可扩展并发</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch16-04-extensible-concurrency-sync-and-send.md">ch16-04-extensible-concurrency-sync-and-send.md</a>
<br>
commit 7c7740a5ddef1458d74f1daf85fd49e03aaa97cf</p>
</blockquote>
<p>Rust 的并发模型中一个有趣的方面是:语言本身对并发知之 <strong>甚少</strong>。我们之前讨论的几乎所有内容,都属于标准库,而不是语言本身的内容。由于不需要语言提供并发相关的基础设施,并发方案不受标准库或语言所限:我们可以编写自己的或使用别人编写的并发功能。</p>
<p>然而有两个并发概念是内嵌于语言中的:<code>std::marker</code> 中的 <code>Sync</code><code>Send</code> trait。</p>
<h3 id="通过-send-允许在线程间转移所有权"><a class="header" href="#通过-send-允许在线程间转移所有权">通过 <code>Send</code> 允许在线程间转移所有权</a></h3>
<p><code>Send</code> 标记 trait 表明实现了 <code>Send</code> 的类型值的所有权可以在线程间传送。几乎所有的 Rust 类型都是<code>Send</code> 的,不过有一些例外,包括 <code>Rc&lt;T&gt;</code>:这是不能 <code>Send</code> 的,因为如果克隆了 <code>Rc&lt;T&gt;</code> 的值并尝试将克隆的所有权转移到另一个线程,这两个线程都可能同时更新引用计数。为此,<code>Rc&lt;T&gt;</code> 被实现为用于单线程场景,这时不需要为拥有线程安全的引用计数而付出性能代价。</p>
<p>因此Rust 类型系统和 trait bound 确保永远也不会意外的将不安全的 <code>Rc&lt;T&gt;</code> 在线程间发送。当尝试在示例 16-14 中这么做的时候,会得到错误 <code>the trait Send is not implemented for Rc&lt;Mutex&lt;i32&gt;&gt;</code>。而使用标记为 <code>Send</code><code>Arc&lt;T&gt;</code> 时,就没有问题了。</p>
<p>任何完全由 <code>Send</code> 的类型组成的类型也会自动被标记为 <code>Send</code>。几乎所有基本类型都是 <code>Send</code>除了第二十章将会讨论的裸指针raw pointer</p>
<h3 id="sync-允许多线程访问"><a class="header" href="#sync-允许多线程访问"><code>Sync</code> 允许多线程访问</a></h3>
<p><code>Sync</code> 标记 trait 表明一个实现了 <code>Sync</code> 的类型可以安全的在多个线程中拥有其值的引用。换一种方式来说,对于任意类型 <code>T</code>,如果 <code>&amp;T</code><code>T</code> 的不可变引用)是 <code>Send</code> 的话 <code>T</code> 就是 <code>Sync</code> 的,这意味着其引用就可以安全的发送到另一个线程。类似于 <code>Send</code> 的情况,基本类型是 <code>Sync</code> 的,完全由 <code>Sync</code> 的类型组成的类型也是 <code>Sync</code> 的。</p>
<p>智能指针 <code>Rc&lt;T&gt;</code> 也不是 <code>Sync</code> 的,出于其不是 <code>Send</code> 相同的原因。<code>RefCell&lt;T&gt;</code>(第十五章讨论过)和 <code>Cell&lt;T&gt;</code> 系列类型不是 <code>Sync</code> 的。<code>RefCell&lt;T&gt;</code> 在运行时所进行的借用检查也不是线程安全的。<code>Mutex&lt;T&gt;</code><code>Sync</code> 的,正如 <a href="ch16-03-shared-state.html#%E5%9C%A8%E7%BA%BF%E7%A8%8B%E9%97%B4%E5%85%B1%E4%BA%AB-mutext">“在线程间共享 <code>Mutex&lt;T&gt;</code></a> 部分所讲的它可以被用来在多线程中共享访问。</p>
<h3 id="手动实现-send-和-sync-是不安全的"><a class="header" href="#手动实现-send-和-sync-是不安全的">手动实现 <code>Send</code><code>Sync</code> 是不安全的</a></h3>
<p>通常并不需要手动实现 <code>Send</code><code>Sync</code> trait因为由 <code>Send</code><code>Sync</code> 的类型组成的类型,自动就是 <code>Send</code><code>Sync</code> 的。因为它们是标记 trait甚至都不需要实现任何方法。它们只是用来加强并发相关的不可变性的。</p>
<p>手动实现这些标记 trait 涉及到编写不安全的 Rust 代码,第十九章将会讲述具体的方法;当前重要的是,在创建新的由不是 <code>Send</code><code>Sync</code> 的部分构成的并发类型时需要多加小心,以确保维持其安全保证。<a href="https://doc.rust-lang.org/nomicon/index.html">“The Rustonomicon”</a> 中有更多关于这些保证以及如何维持它们的信息。</p>
<h2 id="总结-15"><a class="header" href="#总结-15">总结</a></h2>
<p>这不会是本书最后一个出现并发的章节:第二十一章的项目会在更现实的场景中使用这些概念,而不像本章中讨论的这些小例子。</p>
<p>正如之前提到的,因为 Rust 本身很少有处理并发的部分内容,有很多的并发方案都由 crate 实现。它们比标准库要发展的更快;请在网上搜索当前最新的用于多线程场景的 crate。</p>
<p>Rust 提供了用于消息传递的信道,和像 <code>Mutex&lt;T&gt;</code><code>Arc&lt;T&gt;</code> 这样可以安全的用于并发上下文的智能指针。类型系统和借用检查器会确保这些场景中的代码,不会出现数据竞争和无效的引用。一旦代码可以编译了,我们就可以坚信这些代码可以正确的运行于多线程环境,而不会出现其他语言中经常出现的那些难以追踪的 bug。并发编程不再是什么可怕的概念无所畏惧地并发吧</p>
<p>接下来,让我们讨论一下当 Rust 程序变得更大时,有哪些符合语言习惯的问题建模方法和结构化解决方案,以及 Rust 的风格是如何与面向对象编程Object Oriented Programming中那些你所熟悉的概念相联系的。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="async-和-await"><a class="header" href="#async-和-await">Async 和 await</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch17-00-async-await.md">ch17-00-async-await.md</a>
<br>
commit 3111eda07a4a4692bf69e3aaad999d840ac9c138</p>
</blockquote>
<p>很多我们要求计算机处理的操作都需要一定的时间才能完成。例如,如果你使用视频编辑器来创建一个家庭聚会的视频,导出视频可能会花费几分钟到几小时不等。同样,从家庭成员那里下载共享的视频也可能需要很长时间。如果我们能在等待这些长时间运行的操作完成期间做点其他事情,那就太好了。</p>
<p>视频导出会尽可能使用所有的 CPU 和 GPU。如果你只有一个 CPU 核,同时操作系统在导出完成前也不会暂停,那么在其运行期间你无法使用计算机进行任何其他操作。这会是一个非常糟糕的体验。相反计算机的操作系统可以(也确实可以)隐式地中断导出过程,频率足够高,使你能够在导出进行的同时完成其他任务。</p>
<p>下载文件则有所不同。它不占用大量的 CPU 时间。相反 CPU 需要等待来自于网络的数据。虽然可以在部分数据就绪时就开始读取,但等待剩余数据可能还需要一段时间。即便数据全部就绪了,视频文件也可能非常大,因此加载所有数据也会花费一些时间。虽然这可能只需要一两秒,不过这对于一个现代处理器来说已经是非常长的时间了,因为它每秒可以执行数十亿次操作。因此,如果能让 CPU 在等待网络调用完成的同时去处理别的工作就再好不过了。所以同上操作系统会隐式地中断你的程序以便其它工作可以在网络操作进行的同时继续进行。</p>
<blockquote>
<p>注意:视频导出这类操作通常被称为 “CPU 密集型”“CPU-bound”或者 “计算密集型”“compute-bound”操作。其受限于计算机 <em>CPU</em><em>GPU</em> 处理数据的速度,以及它所能利用的计算能力。而下载视频这类操作通常被称为 “IO 密集型”“IO-bound”操作因为其受限于计算机的 <em>输入输出</em> 速度。下载的速度最多只能与通过网络传输数据的速度一致。</p>
</blockquote>
<p>在上述两个例子中,操作系统的隐式中断提供了一种形式的并发。不过这种并发仅限于整个程序的级别:操作系统中断一个程序并让其它程序得以执行。在很多场景中,由于我们能比操作系统在更细粒度上理解我们的程序,因此我们可以观察到很多操作系统无法察觉的并发机会。</p>
<p>例如,如果我们在构建一个管理文件下载的工具,我们应当以一种不会因开始一个下载任务而锁定 UI 的方式来编写程序,并且用户应该能够同时开始多个下载任务。不过很多操作系统与网络交互的 API 都是 <em>阻塞</em> 的(<em>blocking</em>)。也就是说这些 API 会阻塞程序的进程,直到它们处理的数据完全就绪。</p>
<blockquote>
<p>注意:如果你仔细思索一下,会发现这是 <em>大部分</em> 函数调用的工作方式!不过我们通常将 “阻塞” 这个术语保留给那些与文件、网络或其它计算机资源交互的函数调用,因为这些地方是单个程序可以从 <em></em> 阻塞操作中获益的地方。</p>
</blockquote>
<p>我们可以新建专用的线程来下载每个文件以免阻塞主线程。然而,我们最终会发现这些线程的开销会成为一个问题。如果这些调用在一开始就是非阻塞的话那就更理想了。最后,如果我们能够像在阻塞代码中一样,以直接的风格编写非阻塞代码,那就更好了。比如这样:</p>
<pre><code class="language-rust ignore does_not_compile">let data = fetch_data_from(url).await;
println!("{data}");</code></pre>
<p>这正是 Rust 的 async 抽象所提供的。不过在讲解它们在实践中如何工作之前让我们稍微绕个远路来了解一下并行parallelism和并发concurrency的区别。</p>
<h3 id="并行与并发"><a class="header" href="#并行与并发">并行与并发</a></h3>
<p>在上一章中,我们大致将并行和并发视为可以互换的概念。但现在我们需要更加精确地区分它们,因为它们的区别将在实际工作中显现出来。</p>
<p>思考一下不同的团队分割方法来开发一个软件项目。我们可以分配给一个个人多个任务,也可以每个团队成员各自负责一个任务,或者可以采用这两种方法的组合。</p>
<p>当一个个人在任何一个任务完成前同时处理多个任务,这就是 <em>并发</em>。你可能在计算机上同时运行两个项目,当你对其中一个项目感到厌倦或遇到困难时,可以切换到另一个项目。因为你是单独一个人,所以无法真正同时推进两个任务,但是你可以多任务处理,在不同任务之间切换以取得进展。</p>
<figure>
<img alt="并发工作流" src="img/trpl17-01.svg" class="center" />
<figcaption>图 17-1一个并发工作流在任务 A 和任务 B 之间切换</figcaption>
</figure>
<p>当你同意将一组任务在组员中分配,每一个组员分配一个任务并单独处理它,这就是 <em>并行</em>。每个组员可以真正同时进行工作。</p>
<figure>
<img alt="并发工作流" src="img/trpl17-02.svg" class="center" />
<figcaption>图 17-2一个并行流其中任务 A 和任务 B 的工作同时独立进行</figcaption>
</figure>
<p>在这两种场景中,你可能需要协调不同的任务。也许你 <em>认为</em> 某个人负责的任务与其他人的工作完全不相关,但实际上它确实依赖于团队中另一位成员的工作完成。一些工作可以并行进行,不过一些工作事实上是 <em>串行</em> 的:它们只能串行地发生,一个接着一个,如图 17-3 所示。</p>
<figure>
<img alt="并发工作流" src="img/trpl17-03.svg" class="center" />
<figcaption>图 17-3一个部分并行的工作流其中任务 A 和任务 B 的工作相互独立,直到任务 A3 阻塞在等待任务 B3 的结果</figcaption>
</figure>
<p>同理,你可能会意识到你自己的一个任务依赖另一个任务。现在并发任务也变成串行的了。</p>
<p>并行与并发也可能相互交叉(阻塞)。如果你得知某个同事卡在等待你的一个任务完成,你可能会集中所有精力在这个任务上来 “解锁” 你的同事。你和你的同事则不再能并行地工作了,同时你也不能够并发地处理自己的任务。</p>
<p>同样的基础动态也作用于软件与硬件。在一个单核的机器上CPU 一次只能执行一个操作不过它仍然可以并发工作。借助像线程、进程和异步async等工具计算机可以暂停一个活动并在最终切换回第一个活动之前切换到其它活动。在一个有多个 CPU 核心的机器上,它也可以并行工作。一个核心可以做一件工作的同时另一个核心可以做一些完全不相关的工作,而且这些工作实际上是同时发生的。</p>
<p>当使用 Rust 中的 async 时我们总是在处理并发。取决于硬件、操作系统和所使用的异步运行时async runtime-- 稍后会介绍更多的异步运行时!并发也可能在底层使用了并行。</p>
<p>现在让我们深入理解 Rust 的异步编程实际上是如何工作的!在接下来的章节中,我们将:</p>
<ul>
<li>学习如何使用 Rust 的 <code>async</code><code>await</code> 语法</li>
<li>探索如何使用异步模型来解决第十六章中遇到的一些挑战</li>
<li>了解多线程和异步如何互补,在很多场景中你甚至可以同时使用两者</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h2 id="futures-和-async-语法"><a class="header" href="#futures-和-async-语法">Futures 和 async 语法</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch17-01-futures-and-syntax.md">ch17-01-futures-and-syntax.md</a>
<br>
commit e95efa05706c5c4309df9ed47d5e91d8ed342b7d</p>
</blockquote>
<p>Rust 异步编程的关键元素是 <em>futures</em> 和 Rust 的 <code>async</code><code>await</code> 关键字。</p>
<p><em>future</em> 是一个现在可能还没有准备好但将在未来某个时刻准备好的值。(相同的概念也出现在很多语言中,有时被称为 “task” 或者 “promise”。Rust 提供了 <code>Future</code> trait 作为基础组件,这样不同的异步操作就可以在不同的数据结构上实现。在 Rust 中,我们称实现了 <code>Future</code> trait 的类型为 futures。每一个实现了 <code>Future</code> 的类型会维护自己的进度状态信息和 “ready” 的定义。</p>
<p><code>async</code> 关键字可以用于代码块和函数,表明它们可以被中断并恢复。在一个 async 块或 async 函数中,可以使用 <code>await</code> 关键字来等待一个 future 准备就绪,这一过程称为 <em>等待一个 future</em>。async 块或 async 函数中每一个等待 future 的地方都可能是一个 async 块或 async 函数中断并随后恢复的点。检查一个 future 并查看其值是否已经准备就绪的过程被称为 <em>轮询</em>polling</p>
<p>其它一些语言也使用 <code>async</code><code>await</code> 关键字进行异步编程。如果你熟悉这些语言,则可能会注意到它们与 Rust 的处理方式有显著不同,包括语法上的差异。我们将看到,这样做是有充分理由的!</p>
<p>在大多数情况下,编写异步 Rust 代码时,我们使用 <code>async</code><code>await</code> 关键字。Rust 将其编译为等同于使用 <code>Future</code> trait 的代码,这非常类似于将 <code>for</code> 循环编译为等同于使用 <code>Iterator</code> trait 的代码。不过,由于 Rust 提供了 <code>Future</code> trait你也可以在需要时为你自己的数据类型实现它。在整个章节中你会看到很多函数的返回值类型都有其自己的 <code>Future</code> 实现。我们会在本章结尾回到这个 trait 的定义,并深入了解它的工作原理,但现在这些细节已经足够让我们继续前进了。</p>
<p>这些内容可能有点抽象。让我们来编写第一个异步程序:一个小型网络爬虫。我们会从命令行传递两个 URL并发地解析它们并返回第一个完成解析的结果。这个示例会引入不少的新语法不过不用担心。我们会逐步解释所有你需要了解的内容。</p>
<h3 id="第一个异步程序"><a class="header" href="#第一个异步程序">第一个异步程序</a></h3>
<p>为了保持本章的内容专注于学习 async而不是处理生态系统的部分组件我们已经创建了一个 <code>trpl</code> crate<code>trpl</code> 是 “The Rust Programming Language” 的缩写。它重导出了你需要的所有类型、traits 和函数,它们主要来自于 <a href="https://crates.io/crates/futures"><code>futures</code></a><a href="https://tokio.rs"><code>tokio</code></a> crates。</p>
<ul>
<li><code>futures</code> crate 是一个 Rust 异步代码实验的官方仓库,也正是 <code>Future</code> 最初设计的地方。</li>
<li>Tokio 是目前 Rust 中应用最广泛的异步运行时async runtime特别是但不仅是web 应用。这里还有其他优秀的运行时,它们可能更适合你的需求。我们在 <code>trpl</code> 的底层使用 Tokio 是因为它经过了充分测试且广泛使用。</li>
</ul>
<p>在一些场景中,<code>trpl</code> 也会重命名或者封装原始 API 以便我们专注于与本章相关的细节。如果你想了解该 crate 的具体功能,我们鼓励你查看<a href="https://github.com/rust-lang/book/tree/main/packages/trpl">其源码</a>。你可以看到每个重导出的内容来自哪个 crate我们留下了大量注释来解释这个 crate 的用途。</p>
<p>创建一个名为 <code>hello-async</code> 的二进制项目并将 <code>trpl</code> crate 作为一个依赖添加:</p>
<pre><code class="language-console">$ cargo new hello-async
$ cd hello-async
$ cargo add trpl
</code></pre>
<p>现在我们可以利用 <code>trpl</code> 提供的多种组件来编写第一个异步程序。我们构建了一个小的命令行工具来抓取两个网页,拉取各自的 <code>&lt;title&gt;</code> 元素,并打印出第一个完成全部过程的标题。</p>
<p>让我们开始编写一个函数,它获取一个网页 URL 作为参数,请求该 URL 并返回标题元素的文本:</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> // TODO: we'll add this next!
</span><span class="boring">}
</span><span class="boring">
</span>use trpl::Html;
async fn page_title(url: &amp;str) -&gt; Option&lt;String&gt; {
let response = trpl::get(url).await;
let response_text = response.text().await;
Html::parse(&amp;response_text)
.select_first("title")
.map(|title_element| title_element.inner_html())
}</code></pre></pre>
<figcaption>示例 17-1定义一个 async 函数来获取一个 HTML 页面的标题元素</figcaption>
</figure>
<p>在示例 17-1 中,我们定义了一个名为 <code>page_title</code> 的函数,并使用了 <code>async</code> 关键字标记。接着我们使用 <code>trpl::get</code> 函数来获取传入的任意 URL然后使用 <code>await</code> 关键字来等待响应。接着我们调用其 <code>text</code> 方法来获取响应的文本,这里再一次使用 <code>await</code> 关键字等待。这两个步骤都是异步的。对于 <code>get</code> 来说,我们需要等待服务器发送回其响应的第一部分,这会包含 HTTP 头headers、cookies 等。这部分响应可以独立于响应体发送。特别是在响应体非常大时候,接收完整响应可能会花费一些时间。因此我们不得不等待响应 <em>整体</em> 返回,所以 <code>text</code> 方法也是异步。</p>
<p>我们必须显示地等待这两个 futures因为 Rust 中的 futures 是 <em>惰性</em><em>lazy</em>)的:在你使用 <code>await</code> 请求之前它们不会执行任何操作。(事实上,如果你不使用一个 futuresRust 会显示一个编译警告)这应该会让你想起<a href="ch13-02-iterators.html">之前第十三章</a>关于迭代器的讨论。直到你调用迭代器的 <code>next</code> 方法(直接调用或者使用 <code>for</code> 循环或者类似 <code>map</code> 这类在底层使用 <code>next</code> 的方法)之前它们什么也不会做。对于 futures 来说,同样的基本理念也是适用的:除非你显式地请求,否则它们不会执行。惰性使得 Rust 可以避免提前运行异步代码,直到真正需要时才执行。</p>
<blockquote>
<p>注意:这不同于上一章节中 <code>thread::spawn</code> 的行为,当时传递给另一个线程的闭包会立即开始运行。这也与许多其他语言处理异步的方式不同!但对于 Rust 而言,这一点非常重要。稍后我们会解释原因。</p>
</blockquote>
<p>当我们有了 <code>response_text</code> 函数,就可以使用 <code>Html::parse</code> 将其解析为一个 <code>Html</code> 类型的实例。不同于原始字符串,现在我们有了一个可以将 HTML 作为更丰富数据结构来操作的数据类型。特别是我们可以使用 <code>select_first</code> 方法来找出给定 CSS 选择器selector中第一个匹配元素。通过传递字符串 <code>"title"</code>,我们会得到文档中的第一个 <code>&lt;title&gt;</code> 元素,如果它存在的话。由于可能没有任何匹配的元素,<code>select_first</code> 返回一个 <code>Option&lt;ElementRef&gt;</code>。最后我们使用 <code>Option::map</code> 方法,它允许我们在 <code>Option</code> 中有元素时对其进行处理,而在没有时则什么也不做。(这里也可以使用一个 <code>match</code> 表达式,但 <code>map</code> 更符合惯用的写法。)在传递给 <code>map</code> 的函数体中,我们调用了 <code>title_element</code> 上的 <code>inner_html</code> 来获取其内容,这是一个 <code>String</code>。当上面所讲的都完成后,我们会得到一个 <code>Option&lt;String&gt;</code></p>
<p>注意 Rust 的 <code>await</code> 关键字出现在需要等待的表达式之后而不是之前。也就是说,这是一个 <em>后缀关键字</em><em>postfix keyword</em>)。如果你在其它语言中使用过 async 的话这可能与你所熟悉的有所不同。Rust 如此选择是因为这使得方法的链式调用更加简洁。因此,我们可以修改 <code>page_url_for</code> 的函数体来链式调用 <code>trpl::get</code><code>text</code> 并在其之间使用 <code>await</code>,如示例 17-2 所示:</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use trpl::Html;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> // TODO: we'll add this next!
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">async fn page_title(url: &amp;str) -&gt; Option&lt;String&gt; {
</span> let response_text = trpl::get(url).await.text().await;
<span class="boring"> Html::parse(&amp;response_text)
</span><span class="boring"> .select_first("title")
</span><span class="boring"> .map(|title_element| title_element.inner_html())
</span><span class="boring">}</span></code></pre></pre>
<figcaption>示例 17-2使用 `await` 关键字的链式调用</figcaption>
</figure>
<p>这样我们就成功编写了第一个异步函数!在我们向 <code>main</code> 加入一些代码调用它之前,让我们再多了解下我们写了什么以及它的意义。</p>
<p>当 Rust 遇到一个 <code>async</code> 关键字标记的代码块时,会将其编译为一个实现了 <code>Future</code> trait 的唯一的、匿名的数据类型。当 Rust 遇到一个被标记为 <code>async</code> 的函数时,会将其编译进一个拥有异步代码块的非异步函数。异步函数的返回值类型是编译器为异步代码块所创建的匿名数据类型。</p>
<p>因此,编写 <code>async fn</code> 就等同于编写一个返回类型的 <em>future</em> 的函数。当编译器遇到类似示例 17-1 中 <code>async fn page_title</code> 的函数定义时,它等价于以下定义的非异步函数:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate trpl; // required for mdbook test
</span>use std::future::Future;
use trpl::Html;
fn page_title(url: &amp;str) -&gt; impl Future&lt;Output = Option&lt;String&gt;&gt; + '_ {
async move {
let text = trpl::get(url).await.text().await;
Html::parse(&amp;text)
.select_first("title")
.map(|title| title.inner_html())
}
}
<span class="boring">}</span></code></pre></pre>
<p>让我们挨个看一下转换后版本的每一个部分:</p>
<ul>
<li>它使用了之前第十章 <a href="ch10-02-traits.html#trait-%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0">“trait 作为参数”</a> 部分讨论过的 <code>impl Trait</code> 语法</li>
<li>它返回的 trait 是一个 <code>Future</code>,它有一个关联类型 <code>Output</code>。注意 <code>Output</code> 的类型是 <code>Option&lt;String&gt;</code>,这与 <code>async fn</code> 版本的 <code>page_title</code> 的原始返回值类型相同。</li>
<li>所有原始函数中被调用的代码被封装进一个 <code>async move</code> 块。回忆一下,代码块是表达式。这整个块就是函数所返回的表达式</li>
<li>如上所述,这个异步代码块产生一个 <code>Option&lt;String&gt;</code> 类型的值。这个值与返回类型中的 <code>Output</code> 类型一致。这正类似于你已经见过的其它代码块。</li>
<li>新版函数的函数体是一个 <code>async move</code> 代码块,因为它如何使用 <code>url</code> 参数决定了这一点。(本章后续部分将更详细地讨论 <code>async</code><code>async move</code> 之间的区别。)</li>
<li>新版本的函数在返回类型中使用了一种我们之前未见过的生命周期标记:<code>'_</code>。因为函数返回的 <code>Future</code> 指向一个引用(在这个例子中是指向 <code>url</code> 参数的引用)我们需要告诉 Rust 引用的生命周期。这里无需命名该生命周期,因为 Rust 足够智能到能理解这里只涉及到唯一一个引用,不过我们 <em>必须</em> 明确指出返回的 <code>Future</code> 受该生命周期的约束。</li>
</ul>
<p>现在我们可以在 <code>main</code> 中调用 <code>page_title</code>。首先,我们只会获取一个页面的标题。在示例 17-3 中,我们沿用了第十二章中获取命令行参数的相同模式。接着我们传递第一个 URL 给 <code>page_title</code>,并等待结果。因为 future 产生的值是一个 <code>Option&lt;String&gt;</code>,我们使用 <code>match</code> 表达式来根据页面是否有 <code>&lt;title&gt;</code> 来打印不同的信息。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use trpl::Html;
</span><span class="boring">
</span>async fn main() {
let args: Vec&lt;String&gt; = std::env::args().collect();
let url = &amp;args[1];
match page_title(url).await {
Some(title) =&gt; println!("The title for {url} was {title}"),
None =&gt; println!("{url} had no title"),
}
}
<span class="boring">
</span><span class="boring">async fn page_title(url: &amp;str) -&gt; Option&lt;String&gt; {
</span><span class="boring"> let response_text = trpl::get(url).await.text().await;
</span><span class="boring"> Html::parse(&amp;response_text)
</span><span class="boring"> .select_first("title")
</span><span class="boring"> .map(|title_element| title_element.inner_html())
</span><span class="boring">}</span></code></pre>
<figcaption>示例 17-3在 `main` 中通过一个用户提供的参数调用 `page_title` 函数</figcaption>
</figure>
<p>很不幸的是这还不能编译。唯一可以使用 <code>await</code> 关键字的地方是异步函数或者代码块中,同时 Rust 不允许将特殊的 <code>main</code> 函数标记为 <code>async</code></p>
<!-- manual-regeneration
cd listings/ch17-async-await/listing-17-03
cargo build
copy just the compiler error
-->
<pre><code class="language-text">error[E0752]: `main` function is not allowed to be `async`
--&gt; src/main.rs:6:1
|
6 | async fn main() {
| ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`
</code></pre>
<p><code>main</code> 不能标记为 <code>async</code> 的原因是异步代码需要一个 <em>运行时</em>:即一个管理执行异步代码细节的 Rust crate。一个程序的 <code>main</code> 函数可以 <em>初始化</em> 一个运行时,但是其 <em>自身</em> 并不是一个运行时。(稍后我们会进一步解释原因。)每一个执行异步代码的 Rust 程序必须至少有一个设置运行时并执行 futures 的地方。</p>
<p>大部分支持异步的语言会打包一个运行时在语言中。Rust 则不是,相这里有很多不同的异步运行时,每一个都有适合其目标的权衡取舍。例如,一个拥有很多核心和大量内存的高吞吐 web server 与一个单核、少量内存并且没有堆分配能力的微控制器相比有着截然不同的需求。提供这些运行时的 crate 通常也提供了例如文件或者网络 IO 这类常用功能的异步版本。</p>
<p>从这里到本章余下部分,我们会使用 <code>trpl</code> crate 的 <code>run</code> 函数,它获取一个 future 作为参数并运行到结束。在内部,调用 <code>run</code> 会设置一个运行时来运行传递的 future。一旦 future 完成,<code>run</code> 返回 future 返回的任何值。</p>
<p>我们可以将 <code>page_title</code> 返回的 future 直接传递给 <code>run</code>。一旦其完成,我们能够匹配返回的 <code>Option&lt;String&gt;</code>,正如示例 17-3 我们尝试的那样。然而,在本章的大部分示例中(以及大多数实际应用中的异步代码中!),我们会执行不止一次异步函数调用,所以相反我们会传递一个 <code>async</code> 块并显式地等待 <code>page_title</code> 调用的结果,如示例 17-4 所示。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust should_panic noplayground"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use trpl::Html;
</span><span class="boring">
</span>fn main() {
let args: Vec&lt;String&gt; = std::env::args().collect();
trpl::run(async {
let url = &amp;args[1];
match page_title(url).await {
Some(title) =&gt; println!("The title for {url} was {title}"),
None =&gt; println!("{url} had no title"),
}
})
}
<span class="boring">
</span><span class="boring">async fn page_title(url: &amp;str) -&gt; Option&lt;String&gt; {
</span><span class="boring"> let response_text = trpl::get(url).await.text().await;
</span><span class="boring"> Html::parse(&amp;response_text)
</span><span class="boring"> .select_first("title")
</span><span class="boring"> .map(|title_element| title_element.inner_html())
</span><span class="boring">}</span></code></pre>
<figcaption>示例 17-4等待一个使用异步代码块的 `trpl::run`</figcaption>
</figure>
<p>当我们运行代码,我们会得到最初预想的行为:</p>
<pre><code class="language-console">$ cargo run "http://www.rust-lang.org"
The title for http://www.rust-lang.org was
Rust Programming Language
</code></pre>
<p>我们终于有了一些可以正常工作的异步代码!现在它们可以成功编译并运行。在我们添加代码让两个网址进行竞争之前,让我们简要地回顾一下 future 是如何工作的。</p>
<p>每一个 <em>await point</em>,也就是代码使用 <code>await</code> 关键字的地方,代表将控制权交还给运行时的地方。为此 Rust 需要记录异步代码块中涉及的状态,这样运行时可以去执行其他工作,并在准备好时回来继续推进当前的任务。这就像你通过编写一个枚举来保存每一个 <code>await</code> point 的状态一样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span>enum PageTitleFuture&lt;'a&gt; {
Initial { url: &amp;'a str },
GetAwaitPoint { url: &amp;'a str },
TextAwaitPoint { response: trpl::Response },
}
<span class="boring">}</span></code></pre></pre>
<p>编写代码来手动控制不同状态之间的转换是非常乏味且容易出错的特别是之后增加了更多功能和状态的时候。相反Rust 编译器自动创建并管理异步代码的状态机数据结构。如果你感兴趣的话:是的,正常的借用和所有权也全部适用于这些数据结构。幸运的是,编译器也会为我们处理这些检查,并提供友好的错误信息。本章稍后会讲解一些相关内容!</p>
<p>最终需要某个组件来执行状态机。这就是运行时。(这也是为什么在了解运行时的时候,你可能会看到 <em>executors</em> 这个词executor 是运行时中负责执行异步代码的部分。)</p>
<p>现在我们能够理解了之前示例 17-3 中为何编译器阻止我们将 <code>main</code> 本身标记为异步函数了。如果 <code>main</code> 是一个异步函数,需要有其它组件来管理 <code>main</code> futrue 返回的状态机,但是 <code>main</code> 是程序的入口点!为此我们在 <code>main</code> 函数中调用 <code>trpl::run</code>,它设置了一个运行时并运行 <code>async</code> 块返回的 future 并等待它返回 <code>Ready</code></p>
<blockquote>
<p>注意:一些运行时提供了相关的宏所以你 <em>可以</em> 编写一个异步 <code>main</code> 函数。这些宏将 <code>async fn main() { ... }</code> 重写为正常的 <code>fn main</code>,执行的逻辑与我们在示例 17-5 中手动实现的一样:像 <code>trpl::run</code> 一样调用一个函数运行 future 直到结束。</p>
</blockquote>
<p>让我们将这些代码片段整理一下来看看如何编写并发代码,这里通过两个来自命令行的不同 URL 来调用 <code>page_title</code> 并使其相互竞争。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<!-- should_panic,noplayground because mdbook does not pass args -->
<pre><code class="language-rust should_panic noplayground"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span>use trpl::{Either, Html};
fn main() {
let args: Vec&lt;String&gt; = std::env::args().collect();
trpl::run(async {
let title_fut_1 = page_title(&amp;args[1]);
let title_fut_2 = page_title(&amp;args[2]);
let (url, maybe_title) =
match trpl::race(title_fut_1, title_fut_2).await {
Either::Left(left) =&gt; left,
Either::Right(right) =&gt; right,
};
println!("{url} returned first");
match maybe_title {
Some(title) =&gt; println!("Its page title is: '{title}'"),
None =&gt; println!("Its title could not be parsed."),
}
})
}
async fn page_title(url: &amp;str) -&gt; (&amp;str, Option&lt;String&gt;) {
let text = trpl::get(url).await.text().await;
let title = Html::parse(&amp;text)
.select_first("title")
.map(|title| title.inner_html());
(url, title)
}</code></pre>
<figcaption>示例 17-5</figcaption>
</figure>
<p>示例 17-5 中以分别由用户提供的 URL 调用 <code>page_title</code> 开始。我们将调用 <code>page_title</code> 产生的 future 分别保存为 <code>title_fut_1</code><code>title_fut_2</code>。请记住,它们还没有进行任何工作,因为 future 是惰性的,并且我们还没有 <code>await</code> 它们。接着我们将 futures 传递给 <code>trpl::race</code>,它返回一个值表明哪个传递的 future 最先返回。</p>
<blockquote>
<p>注意:在内部 <code>race</code> 构建在一个更通用的函数 <code>select</code> 之上,你会在真实的 Rust 代码中更常遇到它。<code>select</code> 函数可以做很多 <code>trpl::race</code> 函数做不了的事,不过它也有一些额外的复杂性,所以目前我们先略过介绍。</p>
</blockquote>
<p>由于任何一个 future 都可以合理地 “获胜”,所以返回 <code>Result</code> 没有意义。相反 <code>race</code> 返回了一个我们之前没有见过的类型 <code>trpl::Either</code><code>Either</code> 类型有点类似于 <code>Result</code>,它也有两个成员。但是不同于 <code>Either</code><code>Either</code> 没有内置成功或者失败的概念。相反它使用 <code>Left</code><code>Right</code> 来表示 “一个或另一个”。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>enum Either&lt;A, B&gt; {
Left(A),
Right(B),
}
<span class="boring">}</span></code></pre></pre>
<p><code>race</code> 函数返回 <code>Left</code>,如果第一个参数先完成,并包含该 future 的输出,如果 <em>第二个</em> future 先完成,则返回 <code>Right</code> 和第二个 future 的输出。这匹配调用函数时参数出现的顺序:第一个参数在第二个参数的左边。</p>
<p>我们还更新了 <code>page_title</code> 来返回与传递时相同的 URL。如此如果首先返回的页面没有可以解析的 <code>&lt;title&gt;</code>,仍然可以打印出有意义的信息。有了这些信息,我们对 <code>println!</code> 的输出进行了封装和更新,以表明哪个 URL 最先完成,并在页面有 <code>&lt;title&gt;</code> 时打印出它的内容。</p>
<p>现在我们完成一个小型网页爬虫的构建了!挑选一对 URL 并运行命令行工具。你会发现某些网站稳定地快于其它网站,而有些情况哪些网站会 <em></em> 则每次都不同。更重要的是,你已经掌握了处理 futures 的基础知识,因此我们现在可以进一步探索更多异步操作的可能性了。</p>
<!-- TODO: map source link version to version of Rust? -->
<div style="break-before: page; page-break-before: always;"></div><h2 id="并发与-async"><a class="header" href="#并发与-async">并发与 async</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch17-02-concurrency-with-async.md">ch17-02-concurrency-with-async.md</a>
<br>
commit 62d441060d66f9a1c3d3cdfffa8eed40f817d1aa</p>
</blockquote>
<p>在这一部分,我们将使用异步来应对一些与第十六章中通过线程解决的相同的并发问题。因为之前我们已经讨论了很多关键理念了,这一部分我们会专注于线程与 future 的区别。</p>
<p>在很多情况下,使用异步处理并发的 API 与使用线程的非常相似。在其它的一些情况,它们则非常不同。即便线程与异步的的 API <em>看起来</em> 很类似,通常它们有着不同的行为,同时它们几乎总是有着不同的性能特点。</p>
<h3 id="计数"><a class="header" href="#计数">计数</a></h3>
<p>第十六章中我们应付的第一个任务是在两个不同的线程中计数。让我们用异步来完成相同的任务。<code>trpl</code> crate 提供了一个 <code>spawn_task</code> 函数,它看起来非常像 <code>thread::spawn</code> API和一个 <code>sleep</code> 函数,这是 <code>thread::sleep</code> API 的异步版本。我们可以将它们结合使用,实现与线程示例相同的计数功能,如示例 17-6 所示。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span>use std::time::Duration;
fn main() {
trpl::run(async {
trpl::spawn_task(async {
for i in 1..10 {
println!("hi number {i} from the first task!");
trpl::sleep(Duration::from_millis(500)).await;
}
});
for i in 1..5 {
println!("hi number {i} from the second task!");
trpl::sleep(Duration::from_millis(500)).await;
}
});
}</code></pre></pre>
<figcaption>示例 17-6使用 `spawn_task` 启动两个计数任务</figcaption>
</figure>
<p>作为开始,我们在 <code>main</code> 函数中使用 <code>trpl::run</code>,这样我们的顶层函数可以是异步的。</p>
<blockquote>
<p>注意:本章从现在开始,每一个示例的 <code>main</code> 中都会包含几乎相同的 <code>trpl::run</code> 封装代码,所以我们经常会连同 <code>main</code> 一同省略。别忘了在你的代码中加入它们!</p>
</blockquote>
<p>接着我们在代码块中编写了两个循环,每个其中都有一个 <code>trpl::sleep</code> 调用每一个都在发送下一个信息之前等待半秒500 毫秒)。我们将一个循环放到 <code>trpl::spawn_task</code> 中并将另一个放在顶层的 <code>for</code> 循环中。我们也在 <code>sleep</code> 调用之后加入了一个 <code>await</code></p>
<p>这个实现与基于线程的版本类似,包括在运行时,你可能会在终端中看到消息以不同顺序出现的情况。</p>
<!-- Not extracting output because changes to this output aren't significant;
the changes are likely to be due to the threads running differently rather than
changes in the compiler -->
<pre><code class="language-text">hi number 1 from the second task!
hi number 1 from the first task!
hi number 2 from the first task!
hi number 2 from the second task!
hi number 3 from the first task!
hi number 3 from the second task!
hi number 4 from the first task!
hi number 4 from the second task!
hi number 5 from the first task!
</code></pre>
<p>这个版本在 main 中的异步代码块中 for 循环结束后就停止了,因为当 main 函数结束时 <code>spawn_task</code> 产生的任务就会关闭。如果运行该任务直到结束,你需要使用一个 join 句柄join handle来等待第一个任务完成。对于线程来说可以使用 <code>join</code> 方法来 “阻塞” 直到线程结束运行。在示例 17-7 中,我们可以使用 <code>await</code> 来实现相同的效果,因为任务句柄本身是一个 future。它的 <code>Output</code> 类型是一个 <code>Result</code>,所以我们还需要 unwrap 来 await 它。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span> let handle = trpl::spawn_task(async {
for i in 1..10 {
println!("hi number {i} from the first task!");
trpl::sleep(Duration::from_millis(500)).await;
}
});
for i in 1..5 {
println!("hi number {i} from the second task!");
trpl::sleep(Duration::from_millis(500)).await;
}
handle.await.unwrap();
<span class="boring"> });
</span><span class="boring">}</span></code></pre></pre>
<figcaption>示例 17-7在一个 join 句柄上使用 `await` 使得任务运行直到结束</figcaption>
</figure>
<p>更新后的版本会运行 <em>两个</em> 循环直到结束。</p>
<!-- Not extracting output because changes to this output aren't significant;
the changes are likely to be due to the threads running differently rather than
changes in the compiler -->
<pre><code class="language-text">hi number 1 from the second task!
hi number 1 from the first task!
hi number 2 from the first task!
hi number 2 from the second task!
hi number 3 from the first task!
hi number 3 from the second task!
hi number 4 from the first task!
hi number 4 from the second task!
hi number 5 from the first task!
hi number 6 from the first task!
hi number 7 from the first task!
hi number 8 from the first task!
hi number 9 from the first task!
</code></pre>
<p>目前为止,看起来异步和线程版本给出了基本一样的输出,它们只是使用了不同的语法:在 join 句柄上使用 <code>await</code> 而不是调用 <code>join</code>,和 await <code>sleep</code> 调用。</p>
<p>最大的区别在于无需再产生另一个操作系统线程来进行工作。事实上,我们甚至不需要产生一个任务。因为异步代码块会编译为匿名 future我们可以将每一个循环放进一个异步代码块并使用 <code>trpl::join</code> 方法来让运行时将它们两个都运行至完成。</p>
<p>在第十六章中,我们展示了如何在 <code>std::thread::spawn</code> 调用返回的 <code>JoinHandle</code> 类型上调用 <code>join</code> 方法。<code>trpl::join</code> 函数也类似,不过它作用于 future。当你传递两个 future它会产生单独一个 future 但它的输出是一个元组,当 <em>两者</em> 都完成时其中有每一个传递给它的 future 的输出。因此,在示例 17-8 中,我们使用 <code>trpl::join</code> 来等待 <code>fut1</code><code>fut2</code> 都结束。我们 <em>没有</em> await <code>fut1</code><code>fut2</code>,而是等待 <code>trpl::join</code> 新产生的 future。我们忽略其输出因为它只是一个包含两个单元值unit value的元组。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span> let fut1 = async {
for i in 1..10 {
println!("hi number {i} from the first task!");
trpl::sleep(Duration::from_millis(500)).await;
}
};
let fut2 = async {
for i in 1..5 {
println!("hi number {i} from the second task!");
trpl::sleep(Duration::from_millis(500)).await;
}
};
trpl::join(fut1, fut2).await;
<span class="boring"> });
</span><span class="boring">}</span></code></pre></pre>
<figcaption>示例 17-8使用 `trpl::join` 来 await 两个匿名 future</figcaption>
</figure>
<p>当运行代码我们会看到两个 future 会运行至结束:</p>
<!-- Not extracting output because changes to this output aren't significant;
the changes are likely to be due to the threads running differently rather than
changes in the compiler -->
<pre><code class="language-text">hi number 1 from the first task!
hi number 1 from the second task!
hi number 2 from the first task!
hi number 2 from the second task!
hi number 3 from the first task!
hi number 3 from the second task!
hi number 4 from the first task!
hi number 4 from the second task!
hi number 5 from the first task!
hi number 6 from the first task!
hi number 7 from the first task!
hi number 8 from the first task!
hi number 9 from the first task!
</code></pre>
<p>这里,你每次都会看到完全相同的顺序,这与我们在线程中看到的情况非常不同。这是因为 <code>trpl::join</code> 函数是 <em>公平的</em><em>fair</em>),这意味着它以相同的频率检查每一个 future使它们交替执行绝不会让一个任务在另一个任务准备好时抢先执行。对于线程来说操作系统会决定该检查哪个线程和会让它运行多长时间。对于异步 Rust 来说,运行时决定检查哪一个任务。(在实践中,细节会更为复杂,因为异步运行时可能在底层使用操作系统线程来作为其并发管理的一部分,因此要保证公平性可能会增加运行时的工作量,但这仍然是可行的!)运行时无需为任何操作保证公平性,同时运行时也经常提供不同的 API 来让你选择是否需要公平性。</p>
<p>尝试这些不同的 await future 的变体来观察它们的效果:</p>
<ul>
<li>去掉一个或者两个循环外的异步代码块。</li>
<li>在定义两个异步代码块后立刻 await 它们。</li>
<li>直将第一个循环封装进异步代码块,并在第二个循环体之后 await 作为结果的 future。</li>
</ul>
<p>作为额外的挑战,看看你能否在运行代码 <em>之前</em> 想出每个情况下的输出!</p>
<h3 id="消息传递"><a class="header" href="#消息传递">消息传递</a></h3>
<p>在 future 之间共享数据也与线程类似:我们会再次使用消息传递,不过这次使用的是异步版本的类型和函数。我们会采用与之前第十六章中使用的稍微不同的方法,来展示一些基于线程的并发与基于 future 的并发之间的关键差异。在示例 17-9 中,我们会从仅有一个异步代码块开始,<em>不像</em> 之前产生独立线程那样产生一个独立的任务。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span> let (tx, mut rx) = trpl::channel();
let val = String::from("hi");
tx.send(val).unwrap();
let received = rx.recv().await.unwrap();
println!("Got: {received}");
<span class="boring"> });
</span><span class="boring">}</span></code></pre></pre>
<figcaption>示例 17-9创建一个异步信道async channel并赋值其两端为 `tx` 和 `rx`</figcaption>
</figure>
<p>这里我们使用了 <code>trpl::channel</code>,一个第十六章用于线程的多生产者、单消费者信道 API 的异步版本。异步版本的 API 与基于线程的版本只有一点微小的区别:它使用一个可变的而不是不可变的 <code>rx</code>,并且它的 <code>recv</code> 方法产生一个需要 await 的 future 而不是直接返回值。现在我们可以发送端向接收端发送消息了。注意我们无需产生一个独立的线程或者任务只需等待await <code>rx.recv</code> 调用。</p>
<p><code>std::mpsc::channel</code> 中的同步 <code>Receiver::recv</code> 方法阻塞执行直到它接收一个消息。<code>trpl::Receiver::recv</code> 则不会阻塞,因为它是异步的。不同于阻塞,它将控制权交还给运行时,直到接收到一个消息或者信道的发送端关闭。相比之下,我们不用 await <code>send</code>,因为它不会阻塞。也无需阻塞,因为信道的发送端的数量是没有限制的。</p>
<blockquote>
<p>注意:因为所有这些异步代码都运行在一个 <code>trpl::run</code> 调用的异步代码块中,其中的所有代码可以避免阻塞。然而,<em>外面</em> 的代码会阻塞到 <code>run</code> 函数返回。这正是 <code>trpl::run</code> 函数的全部意义:它允许你 <em>选择</em> 在何处阻塞一部分异步代码,也就是在何处进行同步和异步代码的转换。这正是在大部分运行时中 <code>run</code> 实际上被命名为 <code>block_on</code> 的原因。</p>
</blockquote>
<p>请注意这个示例中的两个地方:首先,消息立刻就会到达!其次,虽然我们使用了 future但是这里还没有并发。示例中的所有事情都是顺序发生的就像没涉及到 future 时一样。</p>
<p>让我们通过发送一系列消息并在之间休眠来解决第一个问题,如示例 17-10 所示:</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span><span class="boring"> let (tx, mut rx) = trpl::channel();
</span><span class="boring">
</span><span class="boring"> let vals = vec![
</span><span class="boring"> String::from("hi"),
</span><span class="boring"> String::from("from"),
</span><span class="boring"> String::from("the"),
</span><span class="boring"> String::from("future"),
</span><span class="boring"> ];
</span><span class="boring">
</span><span class="boring"> for val in vals {
</span><span class="boring"> tx.send(val).unwrap();
</span><span class="boring"> trpl::sleep(Duration::from_millis(500)).await;
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> while let Some(value) = rx.recv().await {
</span><span class="boring"> println!("received '{value}'");
</span><span class="boring"> }
</span><span class="boring"> });
</span><span class="boring">}</span></code></pre></pre>
<figcaption>示例 17-10通过异步信道发送和接收多个消息并在每个消息之间通过 `await` 休眠</figcaption>
</figure>
<p>除了发送消息之外,我们还需要接收它们。在这个例子中我们可以手动接收,就是调用四次 <code>rx.recv().await</code>,因为我们知道进来了多少条消息。然而,在现实世界中,我们通常会等待 <em>未知</em> 数量的消息。这时我们需要一直等待直到可以确认没有更多消息了为止。</p>
<p>在示例 16-10 中,我们使用了 <code>for</code> 循坏来处理从异步信道接收的所有消息。然而Rust 目前还没有在 <em>异步</em> 序列上编写 <code>for</code> 循环的方法。取而代之的是,我们需要一个我们还没有见过的新循环类型,即 <code>while let</code> 条件循环。<code>while let</code> 循环是我们在第六章中见过的 <code>if let</code> 结构的循环版本。只要其指定的模式持续匹配循环就会一直执行。</p>
<p><code>rx.recv</code> 调用产生一个 <code>Future</code>,我们会 await 它。运行时会暂停 <code>Future</code> 直到它就绪。一旦消息到达future 会解析为 <code>Some(message)</code>,每次消息到达时都会如此。。当信道关闭时,不管是否有 <em>任何</em> 消息到达future 都会解析为 <code>None</code> 来表明没有更多的值了,我们也就应该停止轮询,也就是停止等待。</p>
<p><code>while let</code> 循环将上述逻辑整合在一起。如果 <code>rx.recv().await</code> 调用的结果是 <code>Some(message)</code>,我们会得到消息并可以在循环体中使用它,就像使用 <code>if let</code> 一样。如果结果是 <code>None</code>,则循环停止。每次循环执行完毕,它会再次触发 await point如此运行时会再次暂停直到另一条消息到达。</p>
<p>现在代码可以成功发送和接收所有的消息了。不幸的是这里还有一些问题。首先消息并不是按照半秒的间隔到达的。它们在程序启动后两秒2000 毫秒)后立刻一起到达。其次,程序永远也不会退出!相反它会永远等待新消息。你会需要使用 <span class="keystroke">ctrl-c</span> 来关闭它。</p>
<p>让我们开始理解为何消息在全部延迟后立刻一起到达,而不是逐个在延迟后到达。在一个给定的异步代码块,<code>await</code> 关键字在代码中出现的顺序也就是程序执行时其发生的顺序。</p>
<p>示例 17-10 中只有一个异步代码块,所以所有的代码线性地执行。这里仍然没有并发。所有 <code>tx.send</code> 调用与 <code>trpl::sleep</code> 调用及其相关的 await point 是依次进行的。只有在此之后 <code>while let</code> 循环才开始执行 <code>recv</code> 调用上的 <code>await</code> point。</p>
<p>为了得到我们需要的行为,在接收每条消息之间引入休眠延迟,我们需要将 <code>tx</code><code>rx</code> 操作放置于它们各自的异步代码块中。这样运行时就可以使用 <code>trpl::join</code> 来分别执行它们,就像在计数示例中一样。我们再一次 await <code>trpl::join</code> 调用的结果,而不是它们各自的 future。如果我们顺序地 await 单个 future则就又回到了一个顺序流这正是我们 <em></em> 希望做的。</p>
<!-- We cannot test this one because it never stops! -->
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span><span class="boring"> let (tx, mut rx) = trpl::channel();
</span><span class="boring">
</span> let tx_fut = async {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_millis(500)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};
trpl::join(tx_fut, rx_fut).await;
<span class="boring"> });
</span><span class="boring">}</span></code></pre>
<figcaption>示例 17-11将 `send` 和 `recv` 分隔到其各自的 `async` 代码块中并 await 这些代码块的 future</figcaption>
</figure>
<p>采用示例 17-11 中的更新后的代码,消息会以 500 毫秒的间隔打印,而不是在两秒后就全部一起打印。</p>
<p>但是程序仍然永远也不会退出,这是由于 <code>while let</code> 循环与 <code>trpl::join</code> 的交互方式所致:</p>
<ul>
<li><code>trpl::join</code> 返回的 future 只会完成一次,即传递的 <em>两个</em> future 都完成的时候。</li>
<li><code>tx</code> future 在发送 <code>vals</code> 中最后一条消息之后的休眠结束后立刻完成。</li>
<li><code>rx</code> future 直到 <code>while let</code> 循环结束之前都不会完成。</li>
<li>当信道的另一端关闭后 await <code>rx.recv</code> 将只会返回 <code>None</code></li>
<li>信道只有在调用 <code>rx.close</code> 或者发送端 <code>tx</code> 被丢弃时才会关闭。</li>
<li>我们没有在任何地方调用 <code>rx.close</code>,并且 <code>tx</code> 直到传递给 <code>trpl::run</code> 的最外层异步代码块结束前都不会被丢弃。</li>
<li>代码块不能结束是因为它阻塞在了等待 <code>trpl::join</code> 完成,这就又回到了列表的开头!</li>
</ul>
<p>我们可以在代码的某处调用 <code>rx.close</code> 来手动关闭 <code>rx</code>,不过这并没有太多意义。在处理了任意数量的消息后停止可以使程序停止,但是可能会丢失消息。我们需要其它的手段来确保 <code>tx</code> 在函数的结尾 <em>之前</em> 被丢弃。</p>
<p>目前发送消息的异步代码块只是借用了 <code>tx</code>,因为发送消息并不需要其所有权,但是如果我们可以将 <code>tx</code> 移动move进异步代码快它会在代码块结束后立刻被丢弃。在第十三章中我们学习了如何在闭包上使用 <code>move</code> 关键字,在第十六章中,我们知道了使用线程时经常需要移动数据进闭包。同样的基本原理也适用于异步代码块,因此 <code>move</code> 关键字也能像闭包那样作用于异步代码块。</p>
<p>在示例 17-12 中,我们将发送消息的异步代码块从普通的 <code>async</code> 代码块修改为 <code>async move</code> 代码块。当运行 <em>这个</em> 版本的代码时,它会在发送和接收完最后一条消息后优雅地关闭。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span> let (tx, mut rx) = trpl::channel();
let tx_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_millis(500)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
eprintln!("received '{value}'");
}
};
trpl::join(tx_fut, rx_fut).await;
<span class="boring"> });
</span><span class="boring">}</span></code></pre></pre>
<figcaption>示例 17-12一个可以工作的在 future 之间接收和发送消息的示例,其在结束后会正确地关闭</figcaption>
</figure>
<p>这个异步信道也是一个多生产者信道,所以如果希望从多个 future 发送消息可以调用 <code>tx</code> 上的 <code>clone</code> 方法。在示例 17-13 中,我们克隆了 <code>tx</code>,在第一个异步代码块外面创建 <code>tx1</code>。我们像第一个 <code>tx</code> 一样将 <code>tx1</code> 移动进代码块。接下来,将原始的 <code>tx</code> 移动进一个 <em>新的</em> 异步代码块,其中会用一个稍微更长的延迟发送更多的消息。我们碰巧将新代码块放在接收消息的异步代码块之后,不过也可以放在之前。关键在于 future 被 await 的顺序,而不是它们创建的顺序。</p>
<p>两个发送消息的异步代码块需要是 <code>async move</code> 代码块,如此 <code>tx</code><code>tx1</code> 都会在代码块结束后被丢弃。否则我们就会陷入到开始时同样的无限循环。最后,我们从 <code>trpl::join</code> 切换到 <code>trpl::join3</code> 来处理额外的 future。</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span> let (tx, mut rx) = trpl::channel();
let tx1 = tx.clone();
let tx1_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx1.send(val).unwrap();
trpl::sleep(Duration::from_millis(500)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};
let tx_fut = async move {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_millis(1500)).await;
}
};
trpl::join3(tx1_fut, tx_fut, rx_fut).await;
<span class="boring"> });
</span><span class="boring">}</span></code></pre></pre>
<figcaption>示例 17-13通过多个异步代码块使用多个发送者</figcaption>
</figure>
<p>现在我们会看到所有来在两个发送 future 的消息。因为发送 future 采用了稍微不同的发送延迟,消息也会以这些不同的延迟接收。</p>
<!-- Not extracting output because changes to this output aren't significant;
the changes are likely to be due to the threads running differently rather than
changes in the compiler -->
<pre><code class="language-text">received 'hi'
received 'more'
received 'from'
received 'the'
received 'messages'
received 'future'
received 'for'
received 'you'
</code></pre>
<p>这是一个良好的开始,不过它将我们限制到少数几个 future<code>join</code> 两个,或者 <code>join3</code> 三个。让我们看下如何处理更多的 future。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="使用任意数量的-futures"><a class="header" href="#使用任意数量的-futures">使用任意数量的 futures</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch17-03-more-futures.md">ch17-03-more-futures.md</a>
<br>
commit 9e85fcc9938e8f8c935d0ad8b4db7f45caaa2ca4</p>
</blockquote>
<p>当我们在上一部分从使用两个 future 到三个 future 的时候,我们也必须从使用 <code>join</code> 切换到 <code>join3</code>。每次我们想要改变 join 的 future 数量时都不得不调用一个不同的函数是很烦人的。令人高兴的是,我们有一个宏版本的 <code>join</code> 可以传递任意数量的参数。它还会自行处理 await 这些 future。因此我们可以重写示例 17-13 中的代码来使用 <code>join!</code> 而不是 <code>join3</code>,如示例 17-14 所示:</p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span><span class="boring"> let (tx, mut rx) = trpl::channel();
</span><span class="boring">
</span><span class="boring"> let tx1 = tx.clone();
</span><span class="boring"> let tx1_fut = async move {
</span><span class="boring"> let vals = vec![
</span><span class="boring"> String::from("hi"),
</span><span class="boring"> String::from("from"),
</span><span class="boring"> String::from("the"),
</span><span class="boring"> String::from("future"),
</span><span class="boring"> ];
</span><span class="boring">
</span><span class="boring"> for val in vals {
</span><span class="boring"> tx1.send(val).unwrap();
</span><span class="boring"> trpl::sleep(Duration::from_secs(1)).await;
</span><span class="boring"> }
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let rx_fut = async {
</span><span class="boring"> while let Some(value) = rx.recv().await {
</span><span class="boring"> println!("received '{value}'");
</span><span class="boring"> }
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let tx_fut = async move {
</span><span class="boring"> let vals = vec![
</span><span class="boring"> String::from("more"),
</span><span class="boring"> String::from("messages"),
</span><span class="boring"> String::from("for"),
</span><span class="boring"> String::from("you"),
</span><span class="boring"> ];
</span><span class="boring">
</span><span class="boring"> for val in vals {
</span><span class="boring"> tx.send(val).unwrap();
</span><span class="boring"> trpl::sleep(Duration::from_secs(1)).await;
</span><span class="boring"> }
</span><span class="boring"> };
</span><span class="boring">
</span> trpl::join!(tx1_fut, tx_fut, rx_fut);
<span class="boring"> });
</span><span class="boring">}</span></code></pre></pre>
<figcaption>示例 17-14使用 `join!` 来等待多个 future</figcaption>
</figure>
<p>相比需要在 <code>join</code><code>join3</code><code>join4</code> 等等直接切换来说这绝对是一个进步!然而,即便是这个宏形式也只能用于我们提前知道 future 的数量的时候。不过,在现实世界的 Rust 中,将 futures 放进一个集合并接着等待集合中的一些或者全部 future 完成是一个常见的模式。</p>
<p>为了检查一些集合中的所有 future我们需要遍历并 join 它们 <em>全部</em><code>trpl::join_all</code> 函数接受任何实现了 <code>Iterator</code> trait 的类型,我们在之前的第十三章中学习过它们,所以这正是我们需要的。让我们将 futures 放进一个向量,并将 <code>join!</code> 替换为 <code>join_all</code></p>
<figure class="listing">
<p><span class="file-name">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">extern crate trpl; // required for mdbook test
</span><span class="boring">
</span><span class="boring">use std::time::Duration;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> trpl::run(async {
</span><span class="boring"> let (tx, mut rx) = trpl::channel();
</span><span class="boring">
</span><span class="boring"> let tx1 = tx.clone();
</span><span class="boring"> let tx1_fut = async move {
</span><span class="boring"> let vals = vec![
</span><span class="boring"> String::from("hi"),
</span><span class="boring"> String::from("from"),
</span><span class="boring"> String::from("the"),
</span><span class="boring"> String::from("future"),
</span><span class="boring"> ];
</span><span class="boring">
</span><span class="boring"> for val in vals {
</span><span class="boring"> tx1.send(val).unwrap();
</span><span class="boring"> trpl::sleep(Duration::from_secs(1)).await;
</span><span class="boring"> }
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let rx_fut = async {
</span><span class="boring"> while let Some(value) = rx.recv().await {
</span><span class="boring"> println!("received '{value}'");
</span><span class="boring"> }
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let tx_fut = async move {
</span><span class="boring"> let vals = vec![
</span><span class="boring"> String::from("more"),
</span><span class="boring"> String::from("messages"),
</span><span class="boring"> String::from("for"),
</span><span class="boring"> String::from("you"),
</span><span class="boring"> ];
</span><span class="boring">
</span><span class="boring"> for val in vals {
</span><span class="boring"> tx.send(val).unwrap();
</span><span class="boring"> trpl::sleep(Duration::from_secs(1)).await;
</span><span class="boring"> }
</span><span class="boring"> };
</span><span class="boring">
</span> let futures = vec![tx1_fut, rx_fut, tx_fut];
trpl::join_all(futures).await;
<span class="boring"> });
</span><span class="boring">}</span></code></pre>
<figcaption>示例 17-15将匿名 futures 储存在一个向量中并调用 `join_all`</figcaption>
</figure>
<p>不幸的是这还不能编译。相反我们会得到这个错误:</p>
<!-- manual-regeneration
cd listings/ch17-async-await/listing-17-16/
cargo build
copy just the compiler error
-->
<pre><code class="language-text">error[E0308]: mismatched types
--&gt; src/main.rs:43:37
|
8 | let tx1_fut = async move {
| _______________________-
9 | | let vals = vec![
10 | | String::from("hi"),
11 | | String::from("from"),
... |
19 | | }
20 | | };
| |_________- the expected `async` block
21 |
22 | let rx_fut = async {
| ______________________-
23 | | while let Some(value) = rx.recv().await {
24 | | println!("received '{value}'");
25 | | }
26 | | };
| |_________- the found `async` block
...
43 | let futures = vec![tx1_fut, rx_fut, tx_fut];
| ^^^^^^ expected `async` block, found a different `async` block
|
= note: expected `async` block `{async block@src/main.rs:8:23: 20:10}`
found `async` block `{async block@src/main.rs:22:22: 26:10}`
= note: no two async blocks, even if identical, have the same type
= help: consider pinning your async block and and casting it to a trait object
</code></pre>
<p>这可能有点令人惊讶。毕竟没有一个 future 返回了任何值,所以每个代码块都会产生一个 <code>Future&lt;Output = ()&gt;</code>。然而,<code>Future</code> 是一个 trait不是一个具体类型。其具体类型是编译器为各个异步代码块生成的不同的数据结构。你不能将两个不同的手写的 struct 放进同一个 <code>Vec</code>,同样的原理也适用于编译器生成的不同 struct。</p>
<p>为了使代码能够正常工作,我们需要使用 <em>trait objects</em>,正如我们在第十二章的 <a href="ch12-03-improving-error-handling-and-modularity.html">“从 <code>run</code> 函数中返回错误”</a> 中做的那样。(第十八章会详细介绍 trait objects。使用 trait objects 允许我们将这些类型所产生的不同的匿名 future 看作相同的类型,因为它们都实现了 <code>Future</code> trait。</p>
<blockquote>
<p>注意:在第八章中,我们讨论过另一种将多种类型包含进一个 <code>Vec</code> 的方式:使用一个枚举来代表每个可以出现在向量中的不同类型。不过这里我们不能这么做。首先,没有方法来命名这些不同的类型,因为它们是匿名的。</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h2 id="流streams"><a class="header" href="#流streams">Streams</a></h2>
<div style="break-before: page; page-break-before: always;"></div><h2 id="深入理解-async-相关的-traits"><a class="header" href="#深入理解-async-相关的-traits">深入理解 async 相关的 traits</a></h2>
<div style="break-before: page; page-break-before: always;"></div><h2 id="futures任务tasks和线程threads"><a class="header" href="#futures任务tasks和线程threads">Futures任务tasks和线程threads</a></h2>
<div style="break-before: page; page-break-before: always;"></div><h1 id="rust-的面向对象特性"><a class="header" href="#rust-的面向对象特性">Rust 的面向对象特性</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch18-00-oop.md">ch18-00-oop.md</a>
<br>
commit 398d6f48d2e6b7b15efd51c4541d446e89de3892</p>
</blockquote>
<p>面向对象编程Object-Oriented ProgrammingOOP是一种对程序进行建模方式。对象Object作为一个编程概念来源于 20 世纪 60 年代的 Simula 编程语言。这些对象影响了 Alan Kay 的编程架构,该架构中对象之间互相传递消息。他在 1967 年创造了 <strong>面向对象编程</strong> <em>object-oriented programming</em>)这个术语。关于 OOP 是什么有很多相互矛盾的定义在一些定义下Rust 是面向对象的在其他定义下Rust 不是。在本章节中,我们会探索一些被普遍认为是面向对象的特性和这些特性是如何体现在 Rust 语言习惯中的。接着会展示如何在 Rust 中实现面向对象设计模式,并讨论这么做与利用 Rust 自身的一些优势实现的方案相比有什么取舍。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="面向对象语言的特征"><a class="header" href="#面向对象语言的特征">面向对象语言的特征</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch18-01-what-is-oo.md">ch18-01-what-is-oo.md</a>
<br>
commit 398d6f48d2e6b7b15efd51c4541d446e89de3892</p>
</blockquote>
<p>关于一门语言必须具备哪些特征才能被视为面向对象目前在编程社区中并没有共识。Rust 受到了许多编程范式的影响包括面向对象编程OOP例如在第 13 章中,我们探讨了来自函数式编程的特性。可以说,面向对象的语言共有一些共同的特征,即对象、封装和继承。我们将会讨论这些特征分别是什么,以及 Rust 是否支持它们。</p>
<h3 id="对象包含数据和行为"><a class="header" href="#对象包含数据和行为">对象包含数据和行为</a></h3>
<p>由 Erich Gamma、Richard Helm、Ralph Johnson 和 John VlissidesAddison-Wesley Professional, 1994编写的书 <em>Design Patterns: Elements of Reusable Object-Oriented Software</em> ,通称 <em>The Gang of Four</em> (“四人帮”),是一本面向对象设计模式的目录。它这样定义面向对象编程:</p>
<blockquote>
<p>Object-oriented programs are made up of objects. An <em>object</em> packages both
data and the procedures that operate on that data. The procedures are
typically called <em>methods</em> or <em>operations</em>.</p>
<p>面向对象的程序由对象组成。一个 <strong>对象</strong> 包含数据和操作这些数据的过程。这些过程通常被称为 <strong>方法</strong><strong>操作</strong></p>
</blockquote>
<p>在这个定义下Rust 是面向对象的:结构体和枚举包含数据而 <code>impl</code> 块提供了在结构体和枚举之上的方法。虽然带有方法的结构体和枚举并不被 <strong>称为</strong> 对象,但是它们提供了与对象相同的功能,参考 <em>The Gang of Four</em> 中对象的定义。</p>
<h3 id="封装隐藏了实现细节"><a class="header" href="#封装隐藏了实现细节">封装隐藏了实现细节</a></h3>
<p>另一个通常与面向对象编程关联的概念是 <strong>封装</strong><em>encapsulation</em>):一个对象的实现细节对使用该对象的代码不可访问。因此,对象交互的唯一方式是通过其公共 API使用对象的代码不应能直接触及对象的内部并改变数据或行为。这使得程序员能够更改和重构一个对象的内部实现而无需改变使用该对象的代码。</p>
<p>我们在第 7 章讨论了如何控制封装:我们可以使用 <code>pub</code> 关键字来决定代码中的哪些模块、类型、函数和方法是公有的,而默认情况下其他所有内容都是私有的。例如,我们可以定义一个 <code>AveragedCollection</code> 结构体,其中有一个存有 <code>Vec&lt;i32&gt;</code> 的字段。该结构体还可以有一个字段存储其平均值,以便需要时取用。示例 17-1 给出了 <code>AveragedCollection</code> 结构体的定义:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub struct AveragedCollection {
list: Vec&lt;i32&gt;,
average: f64,
}</code></pre>
<p><span class="caption">示例 17-1: <code>AveragedCollection</code> 结构体维护了一个整型列表及其所有元素的平均值。</span></p>
<p>该结构体被标记为 <code>pub</code>,这样其他代码就可以使用它,但结构体内的字段保持私有。这在这种情况下很重要,因为我们想确保每当列表中添加或删除值时,平均值也会更新。我们通过实现结构体上的 <code>add</code><code>remove</code><code>average</code> 方法来做到这一点,如示例 17-2 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct AveragedCollection {
</span><span class="boring"> list: Vec&lt;i32&gt;,
</span><span class="boring"> average: f64,
</span><span class="boring">}
</span><span class="boring">
</span>impl AveragedCollection {
pub fn add(&amp;mut self, value: i32) {
self.list.push(value);
self.update_average();
}
pub fn remove(&amp;mut self) -&gt; Option&lt;i32&gt; {
let result = self.list.pop();
match result {
Some(value) =&gt; {
self.update_average();
Some(value)
}
None =&gt; None,
}
}
pub fn average(&amp;self) -&gt; f64 {
self.average
}
fn update_average(&amp;mut self) {
let total: i32 = self.list.iter().sum();
self.average = total as f64 / self.list.len() as f64;
}
}</code></pre>
<p><span class="caption">示例 17-2: 在 <code>AveragedCollection</code> 结构体上实现了 <code>add</code><code>remove</code><code>average</code> 公有方法</span></p>
<p>公有方法 <code>add</code><code>remove</code><code>average</code> 是修改 <code>AveragedCollection</code> 实例的唯一方式。当使用 <code>add</code> 方法把一个元素加入到 <code>list</code> 或者使用 <code>remove</code> 方法来删除时,这些方法的实现同时会调用私有的 <code>update_average</code> 方法来更新 <code>average</code> 字段。</p>
<p><code>list</code><code>average</code> 是私有的,所以没有其他方式来使得外部的代码直接向 <code>list</code> 增加或者删除元素,否则 <code>list</code> 改变时可能会导致 <code>average</code> 字段不同步。<code>average</code> 方法返回 <code>average</code> 字段的值,这使得外部的代码只能读取 <code>average</code> 而不能修改它。</p>
<p>因为我们已经封装了 <code>AveragedCollection</code> 的实现细节,改动数据结构等内部实现非常简单。例如,可以使用 <code>HashSet&lt;i32&gt;</code> 代替 <code>Vec&lt;i32&gt;</code> 作为 <code>list</code> 字段的类型。只要 <code>add</code><code>remove</code><code>average</code> 这些公有方法的签名保持不变,使用 <code>AveragedCollection</code> 的代码就无需改变。如果我们将 <code>list</code> 设为公有,情况就未必如此: <code>HashSet&lt;i32&gt;</code><code>Vec&lt;i32&gt;</code> 使用不同的方法增加或移除项,所以如果外部代码直接修改 <code>list</code> ,很可能需要进行更改。</p>
<p>如果封装被认为是面向对象语言所必要的特征,那么 Rust 满足这个要求。在代码中不同的部分控制 <code>pub</code> 的使用来封装实现细节。</p>
<h2 id="继承作为类型系统与代码共享"><a class="header" href="#继承作为类型系统与代码共享">继承,作为类型系统与代码共享</a></h2>
<p><strong>继承</strong><em>Inheritance</em>)是一种机制:一个对象可以从另一个对象的定义中继承元素,从而获得父对象的数据和行为,无需再次定义。</p>
<p>如果一种语言必须具有继承才能被认为是面向对象语言,那么 Rust 不是其中之一。Rust 不支持定义一个结构体时继承父结构体的字段和方法,除非使用宏。</p>
<p>然而如果您习惯于在编程过程中使用继承那么根据运用继承的原因Rust 提供了其他解决方案。</p>
<p>选择继承有两个主要的原因。其一是代码复用:您可以为一种类型实现特定的行为,继承可将其复用到不同的类型上。在 Rust 代码中可以使用默认 trait 方法实现来进行有限的代码复用,就像示例 10-14 中在 <code>Summary</code> trait 上增加的 <code>summarize</code> 方法的默认实现。任何实现了 <code>Summary</code> trait 的类型都可以使用 <code>summarize</code> 方法而无须进一步实现。这类似于父类有一个方法的实现,继承的子类也拥有这个方法的实现。当实现 <code>Summary</code> trait 时也可以选择覆盖 <code>summarize</code> 的默认实现,这类似于子类覆盖从父类继承方法的实现。</p>
<p>其二与类型系统有关:子类型可以用于父类型被使用的地方。这也被称为 <strong>多态</strong><em>polymorphism</em>):如果多个对象共享某些特征,可以在运行时将它们互相替代。</p>
<blockquote>
<p>多态Polymorphism</p>
<p>对很多人来说,多态性与继承同义。但它实际上是一个更广义的概念,指的是可以处理多种类型数据的代码。对继承而言,这些类型通常是子类。
Rust 使用泛型来抽象不同可能的类型,并通过 trait bounds 来约束这些类型所必须提供的内容。这有时被称为 <em>bounded parametric polymorphism</em></p>
</blockquote>
<p>作为一种语言设计的解决方案,继承在许多新的编程语言中逐渐不被青睐,因为它经常有分享过多代码的风险。子类不应总是共享父类的所有特征,但是继承始终如此。它还引入了在子类上调用方法的可能性,这些方法可能没有意义,或因为方法不适用于子类而导致错误。此外,一些语言只允许单一继承(意味着子类只能从一个类继承),进一步限制了程序设计的灵活性。</p>
<p>出于这些原因Rust 使用 trait 对象而非继承。接下来我们会讨论 Rust 如何使用 trait 对象实现多态性。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="顾及不同类型值的-trait-对象"><a class="header" href="#顾及不同类型值的-trait-对象">顾及不同类型值的 trait 对象</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch18-02-trait-objects.md">ch18-02-trait-objects.md</a>
<br>
commit 96d4b0ec1c5e019b85604c33ceee68b3e2669d40</p>
</blockquote>
<p>在第八章中,我们谈到了 vector 只能存储同种类型元素的局限。示例 8-9 中提供了一个替代方案,通过定义 <code>SpreadsheetCell</code> 枚举,来储存整型、浮点型或文本类型的成员。这意味着,我们可以在每个单元中储存不同类型的数据,并仍能拥有一个代表一排单元的 vector。只要我们需存储的值由一组固定的类型组成并且在代码编译时就知道具体会有哪些类型那么这种使用枚举的办法是完全可行的。</p>
<p>然而有时我们希望库用户在特定情况下能够扩展有效的类型集合。为了展示如何实现这一点这里将创建一个图形用户接口Graphical User InterfaceGUI工具的例子它通过遍历列表并调用每一个项目的 <code>draw</code> 方法来将其绘制到屏幕上 —— 此乃一个 GUI 工具的常见技术。我们将要创建一个叫做 <code>gui</code> 的库 crate它含一个 GUI 库的结构。这个 GUI 库包含一些可供开发者使用的类型,比如 <code>Button</code><code>TextField</code>。在此之上,<code>gui</code> 的用户希望创建自定义的可以绘制于屏幕上的类型:比如,一个程序员可能会增加 <code>Image</code>,另一个可能会增加 <code>SelectBox</code></p>
<p>这个例子中并不会实现一个功能完善的 GUI 库,不过会展示其中各个部分是如何结合在一起的。编写库的时候,我们不可能知晓并定义所有其他程序员希望创建的类型。我们所知晓的是 <code>gui</code> 需要记录一系列不同类型的值,并需要能够对其中每一个值调用 <code>draw</code> 方法。这里无需知道调用 <code>draw</code> 方法时具体会发生什么,只要该值会有那个方法可供我们调用。</p>
<p>在拥有继承的语言中,可以定义一个名为 <code>Component</code> 的类,该类上有一个 <code>draw</code> 方法。其他的类比如 <code>Button</code><code>Image</code><code>SelectBox</code> 会从 <code>Component</code> 派生并因此继承 <code>draw</code> 方法。它们各自都可以覆盖 <code>draw</code> 方法来定义自己的行为,但是框架会把所有这些类型当作是 <code>Component</code> 的实例,并在其上调用 <code>draw</code>。不过 Rust 并没有继承,我们得另寻出路。</p>
<h3 id="定义通用行为的-trait"><a class="header" href="#定义通用行为的-trait">定义通用行为的 trait</a></h3>
<p>为了实现 <code>gui</code> 所期望的行为,让我们定义一个 <code>Draw</code> trait其中包含名为 <code>draw</code> 的方法。接着可以定义一个存放 <strong>trait 对象</strong><em>trait object</em>)的 vector。trait 对象指向一个实现了我们指定 trait 的类型的实例,以及一个用于在运行时查找该类型的 trait 方法的表。我们通过指定某种指针来创建 trait 对象,例如 <code>&amp;</code> 引用或 <code>Box&lt;T&gt;</code> 智能指针,还有 <code>dyn</code> keyword以及指定相关的 trait第二十章 <a href="ch20-04-advanced-types.html#%E5%8A%A8%E6%80%81%E5%A4%A7%E5%B0%8F%E7%B1%BB%E5%9E%8B%E5%92%8C-sized-trait">“动态大小类型和 <code>Sized</code> trait”</a> 部分会介绍 trait 对象必须使用指针的原因)。我们可以使用 trait 对象代替泛型或具体类型。任何使用 trait 对象的位置Rust 的类型系统会在编译时确保任何在此上下文中使用的值会实现其 trait 对象的 trait。如此便无需在编译时就知晓所有可能的类型。</p>
<p>之前提到过Rust 刻意不将结构体与枚举称为 “对象”,以便与其他语言中的对象相区别。在结构体或枚举中,结构体字段中的数据和 <code>impl</code> 块中的行为是分开的不同于其他语言中将数据和行为组合进一个称为对象的概念中。trait 对象将数据和行为两者相结合,从这种意义上说 <strong></strong> 其更类似其他语言中的对象。不过 trait 对象不同于传统的对象,因为不能向 trait 对象增加数据。trait 对象并不像其他语言中的对象那么通用trait 对象)具体的作用是允许对通用行为进行抽象。</p>
<p>示例 17-3 展示了如何定义一个带有 <code>draw</code> 方法的 trait <code>Draw</code></p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub trait Draw {
fn draw(&amp;self);
}</code></pre>
<p><span class="caption">示例 17-3<code>Draw</code> trait 的定义</span></p>
<p>因为第十章已经讨论过如何定义 trait其语法看起来应该比较眼熟。接下来就是新内容了示例 17-4 定义了一个存放了名叫 <code>components</code> 的 vector 的结构体 <code>Screen</code>。这个 vector 的类型是 <code>Box&lt;dyn Draw&gt;</code>,此为一个 trait 对象:它是 <code>Box</code> 中任何实现了 <code>Draw</code> trait 的类型的替身。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Draw {
</span><span class="boring"> fn draw(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span>pub struct Screen {
pub components: Vec&lt;Box&lt;dyn Draw&gt;&gt;,
}</code></pre>
<p><span class="caption">示例 17-4: 一个 <code>Screen</code> 结构体的定义,它带有一个字段 <code>components</code>,其包含实现了 <code>Draw</code> trait 的 trait 对象的 vector</span></p>
<p><code>Screen</code> 结构体上,我们将定义一个 <code>run</code> 方法,该方法会对其 <code>components</code> 上的每一个组件调用 <code>draw</code> 方法,如示例 17-5 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Draw {
</span><span class="boring"> fn draw(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct Screen {
</span><span class="boring"> pub components: Vec&lt;Box&lt;dyn Draw&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>impl Screen {
pub fn run(&amp;self) {
for component in self.components.iter() {
component.draw();
}
}
}</code></pre>
<p><span class="caption">示例 17-5<code>Screen</code> 上实现一个 <code>run</code> 方法,该方法在每个 component 上调用 <code>draw</code> 方法</span></p>
<p>这与定义使用了带有 trait bound 的泛型类型参数的结构体不同。泛型类型参数一次只能替代一个具体类型,而 trait 对象则允许在运行时替代多种具体类型。例如,可以定义 <code>Screen</code> 结构体来使用泛型和 trait bound如示例 17-6 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Draw {
</span><span class="boring"> fn draw(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span>pub struct Screen&lt;T: Draw&gt; {
pub components: Vec&lt;T&gt;,
}
impl&lt;T&gt; Screen&lt;T&gt;
where
T: Draw,
{
pub fn run(&amp;self) {
for component in self.components.iter() {
component.draw();
}
}
}</code></pre>
<p><span class="caption">示例 17-6: 一种 <code>Screen</code> 结构体的替代实现,其 <code>run</code> 方法使用泛型和 trait bound</span></p>
<p>这限制了 <code>Screen</code> 实例必须拥有一个全是 <code>Button</code> 类型或者全是 <code>TextField</code> 类型的组件列表。如果只需要同质(相同类型)集合,则倾向于使用泛型和 trait bound因为其定义会在编译时采用具体类型进行单态化。</p>
<p>另一方面,通过使用 trait 对象的方法,一个 <code>Screen</code> 实例可以存放一个既能包含 <code>Box&lt;Button&gt;</code>,也能包含 <code>Box&lt;TextField&gt;</code><code>Vec&lt;T&gt;</code>。让我们看看它是如何工作的,接着会讲到其运行时性能影响。</p>
<h3 id="实现-trait"><a class="header" href="#实现-trait">实现 trait</a></h3>
<p>现在来增加一些实现了 <code>Draw</code> trait 的类型。我们将提供 <code>Button</code> 类型。再一次重申,真正实现 GUI 库超出了本书的范畴,所以 <code>draw</code> 方法体中不会有任何有意义的实现。为了想象一下这个实现看起来像什么,一个 <code>Button</code> 结构体可能会拥有 <code>width</code><code>height</code><code>label</code> 字段,如示例 17-7 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub trait Draw {
</span><span class="boring"> fn draw(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct Screen {
</span><span class="boring"> pub components: Vec&lt;Box&lt;dyn Draw&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Screen {
</span><span class="boring"> pub fn run(&amp;self) {
</span><span class="boring"> for component in self.components.iter() {
</span><span class="boring"> component.draw();
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>pub struct Button {
pub width: u32,
pub height: u32,
pub label: String,
}
impl Draw for Button {
fn draw(&amp;self) {
// code to actually draw a button
}
}</code></pre>
<p><span class="caption">示例 17-7: 一个实现了 <code>Draw</code> trait 的 <code>Button</code> 结构体</span></p>
<p><code>Button</code> 上的 <code>width</code><code>height</code><code>label</code> 字段会和其他组件不同,比如 <code>TextField</code> 可能有 <code>width</code><code>height</code><code>label</code> 以及 <code>placeholder</code> 字段。每一个我们希望能在屏幕上绘制的类型都会使用不同的代码来实现 <code>Draw</code> trait 的 <code>draw</code> 方法来定义如何绘制特定的类型,像这里的 <code>Button</code> 类型(如上提到的并不包含任何实际的 GUI 代码)。除了实现 <code>Draw</code> trait 之外,比如 <code>Button</code> 还可能有另一个包含按钮点击如何响应的方法的 <code>impl</code> 块。这类方法并不适用于像 <code>TextField</code> 这样的类型。</p>
<p>如果一些库的使用者决定实现一个包含 <code>width</code><code>height</code><code>options</code> 字段的结构体 <code>SelectBox</code>,并且也为其实现了 <code>Draw</code> trait如示例 17-8 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use gui::Draw;
struct SelectBox {
width: u32,
height: u32,
options: Vec&lt;String&gt;,
}
impl Draw for SelectBox {
fn draw(&amp;self) {
// code to actually draw a select box
}
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p><span class="caption">示例 17-8: 另一个使用 <code>gui</code> 的 crate 中,在 <code>SelectBox</code> 结构体上实现 <code>Draw</code> trait</span></p>
<p>库使用者现在可以在他们的 <code>main</code> 函数中创建一个 <code>Screen</code> 实例。至此可以通过将 <code>SelectBox</code><code>Button</code> 放入 <code>Box&lt;T&gt;</code> 转变为 trait 对象再放入 <code>Screen</code> 实例中。接着可以调用 <code>Screen</code><code>run</code> 方法,它会调用每个组件的 <code>draw</code> 方法。示例 17-9 展示了这个实现:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use gui::Draw;
</span><span class="boring">
</span><span class="boring">struct SelectBox {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring"> options: Vec&lt;String&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Draw for SelectBox {
</span><span class="boring"> fn draw(&amp;self) {
</span><span class="boring"> // code to actually draw a select box
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>use gui::{Button, Screen};
fn main() {
let screen = Screen {
components: vec![
Box::new(SelectBox {
width: 75,
height: 10,
options: vec![
String::from("Yes"),
String::from("Maybe"),
String::from("No"),
],
}),
Box::new(Button {
width: 50,
height: 10,
label: String::from("OK"),
}),
],
};
screen.run();
}</code></pre>
<p><span class="caption">示例 17-9: 使用 trait 对象来存储实现了相同 trait 的不同类型的值</span></p>
<p>当编写库的时候,我们不知道何人会在何时增加 <code>SelectBox</code> 类型,不过 <code>Screen</code> 的实现能够操作并绘制这个新类型,因为 <code>SelectBox</code> 实现了 <code>Draw</code> trait这意味着它实现了 <code>draw</code> 方法。</p>
<p>这个概念 —— 只关心值所反映的信息而不是其具体类型 —— 类似于动态类型语言中称为 <strong>鸭子类型</strong><em>duck typing</em>)的概念:如果它走起来像一只鸭子,叫起来像一只鸭子,那么它就是一只鸭子!在示例 17-5 中 <code>Screen</code> 上的 <code>run</code> 实现中,<code>run</code> 并不需要知道各个组件的具体类型是什么。它并不检查组件是 <code>Button</code> 或者 <code>SelectBox</code> 的实例。通过指定 <code>Box&lt;dyn Draw&gt;</code> 作为 <code>components</code> vector 中值的类型,我们就定义了 <code>Screen</code> 为需要可以在其上调用 <code>draw</code> 方法的值。</p>
<p>使用 trait 对象和 Rust 类型系统来进行类似鸭子类型操作的优势是无需在运行时检查一个值是否实现了特定方法或者担心在调用时因为值没有实现方法而产生错误。如果值没有实现 trait 对象所需的 trait 则 Rust 不会编译这些代码。</p>
<p>例如,示例 17-10 展示了当创建一个使用 <code>String</code> 做为其组件的 <code>Screen</code> 时发生的情况:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use gui::Screen;
fn main() {
let screen = Screen {
components: vec![Box::new(String::from("Hi"))],
};
screen.run();
}</code></pre>
<p><span class="caption">示例 17-10: 尝试使用一种没有实现 trait 对象的 trait 的类型</span></p>
<p>我们会遇到这个错误,因为 <code>String</code> 没有实现 <code>rust_gui::Draw</code> trait</p>
<pre><code class="language-console">$ cargo run
Compiling gui v0.1.0 (file:///projects/gui)
error[E0277]: the trait bound `String: Draw` is not satisfied
--&gt; src/main.rs:5:26
|
5 | components: vec![Box::new(String::from("Hi"))],
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String`
|
= help: the trait `Draw` is implemented for `Button`
= note: required for the cast from `Box&lt;String&gt;` to `Box&lt;dyn Draw&gt;`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `gui` (bin "gui") due to 1 previous error
</code></pre>
<p>这告诉了我们,要么是我们传递了并不希望传递给 <code>Screen</code> 的类型并应该提供其他类型,要么应该在 <code>String</code> 上实现 <code>Draw</code> 以便 <code>Screen</code> 可以调用其上的 <code>draw</code></p>
<h3 id="trait-对象执行动态分发"><a class="header" href="#trait-对象执行动态分发">trait 对象执行动态分发</a></h3>
<p>回忆一下第十章 <a href="ch10-01-syntax.html#%E6%B3%9B%E5%9E%8B%E4%BB%A3%E7%A0%81%E7%9A%84%E6%80%A7%E8%83%BD">“泛型代码的性能”</a> 部分讨论过的,当对泛型使用 trait bound 时编译器所执行的单态化处理:编译器为每一个被泛型类型参数代替的具体类型生成了函数和方法的非泛型实现。单态化产生的代码在执行 <strong>静态分发</strong><em>static dispatch</em>)。静态分发发生于编译器在编译时就知晓调用了什么方法的时候。这与 <strong>动态分发</strong> <em>dynamic dispatch</em>)相对,这时编译器在编译时无法知晓调用了什么方法。在动态分发的场景下,编译器会生成负责在运行时确定该调用什么方法的代码。</p>
<p>当使用 trait 对象时Rust 必须使用动态分发。编译器无法知晓所有可能用于 trait 对象代码的类型所以它也不知道应该调用哪个类型的哪个方法实现。为此Rust 在运行时使用 trait 对象中的指针来知晓需要调用哪个方法。动态分发也阻止编译器有选择的内联方法代码,这会相应的禁用一些优化。尽管在编写示例 17-5 和可以支持示例 17-9 中的代码的过程中确实获得了额外的灵活性,但仍然需要权衡取舍。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="面向对象设计模式的实现"><a class="header" href="#面向对象设计模式的实现">面向对象设计模式的实现</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch18-03-oo-design-patterns.md">ch18-03-oo-design-patterns.md</a>
<br>
commit 937784b8708c24314707378ad42faeb12a334bbd</p>
</blockquote>
<p><strong>状态模式</strong><em>state pattern</em>)是一个面向对象设计模式。该模式的关键在于定义一系列值的内含状态。这些状态体现为一系列的 <strong>状态对象</strong>,同时值的行为随着其内部状态而改变。我们将编写一个博客发布结构体的例子,它拥有一个包含其状态的字段,这是一个有着 "draft"、"review" 或 "published" 的状态对象</p>
<p>状态对象共享功能:当然,在 Rust 中使用结构体和 trait 而不是对象和继承。每一个状态对象负责其自身的行为,以及该状态何时应当转移至另一个状态。持有一个状态对象的值对于不同状态的行为以及何时状态转移毫不知情。</p>
<p>使用状态模式的优点在于,程序的业务需求改变时,无需改变值持有状态或者使用值的代码。我们只需更新某个状态对象中的代码来改变其规则,或者是增加更多的状态对象。</p>
<p>首先我们将以一种更加传统的面向对象的方式实现状态模式,接着使用一种更 Rust 一点的方式。让我们使用状态模式增量式地实现一个发布博文的工作流以探索这个概念。</p>
<p>这个博客的最终功能看起来像这样:</p>
<ol>
<li>博文从空白的草案开始。</li>
<li>一旦草案完成,请求审核博文。</li>
<li>一旦博文过审,它将被发表。</li>
<li>只有被发表的博文的内容会被打印,这样就不会意外打印出没有被审核的博文的文本。</li>
</ol>
<p>任何其他对博文的修改尝试都是没有作用的。例如,如果尝试在请求审核之前通过一个草案博文,博文应该保持未发布的状态。</p>
<p>示例 17-11 展示这个工作流的代码形式:这是一个我们将要在一个叫做 <code>blog</code> 的库 crate 中实现的 API 的示例。这段代码还不能编译,因为还未实现 <code>blog</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use blog::Post;
fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
assert_eq!("", post.content());
post.request_review();
assert_eq!("", post.content());
post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}</code></pre>
<p><span class="caption">示例 17-11: 展示了 <code>blog</code> crate 期望行为的代码</span></p>
<p>我们希望允许用户使用 <code>Post::new</code> 创建一个新的博文草案。也希望能在草案阶段为博文编写一些文本。如果在审批之前尝试立刻获取博文的内容,不应该获取到任何文本因为博文仍然是草案。一个好的单元测试将是断言草案博文的 <code>content</code> 方法返回空字符串,不过我们并不准备为这个例子编写单元测试。</p>
<p>接下来,我们希望能够请求审核博文,而在等待审核的阶段 <code>content</code> 应该仍然返回空字符串。最后当博文审核通过,它应该被发表,这意味着当调用 <code>content</code> 时博文的文本将被返回。</p>
<p>注意我们与 crate 交互的唯一的类型是 <code>Post</code>。这个类型会使用状态模式并会存放处于三种博文所可能的状态之一的值 —— 草案,等待审核和发布。状态上的改变由 <code>Post</code> 类型内部进行管理。状态依库用户对 <code>Post</code> 实例调用的方法而改变,但是不能直接管理状态变化。这也意味着用户不会在状态上犯错,比如在过审前发布博文。</p>
<h3 id="定义-post-并新建一个草案状态的实例"><a class="header" href="#定义-post-并新建一个草案状态的实例">定义 <code>Post</code> 并新建一个草案状态的实例</a></h3>
<p>让我们开始实现这个库吧!我们知道需要一个公有 <code>Post</code> 结构体来存放一些文本,所以让我们从结构体的定义和一个创建 <code>Post</code> 实例的公有关联函数 <code>new</code> 开始,如示例 17-12 所示。还需定义一个私有 trait <code>State</code></p>
<p><code>Post</code> 将在私有字段 <code>state</code> 中存放一个 <code>Option&lt;T&gt;</code> 类型的 trait 对象 <code>Box&lt;dyn State&gt;</code>。稍后将会看到为何 <code>Option&lt;T&gt;</code> 是必须的。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub struct Post {
state: Option&lt;Box&lt;dyn State&gt;&gt;,
content: String,
}
impl Post {
pub fn new() -&gt; Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
}
trait State {}
struct Draft {}
impl State for Draft {}</code></pre>
<p><span class="caption">示例 17-12: <code>Post</code> 结构体的定义和新建 <code>Post</code> 实例的 <code>new</code> 函数,<code>State</code> trait 和结构体 <code>Draft</code></span></p>
<p><code>State</code> trait 定义了所有不同状态的博文所共享的行为,这个状态对象是 <code>Draft</code><code>PendingReview</code><code>Published</code>,它们都会实现 <code>State</code> 状态。现在这个 trait 并没有任何方法,同时开始将只定义 <code>Draft</code> 状态因为这是我们希望博文的初始状态。</p>
<p>当创建新的 <code>Post</code> 时,我们将其 <code>state</code> 字段设置为一个存放了 <code>Box</code><code>Some</code> 值。这个 <code>Box</code> 指向一个 <code>Draft</code> 结构体新实例。这确保了无论何时新建一个 <code>Post</code> 实例,它都会从草案开始。因为 <code>Post</code><code>state</code> 字段是私有的,也就无法创建任何其他状态的 <code>Post</code> 了!。<code>Post::new</code> 函数中将 <code>content</code> 设置为新建的空 <code>String</code></p>
<h3 id="存放博文内容的文本"><a class="header" href="#存放博文内容的文本">存放博文内容的文本</a></h3>
<p>在示例 17-11 中,展示了我们希望能够调用一个叫做 <code>add_text</code> 的方法并向其传递一个 <code>&amp;str</code> 来将文本增加到博文的内容中。选择实现为一个方法而不是将 <code>content</code> 字段暴露为 <code>pub</code> 。这意味着之后可以实现一个方法来控制 <code>content</code> 字段如何被读取。<code>add_text</code> 方法是非常直观的,让我们在示例 17-13 的 <code>impl Post</code> 块中增加一个实现:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct Post {
</span><span class="boring"> state: Option&lt;Box&lt;dyn State&gt;&gt;,
</span><span class="boring"> content: String,
</span><span class="boring">}
</span><span class="boring">
</span>impl Post {
// --snip--
<span class="boring"> pub fn new() -&gt; Post {
</span><span class="boring"> Post {
</span><span class="boring"> state: Some(Box::new(Draft {})),
</span><span class="boring"> content: String::new(),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span> pub fn add_text(&amp;mut self, text: &amp;str) {
self.content.push_str(text);
}
}
<span class="boring">
</span><span class="boring">trait State {}
</span><span class="boring">
</span><span class="boring">struct Draft {}
</span><span class="boring">
</span><span class="boring">impl State for Draft {}</span></code></pre>
<p><span class="caption">示例 17-13: 实现方法 <code>add_text</code> 来向博文的 <code>content</code> 增加文本</span></p>
<p><code>add_text</code> 获取一个 <code>self</code> 的可变引用,因为需要改变调用 <code>add_text</code><code>Post</code> 实例。接着调用 <code>content</code> 中的 <code>String</code><code>push_str</code> 并传递 <code>text</code> 参数来保存到 <code>content</code> 中。这不是状态模式的一部分,因为它的行为并不依赖博文所处的状态。<code>add_text</code> 方法完全不与 <code>state</code> 状态交互,不过这是我们希望支持的行为的一部分。</p>
<h3 id="确保博文草案的内容是空的"><a class="header" href="#确保博文草案的内容是空的">确保博文草案的内容是空的</a></h3>
<p>即使调用 <code>add_text</code> 并向博文增加一些内容之后,我们仍然希望 <code>content</code> 方法返回一个空字符串 slice因为博文仍然处于草案状态如示例 17-11 的第 8 行所示。现在让我们使用能满足要求的最简单的方式来实现 <code>content</code> 方法:总是返回一个空字符串 slice。当实现了将博文状态改为发布的能力之后将改变这一做法。但是目前博文只能是草案状态这意味着其内容应该总是空的。示例 17-14 展示了这个占位符实现:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct Post {
</span><span class="boring"> state: Option&lt;Box&lt;dyn State&gt;&gt;,
</span><span class="boring"> content: String,
</span><span class="boring">}
</span><span class="boring">
</span>impl Post {
// --snip--
<span class="boring"> pub fn new() -&gt; Post {
</span><span class="boring"> Post {
</span><span class="boring"> state: Some(Box::new(Draft {})),
</span><span class="boring"> content: String::new(),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn add_text(&amp;mut self, text: &amp;str) {
</span><span class="boring"> self.content.push_str(text);
</span><span class="boring"> }
</span><span class="boring">
</span> pub fn content(&amp;self) -&gt; &amp;str {
""
}
}
<span class="boring">
</span><span class="boring">trait State {}
</span><span class="boring">
</span><span class="boring">struct Draft {}
</span><span class="boring">
</span><span class="boring">impl State for Draft {}</span></code></pre>
<p><span class="caption">列表 17-14: 增加一个 <code>Post</code><code>content</code> 方法的占位实现,它总是返回一个空字符串 slice</span></p>
<p>通过增加这个 <code>content</code> 方法,示例 17-11 中直到第 8 行的代码能如期运行。</p>
<h3 id="请求审核博文来改变其状态"><a class="header" href="#请求审核博文来改变其状态">请求审核博文来改变其状态</a></h3>
<p>接下来需要增加请求审核博文的功能,这应当将其状态由 <code>Draft</code> 改为 <code>PendingReview</code>。示例 17-15 展示了这个代码:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct Post {
</span><span class="boring"> state: Option&lt;Box&lt;dyn State&gt;&gt;,
</span><span class="boring"> content: String,
</span><span class="boring">}
</span><span class="boring">
</span>impl Post {
// --snip--
<span class="boring"> pub fn new() -&gt; Post {
</span><span class="boring"> Post {
</span><span class="boring"> state: Some(Box::new(Draft {})),
</span><span class="boring"> content: String::new(),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn add_text(&amp;mut self, text: &amp;str) {
</span><span class="boring"> self.content.push_str(text);
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn content(&amp;self) -&gt; &amp;str {
</span><span class="boring"> ""
</span><span class="boring"> }
</span><span class="boring">
</span> pub fn request_review(&amp;mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
}
trait State {
fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt;;
}
struct Draft {}
impl State for Draft {
fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
Box::new(PendingReview {})
}
}
struct PendingReview {}
impl State for PendingReview {
fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
self
}
}</code></pre>
<p><span class="caption">示例 17-15: 实现 <code>Post</code><code>State</code> trait 的 <code>request_review</code> 方法</span></p>
<p>这里为 <code>Post</code> 增加一个获取 <code>self</code> 可变引用的公有方法 <code>request_review</code>。接着在 <code>Post</code> 的当前状态下调用内部的 <code>request_review</code> 方法,并且第二个 <code>request_review</code> 方法会消费当前的状态并返回一个新状态。</p>
<p>这里给 <code>State</code> trait 增加了 <code>request_review</code> 方法;所有实现了这个 trait 的类型现在都需要实现 <code>request_review</code> 方法。注意不同于使用 <code>self</code><code>&amp;self</code> 或者 <code>&amp;mut self</code> 作为方法的第一个参数,这里使用了 <code>self: Box&lt;Self&gt;</code>。这个语法意味着该方法只可在持有这个类型的 <code>Box</code> 上被调用。这个语法获取了 <code>Box&lt;Self&gt;</code> 的所有权使老状态无效化,以便 <code>Post</code> 的状态值可转换为一个新状态。</p>
<p>为了消费老状态,<code>request_review</code> 方法需要获取状态值的所有权。这就是 <code>Post</code><code>state</code> 字段中 <code>Option</code> 的来历:调用 <code>take</code> 方法将 <code>state</code> 字段中的 <code>Some</code> 值取出并留下一个 <code>None</code>,因为 Rust 不允许结构体实例中存在值为空的字段。这使得我们将 <code>state</code> 的值移出 <code>Post</code> 而不是借用它。接着我们将博文的 <code>state</code> 值设置为这个操作的结果。</p>
<p>我们需要将 <code>state</code> 临时设置为 <code>None</code> 来获取 <code>state</code> 值,即老状态的所有权,而不是使用 <code>self.state = self.state.request_review();</code> 这样的代码直接更新状态值。这确保了当 <code>Post</code> 被转换为新状态后不能再使用老 <code>state</code> 值。</p>
<p><code>Draft</code><code>request_review</code> 方法需要返回一个新的,装箱的 <code>PendingReview</code> 结构体的实例,其用来代表博文处于等待审核状态。结构体 <code>PendingReview</code> 同样也实现了 <code>request_review</code> 方法,不过它不进行任何状态转换。相反它返回自身,因为当我们请求审核一个已经处于 <code>PendingReview</code> 状态的博文,它应该继续保持 <code>PendingReview</code> 状态。</p>
<p>现在我们能看出状态模式的优势了:无论 <code>state</code> 是何值,<code>Post</code><code>request_review</code> 方法都是一样的。每个状态只负责它自己的规则。</p>
<p>我们将继续保持 <code>Post</code><code>content</code> 方法实现不变,返回一个空字符串 slice。现在我们可以拥有 <code>PendingReview</code> 状态和 <code>Draft</code> 状态的 <code>Post</code> 了,不过我们希望在 <code>PendingReview</code> 状态下 <code>Post</code> 也有相同的行为。现在示例 17-11 中直到 10 行的代码是可以执行的!</p>
<h3 id="增加改变-content-行为的-approve-方法"><a class="header" href="#增加改变-content-行为的-approve-方法">增加改变 <code>content</code> 行为的 <code>approve</code> 方法</a></h3>
<p><code>approve</code> 方法将与 <code>request_review</code> 方法类似:它会将 <code>state</code> 设置为审核通过时应处于的状态,如示例 17-16 所示。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct Post {
</span><span class="boring"> state: Option&lt;Box&lt;dyn State&gt;&gt;,
</span><span class="boring"> content: String,
</span><span class="boring">}
</span><span class="boring">
</span>impl Post {
// --snip--
<span class="boring"> pub fn new() -&gt; Post {
</span><span class="boring"> Post {
</span><span class="boring"> state: Some(Box::new(Draft {})),
</span><span class="boring"> content: String::new(),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn add_text(&amp;mut self, text: &amp;str) {
</span><span class="boring"> self.content.push_str(text);
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn content(&amp;self) -&gt; &amp;str {
</span><span class="boring"> ""
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn request_review(&amp;mut self) {
</span><span class="boring"> if let Some(s) = self.state.take() {
</span><span class="boring"> self.state = Some(s.request_review())
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span> pub fn approve(&amp;mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve())
}
}
}
trait State {
fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt;;
fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt;;
}
struct Draft {}
impl State for Draft {
// --snip--
<span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> Box::new(PendingReview {})
</span><span class="boring"> }
</span><span class="boring">
</span> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
self
}
}
struct PendingReview {}
impl State for PendingReview {
// --snip--
<span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">
</span> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
Box::new(Published {})
}
}
struct Published {}
impl State for Published {
fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
self
}
fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
self
}
}</code></pre>
<p><span class="caption">示例 17-16: 为 <code>Post</code><code>State</code> trait 实现 <code>approve</code> 方法</span></p>
<p>这里为 <code>State</code> trait 增加了 <code>approve</code> 方法,并新增了一个实现了 <code>State</code> 的结构体,<code>Published</code> 状态。</p>
<p>类似于 <code>PendingReview</code><code>request_review</code> 的工作方式,如果对 <code>Draft</code> 调用 <code>approve</code> 方法,并没有任何效果,因为它会返回 <code>self</code>。当对 <code>PendingReview</code> 调用 <code>approve</code> 时,它返回一个新的、装箱的 <code>Published</code> 结构体的实例。<code>Published</code> 结构体实现了 <code>State</code> trait同时对于 <code>request_review</code><code>approve</code> 两方法来说,它返回自身,因为在这两种情况博文应该保持 <code>Published</code> 状态。</p>
<p>现在需要更新 <code>Post</code><code>content</code> 方法。我们希望 <code>content</code> 根据 <code>Post</code> 的当前状态返回值,所以需要 <code>Post</code> 代理一个定义于 <code>state</code> 上的 <code>content</code> 方法,如实例 17-17 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">pub struct Post {
</span><span class="boring"> state: Option&lt;Box&lt;dyn State&gt;&gt;,
</span><span class="boring"> content: String,
</span><span class="boring">}
</span><span class="boring">
</span>impl Post {
// --snip--
<span class="boring"> pub fn new() -&gt; Post {
</span><span class="boring"> Post {
</span><span class="boring"> state: Some(Box::new(Draft {})),
</span><span class="boring"> content: String::new(),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn add_text(&amp;mut self, text: &amp;str) {
</span><span class="boring"> self.content.push_str(text);
</span><span class="boring"> }
</span><span class="boring">
</span> pub fn content(&amp;self) -&gt; &amp;str {
self.state.as_ref().unwrap().content(self)
}
// --snip--
<span class="boring">
</span><span class="boring"> pub fn request_review(&amp;mut self) {
</span><span class="boring"> if let Some(s) = self.state.take() {
</span><span class="boring"> self.state = Some(s.request_review())
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn approve(&amp;mut self) {
</span><span class="boring"> if let Some(s) = self.state.take() {
</span><span class="boring"> self.state = Some(s.approve())
</span><span class="boring"> }
</span><span class="boring"> }
</span>}
<span class="boring">
</span><span class="boring">trait State {
</span><span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt;;
</span><span class="boring"> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt;;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Draft {}
</span><span class="boring">
</span><span class="boring">impl State for Draft {
</span><span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> Box::new(PendingReview {})
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct PendingReview {}
</span><span class="boring">
</span><span class="boring">impl State for PendingReview {
</span><span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> Box::new(Published {})
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Published {}
</span><span class="boring">
</span><span class="boring">impl State for Published {
</span><span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 17-17: 更新 <code>Post</code><code>content</code> 方法来委托调用 <code>State</code><code>content</code> 方法</span></p>
<p>因为目标是将所有像这样的规则保持在实现了 <code>State</code> 的结构体中,我们将调用 <code>state</code> 中的值的 <code>content</code> 方法并传递博文实例(也就是 <code>self</code>)作为参数。接着返回 <code>state</code> 值的 <code>content</code> 方法的返回值。</p>
<p>这里调用 <code>Option</code><code>as_ref</code> 方法是因为需要 <code>Option</code> 中值的引用而不是获取其所有权。因为 <code>state</code> 是一个 <code>Option&lt;Box&lt;dyn State&gt;&gt;</code>,调用 <code>as_ref</code> 会返回一个 <code>Option&lt;&amp;Box&lt;dyn State&gt;&gt;</code>。如果不调用 <code>as_ref</code>,将会得到一个错误,因为不能将 <code>state</code> 移动出借用的 <code>&amp;self</code> 函数参数。</p>
<p>接着调用 <code>unwrap</code> 方法,这里我们知道它永远也不会 panic因为 <code>Post</code> 的所有方法都确保在它们返回时 <code>state</code> 会有一个 <code>Some</code> 值。这就是一个第十二章 <a href="ch09-03-to-panic-or-not-to-panic.html#%E5%BD%93%E6%88%91%E4%BB%AC%E6%AF%94%E7%BC%96%E8%AF%91%E5%99%A8%E7%9F%A5%E9%81%93%E6%9B%B4%E5%A4%9A%E7%9A%84%E6%83%85%E5%86%B5">“当我们比编译器知道更多的情况”</a> 部分讨论过的我们知道 <code>None</code> 是不可能的而编译器却不能理解的情况。</p>
<p>接着我们就有了一个 <code>&amp;Box&lt;dyn State&gt;</code>,当调用其 <code>content</code>Deref 强制转换会作用于 <code>&amp;</code><code>Box</code> ,这样最终会调用实现了 <code>State</code> trait 的类型的 <code>content</code> 方法。这意味着需要为 <code>State</code> trait 定义增加 <code>content</code>,这也是放置根据所处状态返回什么内容的逻辑的地方,如示例 17-18 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct Post {
</span><span class="boring"> state: Option&lt;Box&lt;dyn State&gt;&gt;,
</span><span class="boring"> content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Post {
</span><span class="boring"> pub fn new() -&gt; Post {
</span><span class="boring"> Post {
</span><span class="boring"> state: Some(Box::new(Draft {})),
</span><span class="boring"> content: String::new(),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn add_text(&amp;mut self, text: &amp;str) {
</span><span class="boring"> self.content.push_str(text);
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn content(&amp;self) -&gt; &amp;str {
</span><span class="boring"> self.state.as_ref().unwrap().content(self)
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn request_review(&amp;mut self) {
</span><span class="boring"> if let Some(s) = self.state.take() {
</span><span class="boring"> self.state = Some(s.request_review())
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn approve(&amp;mut self) {
</span><span class="boring"> if let Some(s) = self.state.take() {
</span><span class="boring"> self.state = Some(s.approve())
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>trait State {
// --snip--
<span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt;;
</span><span class="boring"> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt;;
</span><span class="boring">
</span> fn content&lt;'a&gt;(&amp;self, post: &amp;'a Post) -&gt; &amp;'a str {
""
}
}
// --snip--
<span class="boring">
</span><span class="boring">struct Draft {}
</span><span class="boring">
</span><span class="boring">impl State for Draft {
</span><span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> Box::new(PendingReview {})
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct PendingReview {}
</span><span class="boring">
</span><span class="boring">impl State for PendingReview {
</span><span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> Box::new(Published {})
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>struct Published {}
impl State for Published {
// --snip--
<span class="boring"> fn request_review(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> fn approve(self: Box&lt;Self&gt;) -&gt; Box&lt;dyn State&gt; {
</span><span class="boring"> self
</span><span class="boring"> }
</span><span class="boring">
</span> fn content&lt;'a&gt;(&amp;self, post: &amp;'a Post) -&gt; &amp;'a str {
&amp;post.content
}
}</code></pre>
<p><span class="caption">示例 17-18: 为 <code>State</code> trait 增加 <code>content</code> 方法</span></p>
<p>这里增加了一个 <code>content</code> 方法的默认实现来返回一个空字符串 slice。这意味着无需为 <code>Draft</code><code>PendingReview</code> 结构体实现 <code>content</code> 了。<code>Published</code> 结构体会覆盖 <code>content</code> 方法并会返回 <code>post.content</code> 的值。</p>
<p>注意这个方法需要生命周期注解,如第十章所讨论的。这里获取 <code>post</code> 的引用作为参数,并返回 <code>post</code> 一部分的引用,所以返回的引用的生命周期与 <code>post</code> 参数相关。</p>
<p>现在示例完成了 —— 现在示例 17-11 中所有的代码都能工作!我们通过发布博文工作流的规则实现了状态模式。围绕这些规则的逻辑都存在于状态对象中而不是分散在 <code>Post</code> 之中。</p>
<blockquote>
<h4 id="为什么不用枚举"><a class="header" href="#为什么不用枚举">为什么不用枚举?</a></h4>
<p>你可能会好奇为什么不用包含不同可能的博文状态的 <code>enum</code> 作为变量。这确实是一个可能的方案,尝试实现并对比最终结果来看看哪一种更适合你!使用枚举的一个缺点是每一个检查枚举值的地方都需要一个 <code>match</code> 表达式或类似的代码来处理所有可能的成员。这相比 trait 对象模式可能显得更重复。</p>
</blockquote>
<h3 id="状态模式的权衡取舍"><a class="header" href="#状态模式的权衡取舍">状态模式的权衡取舍</a></h3>
<p>我们展示了 Rust 是能够实现面向对象的状态模式的,以便能根据博文所处的状态来封装不同类型的行为。<code>Post</code> 的方法并不知道这些不同类型的行为。通过这种组织代码的方式,要找到所有已发布博文的不同行为只需查看一处代码:<code>Published</code><code>State</code> trait 的实现。</p>
<p>如果要创建一个不使用状态模式的替代实现,则可能会在 <code>Post</code> 的方法中,或者甚至于在 <code>main</code> 代码中用到 <code>match</code> 语句,来检查博文状态并在这里改变其行为。这意味着需要查看很多位置来理解处于发布状态的博文的所有逻辑!这在增加更多状态时会变得更糟:每一个 <code>match</code> 语句都会需要另一个分支。</p>
<p>对于状态模式来说,<code>Post</code> 的方法和使用 <code>Post</code> 的位置无需 <code>match</code> 语句,同时增加新状态只涉及到增加一个新 <code>struct</code> 和为其实现 trait 的方法。</p>
<p>这个实现易于扩展增加更多功能。为了体会使用此模式维护代码的简洁性,请尝试如下一些建议:</p>
<ul>
<li>增加 <code>reject</code> 方法将博文的状态从 <code>PendingReview</code> 变回 <code>Draft</code></li>
<li>在将状态变为 <code>Published</code> 之前需要两次 <code>approve</code> 调用</li>
<li>只允许博文处于 <code>Draft</code> 状态时增加文本内容。提示:让状态对象负责内容可能发生什么改变,但不负责修改 <code>Post</code></li>
</ul>
<p>状态模式的一个缺点是因为状态实现了状态之间的转换,一些状态会相互联系。如果在 <code>PendingReview</code><code>Published</code> 之间增加另一个状态,比如 <code>Scheduled</code>,则不得不修改 <code>PendingReview</code> 中的代码来转移到 <code>Scheduled</code>。如果 <code>PendingReview</code> 无需因为新增的状态而改变就更好了,不过这意味着切换到另一种设计模式。</p>
<p>另一个缺点是我们会发现一些重复的逻辑。为了消除它们,可以尝试为 <code>State</code> trait 中返回 <code>self</code><code>request_review</code><code>approve</code> 方法增加默认实现,不过这会违反对象安全性,因为 trait 不知道 <code>self</code> 具体是什么。我们希望能够将 <code>State</code> 作为一个 trait 对象,所以需要其方法是对象安全的。</p>
<p>另一个重复是 <code>Post</code><code>request_review</code><code>approve</code> 这两个类似的实现。它们都委托调用了 <code>state</code> 字段中 <code>Option</code> 值的同一方法,并在结果中为 <code>state</code> 字段设置了新值。如果 <code>Post</code> 中的很多方法都遵循这个模式,我们可能会考虑定义一个宏来消除重复(查看第二十章的 <a href="ch20-06-macros.html#%E5%AE%8F">“宏”</a> 部分)。</p>
<p>完全按照面向对象语言的定义实现这个模式并没有尽可能地利用 Rust 的优势。让我们看看一些代码中可以做出的修改,来将无效的状态和状态转移变为编译时错误。</p>
<h4 id="将状态和行为编码为类型"><a class="header" href="#将状态和行为编码为类型">将状态和行为编码为类型</a></h4>
<p>我们将展示如何稍微反思状态模式来进行一系列不同的权衡取舍。不同于完全封装状态和状态转移使得外部代码对其毫不知情我们将状态编码进不同的类型。如此Rust 的类型检查就会将任何在只能使用发布博文的地方使用草案博文的尝试变为编译时错误。</p>
<p>让我们考虑一下示例 17-11 中 <code>main</code> 的第一部分:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use blog::Post;
</span><span class="boring">
</span>fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
assert_eq!("", post.content());
<span class="boring">
</span><span class="boring"> post.request_review();
</span><span class="boring"> assert_eq!("", post.content());
</span><span class="boring">
</span><span class="boring"> post.approve();
</span><span class="boring"> assert_eq!("I ate a salad for lunch today", post.content());
</span>}</code></pre>
<p>我们仍然希望能够使用 <code>Post::new</code> 创建一个新的草案博文,并能够增加博文的内容。不过不同于存在一个草案博文时返回空字符串的 <code>content</code> 方法,我们将使草案博文完全没有 <code>content</code> 方法。这样如果尝试获取草案博文的内容,将会得到一个方法不存在的编译错误。这使得我们不可能在生产环境意外显示出草案博文的内容,因为这样的代码甚至就不能编译。示例 17-19 展示了 <code>Post</code> 结构体、<code>DraftPost</code> 结构体以及各自的方法的定义:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub struct Post {
content: String,
}
pub struct DraftPost {
content: String,
}
impl Post {
pub fn new() -&gt; DraftPost {
DraftPost {
content: String::new(),
}
}
pub fn content(&amp;self) -&gt; &amp;str {
&amp;self.content
}
}
impl DraftPost {
pub fn add_text(&amp;mut self, text: &amp;str) {
self.content.push_str(text);
}
}</code></pre>
<p><span class="caption">示例 17-19: 带有 <code>content</code> 方法的 <code>Post</code> 和没有 <code>content</code> 方法的 <code>DraftPost</code></span></p>
<p><code>Post</code><code>DraftPost</code> 结构体都有一个私有的 <code>content</code> 字段来储存博文的文本。这些结构体不再有 <code>state</code> 字段因为我们将状态编码改为结构体类型。<code>Post</code> 将代表发布的博文,它有一个返回 <code>content</code><code>content</code> 方法。</p>
<p>仍然有一个 <code>Post::new</code> 函数,不过不同于返回 <code>Post</code> 实例,它返回 <code>DraftPost</code> 的实例。现在不可能创建一个 <code>Post</code> 实例,因为 <code>content</code> 是私有的同时没有任何函数返回 <code>Post</code></p>
<p><code>DraftPost</code> 上定义了一个 <code>add_text</code> 方法,这样就可以像之前那样向 <code>content</code> 增加文本,不过注意 <code>DraftPost</code> 并没有定义 <code>content</code> 方法!如此现在程序确保了所有博文都从草案开始,同时草案博文没有任何可供展示的内容。任何绕过这些限制的尝试都会产生编译错误。</p>
<h4 id="实现状态转移为不同类型的转换"><a class="header" href="#实现状态转移为不同类型的转换">实现状态转移为不同类型的转换</a></h4>
<p>那么如何得到发布的博文呢?我们希望强制执行的规则是草案博文在可以发布之前必须被审核通过。等待审核状态的博文应该仍然不会显示任何内容。让我们通过增加另一个结构体 <code>PendingReviewPost</code> 来实现这个限制,在 <code>DraftPost</code> 上定义 <code>request_review</code> 方法来返回 <code>PendingReviewPost</code>,并在 <code>PendingReviewPost</code> 上定义 <code>approve</code> 方法来返回 <code>Post</code>,如示例 17-20 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct Post {
</span><span class="boring"> content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">pub struct DraftPost {
</span><span class="boring"> content: String,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Post {
</span><span class="boring"> pub fn new() -&gt; DraftPost {
</span><span class="boring"> DraftPost {
</span><span class="boring"> content: String::new(),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn content(&amp;self) -&gt; &amp;str {
</span><span class="boring"> &amp;self.content
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>impl DraftPost {
// --snip--
<span class="boring"> pub fn add_text(&amp;mut self, text: &amp;str) {
</span><span class="boring"> self.content.push_str(text);
</span><span class="boring"> }
</span><span class="boring">
</span> pub fn request_review(self) -&gt; PendingReviewPost {
PendingReviewPost {
content: self.content,
}
}
}
pub struct PendingReviewPost {
content: String,
}
impl PendingReviewPost {
pub fn approve(self) -&gt; Post {
Post {
content: self.content,
}
}
}</code></pre>
<p><span class="caption">列表 17-20: <code>PendingReviewPost</code> 通过调用 <code>DraftPost</code><code>request_review</code> 创建,<code>approve</code> 方法将 <code>PendingReviewPost</code> 变为发布的 <code>Post</code></span></p>
<p><code>request_review</code><code>approve</code> 方法获取 <code>self</code> 的所有权,因此会消费 <code>DraftPost</code><code>PendingReviewPost</code> 实例,并分别转换为 <code>PendingReviewPost</code> 和发布的 <code>Post</code>。这样在调用 <code>request_review</code> 之后就不会遗留任何 <code>DraftPost</code> 实例,后者同理。<code>PendingReviewPost</code> 并没有定义 <code>content</code> 方法,所以尝试读取其内容会导致编译错误,<code>DraftPost</code> 同理。因为唯一得到定义了 <code>content</code> 方法的 <code>Post</code> 实例的途径是调用 <code>PendingReviewPost</code><code>approve</code> 方法,而得到 <code>PendingReviewPost</code> 的唯一办法是调用 <code>DraftPost</code><code>request_review</code> 方法,现在我们就将发博文的工作流编码进了类型系统。</p>
<p>这也意味着不得不对 <code>main</code> 做出一些小的修改。因为 <code>request_review</code><code>approve</code> 返回新实例而不是修改被调用的结构体,所以我们需要增加更多的 <code>let post = </code> 覆盖赋值来保存返回的实例。也不再能断言草案和等待审核的博文的内容为空字符串了,我们也不再需要它们:不能编译尝试使用这些状态下博文内容的代码。更新后的 <code>main</code> 的代码如示例 17-21 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use blog::Post;
fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
let post = post.request_review();
let post = post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}</code></pre>
<p><span class="caption">示例 17-21: <code>main</code> 中使用新的博文工作流实现的修改</span></p>
<p>不得不修改 <code>main</code> 来重新赋值 <code>post</code> 使得这个实现不再完全遵守面向对象的状态模式:状态间的转换不再完全封装在 <code>Post</code> 实现中。然而,得益于类型系统和编译时类型检查,我们得到了的是无效状态是不可能的!这确保了某些特定的 bug比如显示未发布博文的内容将在部署到生产环境之前被发现。</p>
<p>尝试为示例 17-21 之后的 <code>blog</code> crate 实现这一部分开始所建议的任务来体会使用这个版本的代码是何感觉。注意在这个设计中一些需求可能已经完成了。</p>
<p>即便 Rust 能够实现面向对象设计模式,也有其他像将状态编码进类型这样的模式存在。这些模式有着不同的权衡取舍。虽然你可能非常熟悉面向对象模式,重新思考这些问题来利用 Rust 提供的像在编译时避免一些 bug 这样有益功能。在 Rust 中面向对象模式并不总是最好的解决方案,因为 Rust 拥有像所有权这样的面向对象语言所没有的功能。</p>
<h2 id="总结-16"><a class="header" href="#总结-16">总结</a></h2>
<p>阅读本章后,不管你是否认为 Rust 是一个面向对象语言,现在你都见识了 trait 对象是一个 Rust 中获取部分面向对象功能的方法。动态分发可以通过牺牲少量运行时性能来为你的代码提供一些灵活性。这些灵活性可以用来实现有助于代码可维护性的面向对象模式。Rust 也有像所有权这样不同于面向对象语言的功能。面向对象模式并不总是利用 Rust 优势的最好方式,但也是可用的选项。</p>
<p>接下来,让我们看看另一个提供了多样灵活性的 Rust 功能:模式。贯穿全书的模式,我们已经和它们打过照面了,但并没有见识过它们的全部本领。让我们开始探索吧!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="模式与模式匹配"><a class="header" href="#模式与模式匹配">模式与模式匹配</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch19-00-patterns.md">ch19-00-patterns.md</a>
<br>
commit 6fce661a0938aa0da06526e7b8f98fd7e67a222f</p>
</blockquote>
<p><strong>模式</strong><em>Patterns</em>)是 Rust 中特殊的语法,它用来匹配类型中的结构,无论类型是简单还是复杂。结合使用模式和 <code>match</code> 表达式以及其他结构可以提供更多对程序控制流的支配权。模式由如下一些内容组合而成:</p>
<ul>
<li>字面值</li>
<li>解构的数组、枚举、结构体或者元组</li>
<li>变量</li>
<li>通配符</li>
<li>占位符</li>
</ul>
<p>一些模式的例子包括<code>x</code>, <code>(a, 3)</code><code>Some(Color::Red)</code>。在模式为有效的上下文中,这些部分描述了数据的形状。接着可以用其匹配值来决定程序是否拥有正确的数据来运行特定部分的代码。</p>
<p>我们通过将一些值与模式相比较来使用它。如果模式匹配这些值,我们对值部分进行相应处理。回忆一下第六章讨论 <code>match</code> 表达式时像硬币分类器那样使用模式。如果数据符合这个形状,就可以使用这些命名的片段。如果不符合,与该模式相关的代码则不会运行。</p>
<p>本章是所有模式相关内容的参考。我们将涉及到使用模式的有效位置,<em>refutable</em><em>irrefutable</em> 模式的区别,和你可能会见到的不同类型的模式语法。在最后,你将会看到如何使用模式创建强大而简洁的代码。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="所有可能会用到模式的位置"><a class="header" href="#所有可能会用到模式的位置">所有可能会用到模式的位置</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch19-01-all-the-places-for-patterns.md">ch19-01-all-the-places-for-patterns.md</a>
<br>
commit 0c2d41e2afce734825c3a12087d423e8c2f0ae53</p>
</blockquote>
<p>模式出现在 Rust 的很多地方。你已经在不经意间使用了很多模式!本部分是一个所有有效模式位置的参考。</p>
<h3 id="match-分支"><a class="header" href="#match-分支"><code>match</code> 分支</a></h3>
<p>如第六章所讨论的,一个模式常用的位置是 <code>match</code> 表达式的分支。在形式上 <code>match</code> 表达式由 <code>match</code> 关键字、用于匹配的值和一个或多个分支构成,这些分支包含一个模式和在值匹配分支的模式时运行的表达式:</p>
<pre><code class="language-text">match VALUE {
PATTERN =&gt; EXPRESSION,
PATTERN =&gt; EXPRESSION,
PATTERN =&gt; EXPRESSION,
}
</code></pre>
<p>例如这是一个来自示例 6-5 中匹配变量 <code>x</code><code>Option&lt;i32&gt;</code> 值的 <code>match</code> 表达式:</p>
<pre><code class="language-rust ignore">match x {
None =&gt; None,
Some(i) =&gt; Some(i + 1),
}</code></pre>
<p>这个 <code>match</code> 表达式中的模式为每个箭头左边的 <code>None</code><code>Some(i)</code></p>
<p><code>match</code> 表达式必须是 <strong>穷尽</strong><em>exhaustive</em>)的,意为 <code>match</code> 表达式所有可能的值都必须被考虑到。一个确保覆盖每个可能值的方法是在最后一个分支使用捕获所有的模式:比如,一个匹配任何值的名称永远也不会失败,因此可以覆盖所有匹配剩下的情况。</p>
<p>有一个特定的模式 <code>_</code> 可以匹配所有情况,不过它从不绑定任何变量。这在例如希望忽略任何未指定值的情况很有用。本章之后的 <a href="ch19-03-pattern-syntax.html#%E5%BF%BD%E7%95%A5%E6%A8%A1%E5%BC%8F%E4%B8%AD%E7%9A%84%E5%80%BC">“忽略模式中的值”</a> 部分会详细介绍 <code>_</code> 模式的更多细节。</p>
<h3 id="if-let-条件表达式"><a class="header" href="#if-let-条件表达式"><code>if let</code> 条件表达式</a></h3>
<p>第六章讨论过了 <code>if let</code> 表达式,以及它是如何主要用于编写等同于只关心一个情况的 <code>match</code> 语句简写的。<code>if let</code> 可以对应一个可选的带有代码的 <code>else</code><code>if let</code> 中的模式不匹配时运行。</p>
<p>示例 18-1 展示了也可以组合并匹配 <code>if let</code><code>else if</code><code>else if let</code> 表达式。这相比 <code>match</code> 表达式一次只能将一个值与模式比较提供了更多灵活性。并且 Rust 并不要求一系列 <code>if let</code><code>else if</code><code>else if let</code> 分支的条件相互关联。</p>
<p>示例 18-1 中的代码展示了一系列针对不同条件的检查来决定背景颜色应该是什么。为了达到这个例子的目的,我们创建了硬编码值的变量,在真实程序中则可能由询问用户获得。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let favorite_color: Option&lt;&amp;str&gt; = None;
let is_tuesday = false;
let age: Result&lt;u8, _&gt; = "34".parse();
if let Some(color) = favorite_color {
println!("Using your favorite color, {color}, as the background");
} else if is_tuesday {
println!("Tuesday is green day!");
} else if let Ok(age) = age {
if age &gt; 30 {
println!("Using purple as the background color");
} else {
println!("Using orange as the background color");
}
} else {
println!("Using blue as the background color");
}
}</code></pre></pre>
<p><span class="caption">示例 18-1: 结合 <code>if let</code><code>else if</code><code>else if let</code> 以及 <code>else</code></span></p>
<p>如果用户指定了中意的颜色,将使用其作为背景颜色。如果没有指定中意的颜色且今天是星期二,背景颜色将是绿色。如果用户指定了他们的年龄字符串并能够成功将其解析为数字的话,我们将根据这个数字使用紫色或者橙色。最后,如果没有一个条件符合,背景颜色将是蓝色。</p>
<p>这个条件结构允许我们支持复杂的需求。使用这里硬编码的值,例子会打印出 <code>Using purple as the background color</code></p>
<p>注意 <code>if let</code> 也可以像 <code>match</code> 分支那样引入覆盖变量:<code>if let Ok(age) = age</code> 引入了一个新的覆盖变量 <code>age</code>,它包含 <code>Ok</code> 成员中的值。这意味着 <code>if age &gt; 30</code> 条件需要位于这个代码块内部;不能将两个条件组合为 <code>if let Ok(age) = age &amp;&amp; age &gt; 30</code>,因为我们希望与 30 进行比较的被覆盖的 <code>age</code> 直到大括号开始的新作用域才是有效的。</p>
<p><code>if let</code> 表达式的缺点在于其穷尽性没有为编译器所检查,而 <code>match</code> 表达式则检查了。如果去掉最后的 <code>else</code> 块而遗漏处理一些情况,编译器也不会警告这类可能的逻辑错误。</p>
<h3 id="while-let-条件循环"><a class="header" href="#while-let-条件循环"><code>while let</code> 条件循环</a></h3>
<p>一个与 <code>if let</code> 结构类似的是 <code>while let</code> 条件循环,它允许只要模式匹配就一直进行 <code>while</code> 循环。示例 18-2 展示了一个使用 <code>while let</code> 的例子,它使用 vector 作为栈并以先进后出的方式打印出 vector 中的值:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
for val in [1, 2, 3] {
tx.send(val).unwrap();
}
});
while let Ok(value) = rx.recv() {
println!("{value}");
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">列表 18-2: 使用 <code>while let</code> 循环只要 <code>stack.pop()</code> 返回 <code>Some</code> 就打印出其值</span></p>
<p>这个例子会打印出 3、2 接着是 1。<code>pop</code> 方法取出 vector 的最后一个元素并返回 <code>Some(value)</code>。如果 vector 是空的,它返回 <code>None</code><code>while</code> 循环只要 <code>pop</code> 返回 <code>Some</code> 就会一直运行其块中的代码。一旦其返回 <code>None</code><code>while</code> 循环停止。我们可以使用 <code>while let</code> 来弹出栈中的每一个元素。</p>
<h3 id="for-循环"><a class="header" href="#for-循环"><code>for</code> 循环</a></h3>
<p><code>for</code> 循环中,模式是 <code>for</code> 关键字直接跟随的值,正如 <code>for x in y</code> 中的 <code>x</code>。示例 18-3 中展示了如何使用 <code>for</code> 循环来解构,或拆开一个元组作为 <code>for</code> 循环的一部分:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let v = vec!['a', 'b', 'c'];
for (index, value) in v.iter().enumerate() {
println!("{value} is at index {index}");
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">列表 18-3: 在 <code>for</code> 循环中使用模式来解构元组</span></p>
<p>示例 18-3 的代码会打印出:</p>
<pre><code class="language-console">$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.52s
Running `target/debug/patterns`
a is at index 0
b is at index 1
c is at index 2
</code></pre>
<p>这里使用 <code>enumerate</code> 方法适配一个迭代器来产生一个值和其在迭代器中的索引,它们位于一个元组中。第一个产生的值是元组 <code>(0, 'a')</code>。当这个值匹配模式 <code>(index, value)</code><code>index</code> 将会是 0 而 <code>value</code> 将会是 <code>'a'</code>,并打印出第一行输出。</p>
<h3 id="let-语句"><a class="header" href="#let-语句"><code>let</code> 语句</a></h3>
<p>在本章之前,我们只明确的讨论过通过 <code>match</code><code>if let</code> 使用模式,不过事实上也在别的地方使用过模式,包括 <code>let</code> 语句。例如,考虑一下这个直白的 <code>let</code> 变量赋值:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let x = 5;
<span class="boring">}</span></code></pre></pre>
<p>不过你可能没有发觉,每一次像这样使用 <code>let</code> 语句就是在使用模式!<code>let</code> 语句更为正式的样子如下:</p>
<pre><code class="language-text">let PATTERN = EXPRESSION;
</code></pre>
<p><code>let x = 5;</code> 这样的语句中变量名位于 <code>PATTERN</code> 位置,变量名不过是形式特别朴素的模式。我们将表达式与模式比较,并为任何找到的名称赋值。所以例如 <code>let x = 5;</code> 的情况,<code>x</code> 是一个代表 “将匹配到的值绑定到变量 x” 的模式。同时因为名称 <code>x</code> 是整个模式,这个模式实际上等于 “将任何值绑定到变量 <code>x</code>,不管值是什么”。</p>
<p>为了更清楚的理解 <code>let</code> 的模式匹配方面的内容,考虑示例 18-4 中使用 <code>let</code> 和模式解构一个元组:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let (x, y, z) = (1, 2, 3);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-4: 使用模式解构元组并一次创建三个变量</span></p>
<p>这里将一个元组与模式匹配。Rust 会比较值 <code>(1, 2, 3)</code> 与模式 <code>(x, y, z)</code> 并发现此值匹配这个模式。在这个例子中,将会把 <code>1</code> 绑定到 <code>x</code><code>2</code> 绑定到 <code>y</code> 并将 <code>3</code> 绑定到 <code>z</code>。你可以将这个元组模式看作是将三个独立的变量模式结合在一起。</p>
<p>如果模式中元素的数量不匹配元组中元素的数量,则整个类型不匹配,并会得到一个编译时错误。例如,示例 18-5 展示了尝试用两个变量解构三个元素的元组,这是不行的:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let (x, y) = (1, 2, 3);
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 18-5: 一个错误的模式结构,其中变量的数量不符合元组中元素的数量</span></p>
<p>尝试编译这段代码会给出如下类型错误:</p>
<pre><code class="language-console">$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0308]: mismatched types
--&gt; src/main.rs:2:9
|
2 | let (x, y) = (1, 2, 3);
| ^^^^^^ --------- this expression has type `({integer}, {integer}, {integer})`
| |
| expected a tuple with 3 elements, found one with 2 elements
|
= note: expected tuple `({integer}, {integer}, {integer})`
found tuple `(_, _)`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `patterns` (bin "patterns") due to 1 previous error
</code></pre>
<p>为了修复这个错误,可以使用 <code>_</code><code>..</code> 来忽略元组中一个或多个值,如 <a href="ch19-03-pattern-syntax.html#%E5%BF%BD%E7%95%A5%E6%A8%A1%E5%BC%8F%E4%B8%AD%E7%9A%84%E5%80%BC">“忽略模式中的值”</a> 部分所示。如果问题是模式中有太多的变量,则解决方法是通过去掉变量使得变量数与元组中元素数相等。</p>
<h3 id="函数参数"><a class="header" href="#函数参数">函数参数</a></h3>
<p>函数参数也可以是模式。列表 18-6 中的代码声明了一个叫做 <code>foo</code> 的函数,它获取一个 <code>i32</code> 类型的参数 <code>x</code>,现在这看起来应该很熟悉:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn foo(x: i32) {
// code goes here
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">列表 18-6: 在参数中使用模式的函数签名</span></p>
<p><code>x</code> 部分就是一个模式!类似于之前对 <code>let</code> 所做的,可以在函数参数中匹配元组。列表 18-7 将传递给函数的元组拆分为值:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn print_coordinates(&amp;(x, y): &amp;(i32, i32)) {
println!("Current location: ({x}, {y})");
}
fn main() {
let point = (3, 5);
print_coordinates(&amp;point);
}</code></pre></pre>
<p><span class="caption">列表 18-7: 一个在参数中解构元组的函数</span></p>
<p>这会打印出 <code>Current location: (3, 5)</code>。值 <code>&amp;(3, 5)</code> 会匹配模式 <code>&amp;(x, y)</code>,如此 <code>x</code> 得到了值 <code>3</code>,而 <code>y</code>得到了值 <code>5</code></p>
<p>因为如第十三章所讲闭包类似于函数,也可以在闭包参数列表中使用模式。</p>
<p>现在我们见过了很多使用模式的方式了,不过模式在每个使用它的地方并不以相同的方式工作;在一些地方,模式必须是 <em>irrefutable</em> 的,意味着它们必须匹配所提供的任何值。在另一些情况,它们则可以是 refutable 的。接下来让我们讨论这两个概念。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="refutability可反驳性-模式是否会匹配失效"><a class="header" href="#refutability可反驳性-模式是否会匹配失效">Refutability可反驳性: 模式是否会匹配失效</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch19-02-refutability.md">ch19-02-refutability.md</a>
<br>
commit 0c2d41e2afce734825c3a12087d423e8c2f0ae53</p>
</blockquote>
<p>模式有两种形式refutable可反驳的和 irrefutable不可反驳的。能匹配任何传递的可能值的模式被称为是 <strong>不可反驳的</strong><em>irrefutable</em>)。一个例子就是 <code>let x = 5;</code> 语句中的 <code>x</code>,因为 <code>x</code> 可以匹配任何值所以不可能会失败。对某些可能的值进行匹配会失败的模式被称为是 <strong>可反驳的</strong><em>refutable</em>)。一个这样的例子便是 <code>if let Some(x) = a_value</code> 表达式中的 <code>Some(x)</code>;如果变量 <code>a_value</code> 中的值是 <code>None</code> 而不是 <code>Some</code>,那么 <code>Some(x)</code> 模式不能匹配。</p>
<p>函数参数、<code>let</code> 语句和 <code>for</code> 循环只能接受不可反驳的模式,因为当值不匹配时,程序无法进行有意义的操作。<code>if let</code><code>while let</code> 表达式可以接受可反驳和不可反驳的模式,但编译器会对不可反驳的模式发出警告,因为根据定义它们旨在处理可能的失败:条件表达式的功能在于它能够根据成功或失败来执行不同的操作。</p>
<p>通常我们无需担心可反驳和不可反驳模式的区别,不过确实需要熟悉可反驳性的概念,这样当在错误信息中看到时就知道如何应对。遇到这些情况,根据代码行为的意图,需要修改模式或者使用模式的结构。</p>
<p>让我们看看一个尝试在 Rust 要求不可反驳模式的地方使用可反驳模式以及相反情况的例子。在示例 18-8 中,有一个 <code>let</code> 语句,不过模式被指定为可反驳模式 <code>Some(x)</code>。如你所见,这不能编译:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span><span class="boring"> let some_option_value: Option&lt;i32&gt; = None;
</span> let Some(x) = some_option_value;
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 18-8: 尝试在 <code>let</code> 中使用可反驳模式</span></p>
<p>如果 <code>some_option_value</code> 的值是 <code>None</code>,其不会成功匹配模式 <code>Some(x)</code>,表明这个模式是可反驳的。然而,因为 <code>let</code> 对于 <code>None</code> 匹配不能产生任何合法的代码,所以 <code>let</code> 语句只能接受不可反驳模式。Rust 会在编译时抱怨我们尝试在要求不可反驳模式的地方使用可反驳模式:</p>
<pre><code class="language-console">$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0005]: refutable pattern in local binding
--&gt; src/main.rs:3:9
|
3 | let Some(x) = some_option_value;
| ^^^^^^^ pattern `None` not covered
|
= note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
= note: for more information, visit https://doc.rust-lang.org/book/ch19-02-refutability.html
= note: the matched value is of type `Option&lt;i32&gt;`
help: you might want to use `let else` to handle the variant that isn't matched
|
3 | let Some(x) = some_option_value else { todo!() };
| ++++++++++++++++
For more information about this error, try `rustc --explain E0005`.
error: could not compile `patterns` (bin "patterns") due to 1 previous error
</code></pre>
<p>因为我们没有覆盖(也不可能覆盖!)到模式 <code>Some(x)</code> 的每一个可能的值,所以 Rust 会合理地抗议。</p>
<p>为了修复在需要不可反驳模式的地方使用可反驳模式的情况,可以修改使用模式的代码:不同于使用 <code>let</code>,可以使用 <code>if let</code>。如此,如果模式不匹配,大括号中的代码将被忽略,其余代码保持有效。示例 18-9 展示了如何修复示例 18-8 中的代码。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> let some_option_value: Option&lt;i32&gt; = None;
</span> if let Some(x) = some_option_value {
println!("{x}");
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-9: 使用 <code>if let</code> 和一个带有可反驳模式的代码块来代替 <code>let</code></span></p>
<p>我们给了代码一个得以继续的出路!虽然我们没办法在避免产生错误的情况下使用不可反驳模式,但这段使用可反驳模式的代码是完全有效的。如果为 <code>if let</code> 提供了一个总是会匹配的模式,比如示例 18-10 中的 <code>x</code>,编译器会给出一个警告:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> if let x = 5 {
println!("{x}");
};
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-10: 尝试把不可反驳模式用到 <code>if let</code></span></p>
<p>Rust 会抱怨将不可反驳模式用于 <code>if let</code> 是没有意义的:</p>
<pre><code class="language-console">$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
warning: irrefutable `if let` pattern
--&gt; src/main.rs:2:8
|
2 | if let x = 5 {
| ^^^^^^^^^
|
= note: this pattern will always match, so the `if let` is useless
= help: consider replacing the `if let` with a `let`
= note: `#[warn(irrefutable_let_patterns)]` on by default
warning: `patterns` (bin "patterns") generated 1 warning
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.39s
Running `target/debug/patterns`
5
</code></pre>
<p>基于此,<code>match</code>匹配分支必须使用可反驳模式除了最后一个分支需要使用能匹配任何剩余值的不可反驳模式。Rust 允许我们在只有一个匹配分支的<code>match</code>中使用不可反驳模式,不过这么做不是特别有用,并可以被更简单的 <code>let</code> 语句替代。</p>
<p>目前我们已经讨论了所有可以使用模式的地方,以及可反驳模式与不可反驳模式的区别,下面让我们一起去把可以用来创建模式的语法过目一遍吧。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="所有的模式语法"><a class="header" href="#所有的模式语法">所有的模式语法</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch19-03-pattern-syntax.md">ch19-03-pattern-syntax.md</a>
<br>
commit 6fce661a0938aa0da06526e7b8f98fd7e67a222f</p>
</blockquote>
<p>在本节中,我们收集了模式中所有有效的语法,并讨论为什么以及何时你可能要使用这些语法。</p>
<h3 id="匹配字面值"><a class="header" href="#匹配字面值">匹配字面值</a></h3>
<p>如第六章所示,可以直接匹配字面值模式。如下代码给出了一些例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let x = 1;
match x {
1 =&gt; println!("one"),
2 =&gt; println!("two"),
3 =&gt; println!("three"),
_ =&gt; println!("anything"),
}
<span class="boring">}</span></code></pre></pre>
<p>这段代码会打印 <code>one</code> 因为 <code>x</code> 的值是 1。如果希望代码获得特定的具体值则该语法很有用。</p>
<h3 id="匹配命名变量"><a class="header" href="#匹配命名变量">匹配命名变量</a></h3>
<p>命名变量是匹配任何值的不可反驳模式,这在之前已经使用过数次。然而当其用于 <code>match</code> 表达式时情况会有些复杂。因为 <code>match</code> 会开始一个新作用域,<code>match</code> 表达式中作为模式的一部分声明的变量会覆盖 <code>match</code> 结构之外的同名变量,与所有变量一样。在示例 18-11 中,声明了一个值为 <code>Some(5)</code> 的变量 <code>x</code> 和一个值为 <code>10</code> 的变量 <code>y</code>。接着在值 <code>x</code> 上创建了一个 <code>match</code> 表达式。观察匹配分支中的模式和结尾的 <code>println!</code>,并在运行此代码或进一步阅读之前推断这段代码会打印什么。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let x = Some(5);
let y = 10;
match x {
Some(50) =&gt; println!("Got 50"),
Some(y) =&gt; println!("Matched, y = {y}"),
_ =&gt; println!("Default case, x = {x:?}"),
}
println!("at the end: x = {x:?}, y = {y}");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-11: 一个 <code>match</code> 语句其中一个分支引入了覆盖变量 <code>y</code></span></p>
<p>让我们看看当 <code>match</code> 语句运行的时候发生了什么。第一个匹配分支的模式并不匹配 <code>x</code> 中定义的值,所以代码继续执行。</p>
<p>第二个匹配分支中的模式引入了一个新变量 <code>y</code>,它会匹配任何 <code>Some</code> 中的值。因为我们在 <code>match</code> 表达式的新作用域中,这是一个新变量,而不是开头声明为值 10 的那个 <code>y</code>。这个新的 <code>y</code> 绑定会匹配任何 <code>Some</code> 中的值,在这里是 <code>x</code> 中的值。因此这个 <code>y</code> 绑定了 <code>x</code><code>Some</code> 内部的值。这个值是 5所以这个分支的表达式将会执行并打印出 <code>Matched, y = 5</code></p>
<p>如果 <code>x</code> 的值是 <code>None</code> 而不是 <code>Some(5)</code>,头两个分支的模式不会匹配,所以会匹配下划线。这个分支的模式中没有引入变量 <code>x</code>,所以此时表达式中的 <code>x</code> 会是外部没有被覆盖的 <code>x</code>。在这个假想的例子中,<code>match</code> 将会打印 <code>Default case, x = None</code></p>
<p>一旦 <code>match</code> 表达式执行完毕,其作用域也就结束了,同理内部 <code>y</code> 的作用域也结束了。最后的 <code>println!</code> 会打印 <code>at the end: x = Some(5), y = 10</code></p>
<p>为了创建能够比较外部 <code>x</code><code>y</code> 的值,而不引入覆盖变量的 <code>match</code> 表达式我们需要相应地使用带有条件的匹配守卫match guard。我们稍后将在 <a href="ch19-03-pattern-syntax.html#%E5%8C%B9%E9%85%8D%E5%AE%88%E5%8D%AB%E6%8F%90%E4%BE%9B%E7%9A%84%E9%A2%9D%E5%A4%96%E6%9D%A1%E4%BB%B6">“匹配守卫提供的额外条件”</a> 这一小节讨论匹配守卫。</p>
<h3 id="多个模式"><a class="header" href="#多个模式">多个模式</a></h3>
<p><code>match</code> 表达式中,可以使用 <code>|</code> 语法匹配多个模式,它代表 <strong></strong><em>or</em>)运算符模式。例如,如下代码将 <code>x</code> 的值与匹配分支相比较,第一个分支有 <strong></strong> 选项,意味着如果 <code>x</code> 的值匹配此分支的任一个值,它就会运行:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let x = 1;
match x {
1 | 2 =&gt; println!("one or two"),
3 =&gt; println!("three"),
_ =&gt; println!("anything"),
}
<span class="boring">}</span></code></pre></pre>
<p>上面的代码会打印 <code>one or two</code></p>
<h3 id="通过--匹配值的范围"><a class="header" href="#通过--匹配值的范围">通过 <code>..=</code> 匹配值的范围</a></h3>
<p><code>..=</code> 语法允许你匹配一个闭区间范围内的值。在如下代码中,当模式匹配任何在给定范围内的值时,该分支会执行:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let x = 5;
match x {
1..=5 =&gt; println!("one through five"),
_ =&gt; println!("something else"),
}
<span class="boring">}</span></code></pre></pre>
<p>如果 <code>x</code> 是 1、2、3、4 或 5第一个分支就会匹配。这个语法在匹配多个值时相比使用 <code>|</code> 运算符来表达相同的意思更为方便;如果使用 <code>|</code> 则不得不指定 <code>1 | 2 | 3 | 4 | 5</code>。相反指定范围就简短的多,特别是在希望匹配比如从 1 到 1000 的数字的时候!</p>
<p>编译器会在编译时检查范围不为空,而 <code>char</code> 和数字值是 Rust 仅有的可以判断范围是否为空的类型,所以范围只允许用于数字或 <code>char</code> 值。</p>
<p>如下是一个使用 <code>char</code> 类型值范围的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let x = 'c';
match x {
'a'..='j' =&gt; println!("early ASCII letter"),
'k'..='z' =&gt; println!("late ASCII letter"),
_ =&gt; println!("something else"),
}
<span class="boring">}</span></code></pre></pre>
<p>Rust 知道 <code>'c'</code> 位于第一个模式的范围内,并会打印出 <code>early ASCII letter</code></p>
<h3 id="解构并分解值"><a class="header" href="#解构并分解值">解构并分解值</a></h3>
<p>也可以使用模式来解构结构体、枚举和元组,以便使用这些值的不同部分。让我们来分别看一看。</p>
<h4 id="解构结构体"><a class="header" href="#解构结构体">解构结构体</a></h4>
<p>示例 18-12 展示带有两个字段 <code>x</code><code>y</code> 的结构体 <code>Point</code>,可以通过带有模式的 <code>let</code> 语句将其分解:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 0, y: 7 };
let Point { x: a, y: b } = p;
assert_eq!(0, a);
assert_eq!(7, b);
}</code></pre></pre>
<p><span class="caption">示例 18-12: 解构一个结构体的字段为单独的变量</span></p>
<p>这段代码创建了变量 <code>a</code><code>b</code> 来匹配结构体 <code>p</code> 中的 <code>x</code><code>y</code> 字段。这个例子展示了模式中的变量名不必与结构体中的字段名一致。不过通常希望变量名与字段名一致以便于理解变量来自于哪些字段。因为变量名匹配字段名是常见的,同时因为 <code>let Point { x: x, y: y } = p;</code> 包含了很多重复,所以对于匹配结构体字段的模式存在简写:只需列出结构体字段的名称,则模式创建的变量会有相同的名称。示例 18-13 展示了与示例 18-12 有着相同行为的代码,不过 <code>let</code> 模式创建的变量为 <code>x</code><code>y</code> 而不是 <code>a</code><code>b</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 0, y: 7 };
let Point { x, y } = p;
assert_eq!(0, x);
assert_eq!(7, y);
}</code></pre></pre>
<p><span class="caption">示例 18-13: 使用结构体字段简写来解构结构体字段</span></p>
<p>这段代码创建了变量 <code>x</code><code>y</code>,与变量 <code>p</code> 中的 <code>x</code><code>y</code> 相匹配。其结果是变量 <code>x</code><code>y</code> 包含结构体 <code>p</code> 中的值。</p>
<p>也可以使用字面值作为结构体模式的一部分进行解构,而不是为所有的字段创建变量。这允许我们测试一些字段为特定值的同时创建其他字段的变量。</p>
<p>示例 18-14 展示了一个 <code>match</code> 语句将 <code>Point</code> 值分成了三种情况:直接位于 <code>x</code> 轴上(此时 <code>y = 0</code> 为真)、位于 <code>y</code> 轴上(<code>x = 0</code>)或不在任何轴上的点。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">struct Point {
</span><span class="boring"> x: i32,
</span><span class="boring"> y: i32,
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let p = Point { x: 0, y: 7 };
match p {
Point { x, y: 0 } =&gt; println!("On the x axis at {x}"),
Point { x: 0, y } =&gt; println!("On the y axis at {y}"),
Point { x, y } =&gt; {
println!("On neither axis: ({x}, {y})");
}
}
}</code></pre></pre>
<p><span class="caption">示例 18-14: 解构和匹配模式中的字面值</span></p>
<p>第一个分支通过指定字段 <code>y</code> 匹配字面值 <code>0</code> 来匹配任何位于 <code>x</code> 轴上的点。此模式仍然创建了变量 <code>x</code> 以便在分支的代码中使用。</p>
<p>类似的,第二个分支通过指定字段 <code>x</code> 匹配字面值 <code>0</code> 来匹配任何位于 <code>y</code> 轴上的点,并为字段 <code>y</code> 创建了变量 <code>y</code>。第三个分支没有指定任何字面值,所以其会匹配任何其他的 <code>Point</code> 并为 <code>x</code><code>y</code> 两个字段创建变量。</p>
<p>在这个例子中,值 <code>p</code> 因为其 <code>x</code> 包含 0 而匹配第二个分支,因此会打印出 <code>On the y axis at 7</code></p>
<p>记住 <code>match</code> 表达式一旦找到一个匹配的模式就会停止检查其它分支,所以即使 <code>Point { x: 0, y: 0}</code><code>x</code> 轴上也在 <code>y</code> 轴上,这些代码也只会打印 <code>On the x axis at 0</code></p>
<h4 id="解构枚举"><a class="header" href="#解构枚举">解构枚举</a></h4>
<p>本书之前曾经解构过枚举(例如第六章示例 6-5不过当时没有明确提到解构枚举的模式需要对应枚举所定义的储存数据的方式。让我们以示例 6-2 中的 <code>Message</code> 枚举为例,编写一个 <code>match</code> 使用模式解构每一个内部值,如示例 18-15 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn main() {
let msg = Message::ChangeColor(0, 160, 255);
match msg {
Message::Quit =&gt; {
println!("The Quit variant has no data to destructure.");
}
Message::Move { x, y } =&gt; {
println!("Move in the x direction {x} and in the y direction {y}");
}
Message::Write(text) =&gt; {
println!("Text message: {text}");
}
Message::ChangeColor(r, g, b) =&gt; {
println!("Change the color to red {r}, green {g}, and blue {b}")
}
}
}</code></pre></pre>
<p><span class="caption">示例 18-15: 解构包含不同类型值成员的枚举</span></p>
<p>这段代码会打印出 <code>Change the color to red 0, green 160, and blue 255</code>。尝试改变 <code>msg</code> 的值来观察其他分支代码的运行。</p>
<p>对于像 <code>Message::Quit</code> 这样没有任何数据的枚举成员,不能进一步解构其值。只能匹配其字面值 <code>Message::Quit</code>,因此模式中没有任何变量。</p>
<p>对于像 <code>Message::Move</code> 这样的类结构体枚举成员,可以采用类似于匹配结构体的模式。在成员名称后,使用大括号并列出字段变量以便将其分解以供此分支的代码使用。这里使用了示例 18-13 所展示的简写。</p>
<p>对于像 <code>Message::Write</code> 这样的包含一个元素,以及像 <code>Message::ChangeColor</code> 这样包含三个元素的类元组枚举成员,其模式则类似于用于解构元组的模式。模式中变量的数量必须与成员中元素的数量一致。</p>
<h4 id="解构嵌套的结构体和枚举"><a class="header" href="#解构嵌套的结构体和枚举">解构嵌套的结构体和枚举</a></h4>
<p>目前为止,所有的例子都只匹配了深度为一级的结构体或枚举,不过当然也可以匹配嵌套的项!例如,我们可以重构列表 18-15 的代码在 <code>ChangeColor</code> 消息中同时支持 RGB 和 HSV 色彩模式,如示例 18-16 所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021">enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(Color),
}
fn main() {
let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));
match msg {
Message::ChangeColor(Color::Rgb(r, g, b)) =&gt; {
println!("Change color to red {r}, green {g}, and blue {b}");
}
Message::ChangeColor(Color::Hsv(h, s, v)) =&gt; {
println!("Change color to hue {h}, saturation {s}, value {v}")
}
_ =&gt; (),
}
}</code></pre></pre>
<p><span class="caption">示例 18-16: 匹配嵌套的枚举</span></p>
<p><code>match</code> 表达式第一个分支的模式匹配一个包含 <code>Color::Rgb</code> 枚举成员的 <code>Message::ChangeColor</code> 枚举成员,然后模式绑定了 3 个内部的 <code>i32</code> 值。第二个分支的模式也匹配一个 <code>Message::ChangeColor</code> 枚举成员,但是其内部的枚举会匹配 <code>Color::Hsv</code> 枚举成员。我们可以在一个 <code>match</code> 表达式中指定这些复杂条件,即使会涉及到两个枚举。</p>
<h4 id="解构结构体和元组"><a class="header" href="#解构结构体和元组">解构结构体和元组</a></h4>
<p>甚至可以用复杂的方式来混合、匹配和嵌套解构模式。如下是一个复杂结构体的例子,其中结构体和元组嵌套在元组中,并将所有的原始类型解构出来:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span><span class="boring"> struct Point {
</span><span class="boring"> x: i32,
</span><span class="boring"> y: i32,
</span><span class="boring"> }
</span><span class="boring">
</span> let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 });
<span class="boring">}</span></code></pre></pre>
<p>这将复杂的类型分解成部分组件以便可以单独使用我们感兴趣的值。</p>
<p>通过模式解构是一个方便利用部分值片段的手段,比如结构体中每个单独字段的值。</p>
<h3 id="忽略模式中的值"><a class="header" href="#忽略模式中的值">忽略模式中的值</a></h3>
<p>有时忽略模式中的一些值是有用的,比如 <code>match</code> 中最后捕获全部情况的分支实际上没有做任何事,但是它确实对所有剩余情况负责。有一些简单的方法可以忽略模式中全部或部分值:使用 <code>_</code> 模式(我们已经见过了),在另一个模式中使用 <code>_</code> 模式,使用一个以下划线开始的名称,或者使用 <code>..</code> 忽略所剩部分的值。让我们来分别探索如何以及为什么要这么做。</p>
<h4 id="使用-_-忽略整个值"><a class="header" href="#使用-_-忽略整个值">使用 <code>_</code> 忽略整个值</a></h4>
<p>我们已经使用过下划线作为匹配但不绑定任何值的通配符模式了。虽然这作为 <code>match</code> 表达式最后的分支特别有用,也可以将其用于任意模式,包括函数参数中,如示例 18-17 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn foo(_: i32, y: i32) {
println!("This code only uses the y parameter: {y}");
}
fn main() {
foo(3, 4);
}</code></pre></pre>
<p><span class="caption">示例 18-17: 在函数签名中使用 <code>_</code></span></p>
<p>这段代码会完全忽略作为第一个参数传递的值 <code>3</code>,并会打印出 <code>This code only uses the y parameter: 4</code></p>
<p>大部分情况当你不再需要特定函数参数时,最好修改签名不再包含无用的参数。在一些情况下忽略函数参数会变得特别有用,比如实现 trait 时,当你需要特定类型签名但是函数实现并不需要某个参数时。这样可以避免一个存在未使用的函数参数的编译警告,就跟使用命名参数一样。</p>
<h4 id="使用嵌套的-_-忽略部分值"><a class="header" href="#使用嵌套的-_-忽略部分值">使用嵌套的 <code>_</code> 忽略部分值</a></h4>
<p>也可以在一个模式内部使用<code>_</code> 忽略部分值,例如,当只需要测试部分值但在期望运行的代码中没有用到其他部分时。示例 18-18 展示了负责管理设置值的代码。业务需求是用户不允许覆盖现有的自定义设置,但是可以取消设置,也可以在当前未设置时为其提供设置。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut setting_value = Some(5);
let new_setting_value = Some(10);
match (setting_value, new_setting_value) {
(Some(_), Some(_)) =&gt; {
println!("Can't overwrite an existing customized value");
}
_ =&gt; {
setting_value = new_setting_value;
}
}
println!("setting is {setting_value:?}");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-18: 当不需要 <code>Some</code> 中的值时在模式内使用下划线来匹配 <code>Some</code> 成员</span></p>
<p>这段代码会打印出 <code>Can't overwrite an existing customized value</code> 接着是 <code>setting is Some(5)</code>。在第一个匹配分支,我们不需要匹配或使用任一个 <code>Some</code> 成员中的值;重要的部分是需要测试 <code>setting_value</code><code>new_setting_value</code> 都为 <code>Some</code> 成员的情况。在这种情况,我们打印出为何不改变 <code>setting_value</code>,并且不会改变它。</p>
<p>对于所有其他情况(<code>setting_value</code><code>new_setting_value</code> 任一为 <code>None</code>),这由第二个分支的 <code>_</code> 模式体现,这时确实希望允许 <code>new_setting_value</code> 变为 <code>setting_value</code></p>
<p>也可以在一个模式中的多处使用下划线来忽略特定值,如示例 18-19 所示,这里忽略了一个五元元组中的第二和第四个值:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, _, third, _, fifth) =&gt; {
println!("Some numbers: {first}, {third}, {fifth}")
}
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-19: 忽略元组的多个部分</span></p>
<p>这会打印出 <code>Some numbers: 2, 8, 32</code>,值 4 和 16 会被忽略。</p>
<h4 id="通过在名字前以一个-_-开头来忽略未使用的变量"><a class="header" href="#通过在名字前以一个-_-开头来忽略未使用的变量">通过在名字前以一个 <code>_</code> 开头来忽略未使用的变量</a></h4>
<p>如果你创建了一个变量却不在任何地方使用它Rust 通常会给你一个警告,因为未使用的变量可能会是个 bug。但是有时创建一个还未使用的变量是有用的比如你正在设计原型或刚刚开始一个项目。这时你希望告诉 Rust 不要警告未使用的变量,为此可以用下划线作为变量名的开头。示例 18-20 中创建了两个未使用变量,不过当编译代码时只会得到其中一个的警告:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let _x = 5;
let y = 10;
}</code></pre></pre>
<p><span class="caption">示例 18-20: 以下划线开始变量名以便去掉未使用变量警告</span></p>
<p>这里得到了警告说未使用变量 <code>y</code>,不过没有警告说使用 <code>_x</code></p>
<p>注意,只使用 <code>_</code> 和使用以下划线开头的名称有些微妙的不同:比如 <code>_x</code> 仍会将值绑定到变量,而 <code>_</code> 则完全不会绑定。为了展示这个区别的意义,示例 18-21 会产生一个错误。</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let s = Some(String::from("Hello!"));
if let Some(_s) = s {
println!("found a string");
}
println!("{s:?}");
<span class="boring">}</span></code></pre>
<p><span class="caption">示例 18-21: 以下划线开头的未使用变量仍然会绑定值,它可能会获取值的所有权</span></p>
<p>我们会得到一个错误,因为 <code>s</code> 的值仍然会移动进 <code>_s</code>,并阻止我们再次使用 <code>s</code>。然而只使用下划线本身,并不会绑定值。示例 18-22 能够无错编译,因为 <code>s</code> 没有被移动进 <code>_</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let s = Some(String::from("Hello!"));
if let Some(_) = s {
println!("found a string");
}
println!("{s:?}");
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-22: 单独使用下划线不会绑定值</span></p>
<p>上面的代码能很好的运行;因为没有把 <code>s</code> 绑定到任何变量;它没有被移动。</p>
<h4 id="用--忽略剩余值"><a class="header" href="#用--忽略剩余值"><code>..</code> 忽略剩余值</a></h4>
<p>对于有多个部分的值,可以使用 <code>..</code> 语法来只使用特定部分并忽略其它值,同时避免不得不每一个忽略值列出下划线。<code>..</code> 模式会忽略模式中剩余的任何没有显式匹配的值部分。在示例 18-23 中,有一个 <code>Point</code> 结构体存放了三维空间中的坐标。在 <code>match</code> 表达式中,我们希望只操作 <code>x</code> 坐标并忽略 <code>y</code><code>z</code> 字段的值:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> struct Point {
x: i32,
y: i32,
z: i32,
}
let origin = Point { x: 0, y: 0, z: 0 };
match origin {
Point { x, .. } =&gt; println!("x is {x}"),
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-23: 通过使用 <code>..</code> 来忽略 <code>Point</code> 中除 <code>x</code> 以外的字段</span></p>
<p>这里列出了 <code>x</code> 值,接着仅仅包含了 <code>..</code> 模式。这比不得不列出 <code>y: _</code><code>z: _</code> 要来得简单,特别是在处理有很多字段的结构体,但只涉及一到两个字段时的情形。</p>
<p><code>..</code> 会扩展为所需要的值的数量。示例 18-24 展示了元组中 <code>..</code> 的应用:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, .., last) =&gt; {
println!("Some numbers: {first}, {last}");
}
}
}</code></pre></pre>
<p><span class="caption">示例 18-24: 只匹配元组中的第一个和最后一个值并忽略掉所有其它值</span></p>
<p>这里用 <code>first</code><code>last</code> 来匹配第一个和最后一个值。<code>..</code> 将匹配并忽略中间的所有值。</p>
<p>然而使用 <code>..</code> 必须是无歧义的。如果期望匹配和忽略的值是不明确的Rust 会报错。示例 18-25 展示了一个带有歧义的 <code>..</code> 例子,因此其不能编译:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(.., second, ..) =&gt; {
println!("Some numbers: {second}")
},
}
}</code></pre>
<p><span class="caption">示例 18-25: 尝试以有歧义的方式运用 <code>..</code></span></p>
<p>如果编译上面的例子,会得到下面的错误:</p>
<pre><code class="language-console">$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error: `..` can only be used once per tuple pattern
--&gt; src/main.rs:5:22
|
5 | (.., second, ..) =&gt; {
| -- ^^ can only be used once per tuple pattern
| |
| previously used here
error: could not compile `patterns` (bin "patterns") due to 1 previous error
</code></pre>
<p>Rust 不可能决定在元组中匹配 <code>second</code> 值之前应该忽略多少个值,以及在之后忽略多少个值。这段代码可能表明我们意在忽略 <code>2</code>,绑定 <code>second</code><code>4</code>,接着忽略 <code>8</code><code>16</code><code>32</code>;抑或是意在忽略 <code>2</code><code>4</code>,绑定 <code>second</code><code>8</code>,接着忽略 <code>16</code><code>32</code>,以此类推。变量名 <code>second</code> 对于 Rust 来说并没有任何特殊意义,所以会得到编译错误,因为在这两个地方使用 <code>..</code> 是有歧义的。</p>
<h3 id="匹配守卫提供的额外条件"><a class="header" href="#匹配守卫提供的额外条件">匹配守卫提供的额外条件</a></h3>
<p><strong>匹配守卫</strong><em>match guard</em>)是一个指定于 <code>match</code> 分支模式之后的额外 <code>if</code> 条件,它也必须被满足才能选择此分支。匹配守卫用于表达比单独的模式所能允许的更为复杂的情况。</p>
<p>这个条件可以使用模式中创建的变量。示例 18-26 展示了一个 <code>match</code>,其中第一个分支有模式 <code>Some(x)</code> 还有匹配守卫 <code>if x % 2 == 0</code> (当 <code>x</code> 是偶数的时候为真)</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let num = Some(4);
match num {
Some(x) if x % 2 == 0 =&gt; println!("The number {x} is even"),
Some(x) =&gt; println!("The number {x} is odd"),
None =&gt; (),
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-26: 在模式中加入匹配守卫</span></p>
<p>上例会打印出 <code>The number 4 is even</code>。当 <code>num</code> 与模式中第一个分支比较时,因为 <code>Some(4)</code> 匹配 <code>Some(x)</code> 所以可以匹配。接着匹配守卫检查 <code>x</code> 除以 <code>2</code> 的余数是否等于 <code>0</code>,因为它等于 <code>0</code>,所以第一个分支被选择。</p>
<p>相反如果 <code>num</code><code>Some(5)</code>,因为 <code>5</code> 除以 <code>2</code> 的余数是 <code>1</code> 不等于 <code>0</code> 所以第一个分支的匹配守卫为假。接着 Rust 会前往第二个分支,这次匹配因为它没有匹配守卫所以会匹配任何 <code>Some</code> 成员。</p>
<p>无法在模式中表达类似 <code>if x % 2 == 0</code> 的条件,所以通过匹配守卫提供了表达类似逻辑的能力。这种替代表达方式的缺点是,编译器不会尝试为包含匹配守卫的模式检查穷尽性。</p>
<p>在示例 18-11 中,我们提到可以使用匹配守卫来解决模式中变量覆盖的问题,那里 <code>match</code> 表达式的模式中新建了一个变量而不是使用 <code>match</code> 之外的同名变量。新变量意味着不能够测试外部变量的值。示例 18-27 展示了如何使用匹配守卫修复这个问题。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = Some(5);
let y = 10;
match x {
Some(50) =&gt; println!("Got 50"),
Some(n) if n == y =&gt; println!("Matched, n = {n}"),
_ =&gt; println!("Default case, x = {x:?}"),
}
println!("at the end: x = {x:?}, y = {y}");
}</code></pre></pre>
<p><span class="caption">示例 18-27: 使用匹配守卫来测试与外部变量的相等性</span></p>
<p>现在这会打印出 <code>Default case, x = Some(5)</code>。现在第二个匹配分支中的模式不会引入一个覆盖外部 <code>y</code> 的新变量 <code>y</code>,这意味着可以在匹配守卫中使用外部的 <code>y</code>。相比指定会覆盖外部 <code>y</code> 的模式 <code>Some(y)</code>,这里指定为 <code>Some(n)</code>。此新建的变量 <code>n</code> 并没有覆盖任何值,因为 <code>match</code> 外部没有变量 <code>n</code></p>
<p>匹配守卫 <code>if n == y</code> 并不是一个模式所以没有引入新变量。这个 <code>y</code> <strong>正是</strong> 外部的 <code>y</code> 而不是新的覆盖变量 <code>y</code>,这样就可以通过比较 <code>n</code><code>y</code> 来表达寻找一个与外部 <code>y</code> 相同的值的概念了。</p>
<p>也可以在匹配守卫中使用 <strong></strong> 运算符 <code>|</code> 来指定多个模式,同时匹配守卫的条件会作用于所有的模式。示例 18-28 展示了结合匹配守卫与使用了 <code>|</code> 的模式的优先级。这个例子中重要的部分是匹配守卫 <code>if y</code> 作用于 <code>4</code><code>5</code> <strong></strong> <code>6</code>,即使这看起来好像 <code>if y</code> 只作用于 <code>6</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let x = 4;
let y = false;
match x {
4 | 5 | 6 if y =&gt; println!("yes"),
_ =&gt; println!("no"),
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-28: 结合多个模式与匹配守卫</span></p>
<p>这个匹配条件表明此分支值匹配 <code>x</code> 值为 <code>4</code><code>5</code><code>6</code> <strong>同时</strong> <code>y</code><code>true</code> 的情况。运行这段代码时会发生的是第一个分支的模式因 <code>x</code><code>4</code> 而匹配,不过匹配守卫 <code>if y</code> 为假,所以第一个分支不会被选择。代码移动到第二个分支,这会匹配,此程序会打印出 <code>no</code>。这是因为 <code>if</code> 条件作用于整个 <code>4 | 5 | 6</code> 模式,而不仅是最后的值 <code>6</code>。换句话说,匹配守卫与模式的优先级关系看起来像这样:</p>
<pre><code class="language-text">(4 | 5 | 6) if y =&gt; ...
</code></pre>
<p>而不是:</p>
<pre><code class="language-text">4 | 5 | (6 if y) =&gt; ...
</code></pre>
<p>可以通过运行代码时的情况看出这一点:如果匹配守卫只作用于由 <code>|</code> 运算符指定的值列表的最后一个值,这个分支就会匹配且程序会打印出 <code>yes</code></p>
<h3 id="-绑定"><a class="header" href="#-绑定"><code>@</code> 绑定</a></h3>
<p><em>at</em> 运算符(<code>@</code>)允许我们在创建一个存放值的变量的同时测试其值是否匹配模式。示例 18-29 展示了一个例子,这里我们希望测试 <code>Message::Hello</code><code>id</code> 字段是否位于 <code>3..=7</code> 范围内,同时也希望能将其值绑定到 <code>id_variable</code> 变量中以便此分支相关联的代码可以使用它。可以将 <code>id_variable</code> 命名为 <code>id</code>,与字段同名,不过出于示例的目的这里选择了不同的名称。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> enum Message {
Hello { id: i32 },
}
let msg = Message::Hello { id: 5 };
match msg {
Message::Hello {
id: id_variable @ 3..=7,
} =&gt; println!("Found an id in range: {id_variable}"),
Message::Hello { id: 10..=12 } =&gt; {
println!("Found an id in another range")
}
Message::Hello { id } =&gt; println!("Found some other id: {id}"),
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 18-29: 使用 <code>@</code> 在模式中绑定值的同时测试它</span></p>
<p>上例会打印出 <code>Found an id in range: 5</code>。通过在 <code>3..=7</code> 之前指定 <code>id_variable @</code>,我们捕获了任何匹配此范围的值并同时测试其值匹配这个范围模式。</p>
<p>第二个分支只在模式中指定了一个范围,分支相关代码没有一个包含 <code>id</code> 字段实际值的变量。<code>id</code> 字段的值可以是 10、11 或 12不过这个模式的代码并不知情也不能使用 <code>id</code> 字段中的值,因为没有将 <code>id</code> 值保存进一个变量。</p>
<p>最后一个分支指定了一个没有范围的变量,此时确实拥有可以用于分支代码的变量 <code>id</code>,因为这里使用了结构体字段简写语法。不过此分支中没有像头两个分支那样对 <code>id</code> 字段的值进行测试:任何值都会匹配此分支。</p>
<p>使用 <code>@</code> 可以在一个模式中同时测试和保存变量值。</p>
<h2 id="总结-17"><a class="header" href="#总结-17">总结</a></h2>
<p>模式是 Rust 中一个很有用的功能,它有助于我们区分不同类型的数据。当用于 <code>match</code> 语句时Rust 确保模式会包含每一个可能的值,否则程序将不能编译。<code>let</code> 语句和函数参数的模式使得这些结构更强大,可以在将值解构为更小部分的同时为变量赋值。可以创建简单或复杂的模式来满足我们的要求。</p>
<p>接下来,在本书倒数第二章中,我们将介绍一些 Rust 众多功能中较为高级的部分。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="高级特征"><a class="header" href="#高级特征">高级特征</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch20-00-advanced-features.md">ch20-00-advanced-features.md</a>
<br>
commit a8536189d5f1ba2f0b1187bfae787c0d89e2871c</p>
</blockquote>
<p>现在我们已经学习了 Rust 编程语言中最常用的部分。在第二十一章开始另一个新项目之前,让我们聊聊一些总有一天你会遇上的部分内容。你可以将本章作为不经意间遇到未知的内容时的参考。本章将要学习的功能在一些非常特定的场景下很有用处。虽然很少会碰到它们,我们希望确保你了解 Rust 提供的所有功能。</p>
<p>本章将涉及如下内容:</p>
<ul>
<li>不安全 Rust用于当需要舍弃 Rust 的某些保证并负责手动维持这些保证</li>
<li>高级 trait与 trait 相关的关联类型默认类型参数完全限定语法fully qualified syntaxtraitsupertraits和 newtype 模式</li>
<li>高级类型:关于 newtype 模式的更多内容类型别名never 类型和动态大小类型</li>
<li>高级函数和闭包:函数指针和返回闭包</li>
<li>宏:定义在编译时定义更多代码的方式</li>
</ul>
<p>对所有人而言,这都是一个介绍 Rust 迷人特性的宝典!让我们翻开它吧!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="不安全-rust"><a class="header" href="#不安全-rust">不安全 Rust</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch20-01-unsafe-rust.md">ch20-01-unsafe-rust.md</a>
<br>
commit 057b0d338229b87d06be772346ea0b643bdecdc5</p>
</blockquote>
<p>目前为止讨论过的代码都有 Rust 在编译时会强制执行的内存安全保证。然而Rust 还隐藏有第二种语言,它不会强制执行这类内存安全保证:这被称为 <strong>不安全 Rust</strong><em>unsafe Rust</em>)。它与常规 Rust 代码无异,但是会提供额外的超能力。</p>
<p>尽管代码可能没问题,但如果 Rust 编译器没有足够的信息可以确定,它将拒绝代码。</p>
<p>不安全 Rust 之所以存在,是因为静态分析本质上是保守的。当编译器尝试确定一段代码是否支持某个保证时,拒绝一些合法的程序比接受无效的程序要好一些。这必然意味着有时代码 <strong>可能</strong> 是合法的,但如果 Rust 编译器没有足够的信息来确定,它将拒绝该代码。在这种情况下,可以使用不安全代码告诉编译器,“相信我,我知道我在干什么。” 不过千万注意,使用不安全 Rust 风险自担:如果不安全代码出错了,比如解引用空指针,可能会导致不安全的内存使用。</p>
<p>另一个 Rust 存在不安全一面的原因是:底层计算机硬件固有的不安全性。如果 Rust 不允许进行不安全操作那么有些任务则根本完成不了。Rust 需要能够进行像直接与操作系统交互,甚至于编写你自己的操作系统这样的底层系统编程!这也是 Rust 语言的目标之一。让我们看看不安全 Rust 能做什么,和怎么做。</p>
<h3 id="不安全的超能力"><a class="header" href="#不安全的超能力">不安全的超能力</a></h3>
<p>可以通过 <code>unsafe</code> 关键字来切换到不安全 Rust接着可以开启一个新的存放不安全代码的块。这里有五类可以在不安全 Rust 中进行而不能用于安全 Rust 的操作,它们称之为 “不安全的超能力。(<em>unsafe superpowers</em>)” 这些超能力是:</p>
<ul>
<li>解引用裸指针</li>
<li>调用不安全的函数或方法</li>
<li>访问或修改可变静态变量</li>
<li>实现不安全 trait</li>
<li>访问 <code>union</code> 的字段</li>
</ul>
<p>有一点很重要,<code>unsafe</code> 并不会关闭借用检查器或禁用任何其他 Rust 安全检查:如果在不安全代码中使用引用,它仍会被检查。<code>unsafe</code> 关键字只是提供了那五个不会被编译器检查内存安全的功能。你仍然能在不安全块中获得某种程度的安全。</p>
<p>再者,<code>unsafe</code> 不意味着块中的代码就一定是危险的或者必然导致内存安全问题:其意图在于作为程序员你将会确保 <code>unsafe</code> 块中的代码以有效的方式访问内存。</p>
<p>人是会犯错误的,错误总会发生,不过通过要求这五类操作必须位于标记为 <code>unsafe</code> 的块中,就能够知道任何与内存安全相关的错误必定位于 <code>unsafe</code> 块内。保持 <code>unsafe</code> 块尽可能小,如此当之后调查内存 bug 时就会感谢你自己了。</p>
<p>为了尽可能隔离不安全代码,将不安全代码封装进一个安全的抽象并提供安全 API 是一个好主意,当我们学习不安全函数和方法时会讨论到。标准库的一部分被实现为在被评审过的不安全代码之上的安全抽象。这个技术防止了 <code>unsafe</code> 泄露到所有你或者用户希望使用由 <code>unsafe</code> 代码实现的功能的地方,因为使用其安全抽象是安全的。</p>
<p>让我们按顺序依次介绍上述五个超能力,同时我们会看到一些提供不安全代码的安全接口的抽象。</p>
<h3 id="解引用裸指针"><a class="header" href="#解引用裸指针">解引用裸指针</a></h3>
<p>回到第四章的 <a href="ch04-02-references-and-borrowing.html#%E6%82%AC%E5%9E%82%E5%BC%95%E7%94%A8dangling-references">“悬垂引用”</a> 部分,那里提到了编译器会确保引用总是有效的。不安全 Rust 有两个被称为 <strong>裸指针</strong><em>raw pointers</em>)的类似于引用的新类型。和引用一样,裸指针是不可变或可变的,分别写作 <code>*const T</code><code>*mut T</code>。这里的星号不是解引用运算符;它是类型名称的一部分。在裸指针的上下文中,<strong>不可变</strong> 意味着指针解引用之后不能直接赋值。</p>
<p>裸指针与引用和智能指针的区别在于</p>
<ul>
<li>允许忽略借用规则,可以同时拥有不可变和可变的指针,或多个指向相同位置的可变指针</li>
<li>不保证指向有效的内存</li>
<li>允许为空</li>
<li>不能实现任何自动清理功能</li>
</ul>
<p>通过去掉 Rust 强加的保证,你可以放弃安全保证以换取性能或使用另一个语言或硬件接口的能力,此时 Rust 的保证并不适用。</p>
<p>示例 19-1 展示了如何从引用同时创建不可变和可变裸指针。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut num = 5;
let r1 = &amp;num as *const i32;
let r2 = &amp;mut num as *mut i32;
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 19-1: 通过引用创建裸指针</span></p>
<p>注意这里没有引入 <code>unsafe</code> 关键字。可以在安全代码中 <strong>创建</strong> 裸指针,只是不能在不安全块之外 <strong>解引用</strong> 裸指针,稍后便会看到。</p>
<p>这里使用 <code>as</code> 将不可变和可变引用强转为对应的裸指针类型。因为直接从保证安全的引用来创建它们,可以知道这些特定的裸指针是有效,但是不能对任何裸指针做出如此假设。</p>
<p>作为展示接下来会创建一个不能确定其有效性的裸指针,示例 19-2 展示了如何创建一个指向任意内存地址的裸指针。尝试使用任意内存是未定义行为此地址可能有数据也可能没有编译器可能会优化掉这个内存访问或者程序可能会出现段错误segmentation fault。通常没有好的理由编写这样的代码不过却是可行的</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let address = 0x012345usize;
let r = address as *const i32;
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 19-2: 创建指向任意内存地址的裸指针</span></p>
<p>记得我们说过可以在安全代码中创建裸指针,不过不能 <strong>解引用</strong> 裸指针和读取其指向的数据。现在我们要做的就是对裸指针使用解引用运算符 <code>*</code>,这需要一个 <code>unsafe</code> 块,如示例 19-3 所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut num = 5;
let r1 = &amp;num as *const i32;
let r2 = &amp;mut num as *mut i32;
unsafe {
println!("r1 is: {}", *r1);
println!("r2 is: {}", *r2);
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 19-3: 在 <code>unsafe</code> 块中解引用裸指针</span></p>
<p>创建一个指针不会造成任何危险;只有当访问其指向的值时才有可能遇到无效的值。</p>
<p>还需注意示例 19-1 和 19-3 中创建了同时指向相同内存位置 <code>num</code> 的裸指针 <code>*const i32</code><code>*mut i32</code>。相反如果尝试同时创建 <code>num</code> 的不可变和可变引用,将无法通过编译,因为 Rust 的所有权规则不允许在拥有任何不可变引用的同时再创建一个可变引用。通过裸指针,就能够同时创建同一地址的可变指针和不可变指针,若通过可变指针修改数据,则可能潜在造成数据竞争。请多加小心!</p>
<p>既然存在这么多的危险,为何还要使用裸指针呢?一个主要的应用场景便是调用 C 代码接口,这在下一部分 <a href="ch20-01-unsafe-rust.html#%E8%B0%83%E7%94%A8%E4%B8%8D%E5%AE%89%E5%85%A8%E5%87%BD%E6%95%B0%E6%88%96%E6%96%B9%E6%B3%95">“调用不安全函数或方法”</a> 中会讲到。另一个场景是构建借用检查器无法理解的安全抽象。让我们先介绍不安全函数,接着看一看使用不安全代码的安全抽象的例子。</p>
<h3 id="调用不安全函数或方法"><a class="header" href="#调用不安全函数或方法">调用不安全函数或方法</a></h3>
<p>第二类可以在不安全块中进行的操作是调用不安全函数。不安全函数和方法与常规函数方法十分类似,除了其开头有一个额外的 <code>unsafe</code>。在此上下文中,关键字<code>unsafe</code>表示该函数具有调用时需要满足的要求,而 Rust 不会保证满足这些要求。通过在 <code>unsafe</code> 块中调用不安全函数,表明我们已经阅读过此函数的文档并对其是否满足函数自身的契约负责。</p>
<p>如下是一个没有做任何操作的不安全函数 <code>dangerous</code> 的例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> unsafe fn dangerous() {}
unsafe {
dangerous();
}
<span class="boring">}</span></code></pre></pre>
<p>必须在一个单独的 <code>unsafe</code> 块中调用 <code>dangerous</code> 函数。如果尝试不使用 <code>unsafe</code> 块调用 <code>dangerous</code>,则会得到一个错误:</p>
<pre><code class="language-console">$ cargo run
Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
error[E0133]: call to unsafe function `dangerous` is unsafe and requires unsafe function or block
--&gt; src/main.rs:4:5
|
4 | dangerous();
| ^^^^^^^^^^^ call to unsafe function
|
= note: consult the function's documentation for information on how to avoid undefined behavior
For more information about this error, try `rustc --explain E0133`.
error: could not compile `unsafe-example` (bin "unsafe-example") due to 1 previous error
</code></pre>
<p>通过 <code>unsafe</code> 块,我们向 Rust 保证了我们已经阅读过函数的文档,理解如何正确使用,并验证过其满足函数的契约。</p>
<p>不安全函数体也是有效的 <code>unsafe</code> 块,所以在不安全函数中进行另一个不安全操作时无需新增额外的 <code>unsafe</code> 块。</p>
<h4 id="创建不安全代码的安全抽象"><a class="header" href="#创建不安全代码的安全抽象">创建不安全代码的安全抽象</a></h4>
<p>仅仅因为函数包含不安全代码并不意味着整个函数都需要标记为不安全的。事实上,将不安全代码封装进安全函数是一个常见的抽象。作为一个例子,了解一下标准库中的函数 <code>split_at_mut</code>,它需要一些不安全代码,让我们探索如何可以实现它。这个安全函数定义于可变 slice 之上:它获取一个 slice 并从给定的索引参数开始将其分为两个 slice。<code>split_at_mut</code> 的用法如示例 19-4 所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let mut v = vec![1, 2, 3, 4, 5, 6];
let r = &amp;mut v[..];
let (a, b) = r.split_at_mut(3);
assert_eq!(a, &amp;mut [1, 2, 3]);
assert_eq!(b, &amp;mut [4, 5, 6]);
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 19-4: 使用安全的 <code>split_at_mut</code> 函数</span></p>
<p>这个函数无法只通过安全 Rust 实现。一个尝试可能看起来像示例 19-5它不能编译。出于简单考虑我们将 <code>split_at_mut</code> 实现为函数而不是方法,并只处理 <code>i32</code> 值而非泛型 <code>T</code> 的 slice。</p>
<pre><code class="language-rust ignore does_not_compile">fn split_at_mut(values: &amp;mut [i32], mid: usize) -&gt; (&amp;mut [i32], &amp;mut [i32]) {
let len = values.len();
assert!(mid &lt;= len);
(&amp;mut values[..mid], &amp;mut values[mid..])
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let mut vector = vec![1, 2, 3, 4, 5, 6];
</span><span class="boring"> let (left, right) = split_at_mut(&amp;mut vector, 3);
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 19-5: 尝试只使用安全 Rust 来实现 <code>split_at_mut</code></span></p>
<p>此函数首先获取 slice 的长度,然后通过检查参数是否小于或等于这个长度来断言参数所给定的索引位于 slice 当中。该断言意味着如果传入的索引比要分割的 slice 的索引更大,此函数在尝试使用这个索引前 panic。</p>
<p>之后我们在一个元组中返回两个可变的 slice一个从原始 slice 的开头直到 <code>mid</code> 索引,另一个从 <code>mid</code> 直到原 slice 的结尾。</p>
<p>如果尝试编译示例 19-5 的代码,会得到一个错误:</p>
<pre><code class="language-console">$ cargo run
Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
error[E0499]: cannot borrow `*values` as mutable more than once at a time
--&gt; src/main.rs:6:31
|
1 | fn split_at_mut(values: &amp;mut [i32], mid: usize) -&gt; (&amp;mut [i32], &amp;mut [i32]) {
| - let's call the lifetime of this reference `'1`
...
6 | (&amp;mut values[..mid], &amp;mut values[mid..])
| --------------------------^^^^^^--------
| | | |
| | | second mutable borrow occurs here
| | first mutable borrow occurs here
| returning this value requires that `*values` is borrowed for `'1`
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices
For more information about this error, try `rustc --explain E0499`.
error: could not compile `unsafe-example` (bin "unsafe-example") due to 1 previous error
</code></pre>
<p>Rust 的借用检查器不能理解我们要借用这个 slice 的两个不同部分:它只知道我们借用了同一个 slice 两次。本质上借用 slice 的不同部分是可以的,因为结果两个 slice 不会重叠,不过 Rust 还没有智能到能够理解这些。当我们知道某些事是可以的而 Rust 不知道的时候,就是触及不安全代码的时候了</p>
<p>示例 19-6 展示了如何使用 <code>unsafe</code> 块,裸指针和一些不安全函数调用来实现 <code>split_at_mut</code></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::slice;
fn split_at_mut(values: &amp;mut [i32], mid: usize) -&gt; (&amp;mut [i32], &amp;mut [i32]) {
let len = values.len();
let ptr = values.as_mut_ptr();
assert!(mid &lt;= len);
unsafe {
(
slice::from_raw_parts_mut(ptr, mid),
slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let mut vector = vec![1, 2, 3, 4, 5, 6];
</span><span class="boring"> let (left, right) = split_at_mut(&amp;mut vector, 3);
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 19-6: 在 <code>split_at_mut</code> 函数的实现中使用不安全代码</span></p>
<p>回忆第四章的 <a href="ch04-03-slices.html#slice-%E7%B1%BB%E5%9E%8B">“Slice 类型” </a> 部分slice 是一个指向一些数据的指针,并带有该 slice 的长度。可以使用 <code>len</code> 方法获取 slice 的长度,使用 <code>as_mut_ptr</code> 方法访问 slice 的裸指针。在这个例子中,因为有一个 <code>i32</code> 值的可变 slice<code>as_mut_ptr</code> 返回一个 <code>*mut i32</code> 类型的裸指针,储存在 <code>ptr</code> 变量中。</p>
<p>我们保持索引 <code>mid</code> 位于 slice 中的断言。接着是不安全代码:<code>slice::from_raw_parts_mut</code> 函数获取一个裸指针和一个长度来创建一个 slice。这里使用此函数从 <code>ptr</code> 中创建了一个有 <code>mid</code> 个项的 slice。之后在 <code>ptr</code> 上调用 <code>add</code> 方法并使用 <code>mid</code> 作为参数来获取一个从 <code>mid</code> 开始的裸指针,使用这个裸指针并以 <code>mid</code> 之后项的数量为长度创建一个 slice。</p>
<p><code>slice::from_raw_parts_mut</code> 函数是不安全的因为它获取一个裸指针,并必须确信这个指针是有效的。裸指针上的 <code>add</code> 方法也是不安全的,因为其必须确信此地址偏移量也是有效的指针。因此必须将 <code>slice::from_raw_parts_mut</code><code>add</code> 放入 <code>unsafe</code> 块中以便能调用它们。通过观察代码,和增加 <code>mid</code> 必然小于等于 <code>len</code> 的断言,我们可以说 <code>unsafe</code> 块中所有的裸指针将是有效的 slice 中数据的指针。这是一个可以接受的 <code>unsafe</code> 的恰当用法。</p>
<p>注意无需将 <code>split_at_mut</code> 函数的结果标记为 <code>unsafe</code>,并可以在安全 Rust 中调用此函数。我们创建了一个不安全代码的安全抽象,其代码以一种安全的方式使用了 <code>unsafe</code> 代码,因为其只从这个函数访问的数据中创建了有效的指针。</p>
<p>与此相对,示例 19-7 中的 <code>slice::from_raw_parts_mut</code> 在使用 slice 时很有可能会崩溃。这段代码获取任意内存地址并创建了一个长为一万的 slice</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> use std::slice;
let address = 0x01234usize;
let r = address as *mut i32;
let values: &amp;[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) };
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 19-7: 通过任意内存地址创建 slice</span></p>
<p>我们并不拥有这个任意地址的内存,也不能保证这段代码创建的 slice 包含有效的 <code>i32</code> 值。试图使用臆测为有效的 <code>values</code> 会导致未定义的行为。</p>
<h4 id="使用-extern-函数调用外部代码"><a class="header" href="#使用-extern-函数调用外部代码">使用 <code>extern</code> 函数调用外部代码</a></h4>
<p>有时你的 Rust 代码可能需要与其他语言编写的代码交互。为此 Rust 有一个关键字,<code>extern</code>,有助于创建和使用 <strong>外部函数接口</strong><em>Foreign Function Interface</em>FFI。外部函数接口是一个编程语言用以定义函数的方式其允许不同外部编程语言调用这些函数。</p>
<p>示例 19-8 展示了如何集成 C 标准库中的 <code>abs</code> 函数。<code>extern</code> 块中声明的函数在 Rust 代码中总是不安全的。因为其他语言不会强制执行 Rust 的规则且 Rust 无法检查它们,所以确保其安全是程序员的责任:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">extern "C" {
fn abs(input: i32) -&gt; i32;
}
fn main() {
unsafe {
println!("Absolute value of -3 according to C: {}", abs(-3));
}
}</code></pre></pre>
<p><span class="caption">示例 19-8: 声明并调用另一个语言中定义的 <code>extern</code> 函数</span></p>
<p><code>extern "C"</code> 块中,列出了我们希望能够调用的另一个语言中的外部函数的签名和名称。<code>"C"</code> 部分定义了外部函数所使用的 <strong>应用二进制接口</strong><em>application binary interface</em>ABI —— ABI 定义了如何在汇编语言层面调用此函数。<code>"C"</code> ABI 是最常见的,并遵循 C 编程语言的 ABI。</p>
<blockquote>
<h4 id="从其它语言调用-rust-函数"><a class="header" href="#从其它语言调用-rust-函数">从其它语言调用 Rust 函数</a></h4>
<p>也可以使用 <code>extern</code> 来创建一个允许其他语言调用 Rust 函数的接口。不同于创建整个 <code>extern</code> 块,就在 <code>fn</code> 关键字之前增加 <code>extern</code> 关键字并为相关函数指定所用到的 ABI。还需增加 <code>#[no_mangle]</code> 注解来告诉 Rust 编译器不要 mangle 此函数的名称。<em>Mangling</em> 发生于当编译器将我们指定的函数名修改为不同的名称时,这会增加用于其他编译过程的额外信息,不过会使其名称更难以阅读。每一个编程语言的编译器都会以稍微不同的方式 mangle 函数名,所以为了使 Rust 函数能在其他语言中指定,必须禁用 Rust 编译器的 name mangling。</p>
<p>在如下的例子中,一旦其编译为动态库并从 C 语言中链接,<code>call_from_c</code> 函数就能够在 C 代码中访问:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[no_mangle]
pub extern "C" fn call_from_c() {
println!("Just called a Rust function from C!");
}
<span class="boring">}</span></code></pre></pre>
<p><code>extern</code> 的使用无需 <code>unsafe</code></p>
</blockquote>
<h3 id="访问或修改可变静态变量"><a class="header" href="#访问或修改可变静态变量">访问或修改可变静态变量</a></h3>
<p>目前为止全书都尽量避免讨论 <strong>全局变量</strong><em>global variables</em>Rust 确实支持它们,不过这对于 Rust 的所有权规则来说是有问题的。如果有两个线程访问相同的可变全局变量,则可能会造成数据竞争。</p>
<p>全局变量在 Rust 中被称为 <strong>静态</strong><em>static</em>)变量。示例 19-9 展示了一个拥有字符串 slice 值的静态变量的声明和应用:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">static HELLO_WORLD: &amp;str = "Hello, world!";
fn main() {
println!("name is: {HELLO_WORLD}");
}</code></pre></pre>
<p><span class="caption">示例 19-9: 定义和使用一个不可变静态变量</span></p>
<p>静态(<code>static</code>)变量类似于第三章 <a href="ch03-01-variables-and-mutability.html#%E5%B8%B8%E9%87%8F">“变量和常量的区别”</a> 部分讨论的常量。通常静态变量的名称采用 <code>SCREAMING_SNAKE_CASE</code> 写法。静态变量只能储存拥有 <code>'static</code> 生命周期的引用,这意味着 Rust 编译器可以自己计算出其生命周期而无需显式标注。访问不可变静态变量是安全的。</p>
<p>常量与不可变静态变量的一个微妙的区别是静态变量中的值有一个固定的内存地址。使用这个值总是会访问相同的地址。另一方面,常量则允许在任何被用到的时候复制其数据。另一个区别在于静态变量可以是可变的。访问和修改可变静态变量都是 <strong>不安全</strong> 的。示例 19-10 展示了如何声明、访问和修改名为 <code>COUNTER</code> 的可变静态变量:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">static mut COUNTER: u32 = 0;
fn add_to_count(inc: u32) {
unsafe {
COUNTER += inc;
}
}
fn main() {
add_to_count(3);
unsafe {
println!("COUNTER: {COUNTER}");
}
}</code></pre></pre>
<p><span class="caption">示例 19-10: 读取或修改一个可变静态变量是不安全的</span></p>
<p>就像常规变量一样,我们使用 <code>mut</code> 关键来指定可变性。任何读写 <code>COUNTER</code> 的代码都必须位于 <code>unsafe</code> 块中。这段代码可以编译并如期打印出 <code>COUNTER: 3</code>,因为这是单线程的。拥有多个线程访问 <code>COUNTER</code> 则可能导致数据竞争。</p>
<p>拥有可以全局访问的可变数据,难以保证不存在数据竞争,这就是为何 Rust 认为可变静态变量是不安全的。任何可能的情况,请优先使用第十六章讨论的并发技术和线程安全智能指针,这样编译器就能检测不同线程间的数据访问是否是安全的。</p>
<h3 id="实现不安全-trait"><a class="header" href="#实现不安全-trait">实现不安全 trait</a></h3>
<p><code>unsafe</code> 的另一个操作用例是实现不安全 trait。当 trait 中至少有一个方法中包含编译器无法验证的不变式invariant时 trait 是不安全的。可以在 <code>trait</code> 之前增加 <code>unsafe</code> 关键字将 trait 声明为 <code>unsafe</code>,同时 trait 的实现也必须标记为 <code>unsafe</code>,如示例 19-11 所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021">unsafe trait Foo {
// methods go here
}
unsafe impl Foo for i32 {
// method implementations go here
}
fn main() {}</code></pre></pre>
<p><span class="caption">示例 19-11: 定义并实现不安全 trait</span></p>
<p>通过 <code>unsafe impl</code>,我们承诺将保证编译器所不能验证的不变量。</p>
<p>作为一个例子,回忆第十六章 <a href="ch16-04-extensible-concurrency-sync-and-send.html#%E4%BD%BF%E7%94%A8-sync-%E5%92%8C-send-trait-%E7%9A%84%E5%8F%AF%E6%89%A9%E5%B1%95%E5%B9%B6%E5%8F%91">“使用 <code>Sync</code><code>Send</code> trait 的可扩展并发”</a> 部分中的 <code>Sync</code><code>Send</code> 标记 trait编译器会自动为完全由 <code>Send</code><code>Sync</code> 类型组成的类型自动实现它们。如果实现了一个包含一些不是 <code>Send</code><code>Sync</code> 的类型,比如裸指针,并希望将此类型标记为 <code>Send</code><code>Sync</code>,则必须使用 <code>unsafe</code>。Rust 不能验证我们的类型保证可以安全的跨线程发送或在多线程间访问,所以需要我们自己进行检查并通过 <code>unsafe</code> 表明。</p>
<h3 id="访问联合体中的字段"><a class="header" href="#访问联合体中的字段">访问联合体中的字段</a></h3>
<p>仅适用于 <code>unsafe</code> 的最后一个操作是访问 <strong>联合体</strong> 中的字段,<code>union</code><code>struct</code> 类似,但是在一个实例中同时只能使用一个声明的字段。联合体主要用于和 C 代码中的联合体交互。访问联合体的字段是不安全的,因为 Rust 无法保证当前存储在联合体实例中数据的类型。可以查看 <a href="https://doc.rust-lang.org/reference/items/unions.html">参考 Rust 文档</a> 了解有关联合体的更多信息。</p>
<h3 id="何时使用不安全代码"><a class="header" href="#何时使用不安全代码">何时使用不安全代码</a></h3>
<p>使用 <code>unsafe</code> 来进行这五个操作(超能力)之一是没有问题的,甚至是不需要深思熟虑的,不过使得 <code>unsafe</code> 代码正确也实属不易,因为编译器不能帮助保证内存安全。当有理由使用 <code>unsafe</code> 代码时,是可以这么做的,通过使用显式的 <code>unsafe</code> 标注可以更容易地在错误发生时追踪问题的源头。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="高级-trait"><a class="header" href="#高级-trait">高级 trait</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch20-03-advanced-traits.md">ch20-03-advanced-traits.md</a>
<br>
commit 95e931170404cb98d476b19017cbbdbc00d0834d</p>
</blockquote>
<p>第十章 <a href="ch10-02-traits.html#trait%E5%AE%9A%E4%B9%89%E5%85%B1%E5%90%8C%E8%A1%8C%E4%B8%BA">“trait定义共同行为”</a> 部分,我们第一次涉及到了 trait不过我们并没有覆盖一些较为高级的细节。现在我们更加了解 Rust 了,可以深入理解其本质了。</p>
<h3 id="关联类型在-trait-定义中指定占位符类型"><a class="header" href="#关联类型在-trait-定义中指定占位符类型">关联类型在 trait 定义中指定占位符类型</a></h3>
<p><strong>关联类型</strong><em>associated types</em>)让我们可以在 trait 里面增加一个待定义的类型(类型占位符),将类型占位符与 trait 相关联,这样 trait 的方法签名中就可以使用这些占位符类型。trait 的实现者在实现这个 trait 的时候,会指定一个具体类型,来替换掉这个占位符。这样,我们可以在一个 trait 中通过占位符使用不同类型,在实现此 trait 时才需要指定这些类型具体是什么。</p>
<p>我们之前提到,本章所描述的大部分内容都较少使用。关联类型则比较适中;它们比本书其他的内容要少见,不过比本章中的很多内容要更常见。</p>
<p>一个带有关联类型的 trait 的例子是标准库提供的 <code>Iterator</code> trait。它有一个叫做 <code>Item</code> 的关联类型来替代遍历的值的类型。<code>Iterator</code> trait 的定义如示例 19-12 所示:</p>
<pre><code class="language-rust noplayground">pub trait Iterator {
type Item;
fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt;;
}</code></pre>
<p><span class="caption">示例 19-12: <code>Iterator</code> trait 的定义中带有关联类型 <code>Item</code></span></p>
<p><code>Item</code> 是一个占位符类型,同时 <code>next</code> 方法的定义表明它返回 <code>Option&lt;Self::Item&gt;</code> 类型的值。这个 trait 的实现者会指定 <code>Item</code> 的具体类型,无论实现者指定何种类型,<code>next</code> 方法都会返回一个包含了此具体类型值的 <code>Option</code></p>
<p>关联类型看起来有点像泛型:后者允许定义一个函数时,暂不指定其可以处理的类型。为了体现这两者的区别,请看下面的例子。
这个例子为 <code>Counter</code> 结构体实现了 <code>Iterator</code> trait其中指定 <code>Item</code> 的类型为 <code>u32</code></p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">struct Counter {
</span><span class="boring"> count: u32,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Counter {
</span><span class="boring"> fn new() -&gt; Counter {
</span><span class="boring"> Counter { count: 0 }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>impl Iterator for Counter {
type Item = u32;
fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
// --snip--
<span class="boring"> if self.count &lt; 5 {
</span><span class="boring"> self.count += 1;
</span><span class="boring"> Some(self.count)
</span><span class="boring"> } else {
</span><span class="boring"> None
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>这个语法类似于泛型。那么为什么 <code>Iterator</code> trait 不像下面示例 19-13 那样,使用泛型来定义呢?</p>
<pre><code class="language-rust noplayground">pub trait Iterator&lt;T&gt; {
fn next(&amp;mut self) -&gt; Option&lt;T&gt;;
}</code></pre>
<p><span class="caption">示例 19-13: 一个使用泛型的 <code>Iterator</code> trait 假想定义</span></p>
<p>区别在于当如示例 19-13 那样使用泛型时,则不得不在每一个实现中标注类型。这是因为我们也可以实现为 <code>Iterator&lt;String&gt; for Counter</code>,或任何其他类型,这样就可以有多个 <code>Counter</code><code>Iterator</code> 的实现。换句话说,当 trait 有泛型参数时,可以多次实现这个 trait每次需改变泛型参数的具体类型。接着当使用 <code>Counter</code><code>next</code> 方法时,必须提供类型注解来表明希望使用 <code>Iterator</code> 的哪一个实现。</p>
<p>有了关联类型,在实现时就无需标注类型,因为不能多次实现这个 trait。对于示例 19-12 使用关联类型的定义,我们只能选择一次 <code>Item</code> 会是什么类型,因为只能有一个 <code>impl Iterator for Counter</code>。当调用 <code>Counter</code><code>next</code> 时不必每次指定我们需要 <code>u32</code> 值的迭代器。</p>
<p>关联类型也会成为 trait 契约的一部分trait 的实现必须提供一个类型来替代关联类型占位符。关联类型通常以它的用途来命名,并且我们最好在 API 文档中为关联类型编写文档。</p>
<h3 id="默认泛型类型参数和运算符重载"><a class="header" href="#默认泛型类型参数和运算符重载">默认泛型类型参数和运算符重载</a></h3>
<p>当使用泛型类型参数时,可以为泛型指定一个默认的具体类型。如果默认类型就足够的话,这消除了为具体类型实现 trait 的需要。为泛型类型指定默认类型的语法是在声明泛型类型时使用 <code>&lt;PlaceholderType=ConcreteType&gt;</code></p>
<p>这种情况的一个非常好的例子是使用 <strong>运算符重载</strong><em>Operator overloading</em>),这是指在特定情况下自定义运算符(比如 <code>+</code>)行为的操作。</p>
<p>Rust 并不允许创建自定义运算符或重载任意运算符,不过 <code>std::ops</code> 中所列出的运算符和相应的 trait 可以通过实现运算符相关 trait 来重载。例如,示例 19-14 中展示了如何在 <code>Point</code> 结构体上实现 <code>Add</code> trait 来重载 <code>+</code> 运算符,这样就可以将两个 <code>Point</code> 实例相加了:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::ops::Add;
#[derive(Debug, Copy, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -&gt; Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
assert_eq!(
Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
Point { x: 3, y: 3 }
);
}</code></pre></pre>
<p><span class="caption">示例 19-14: 实现 <code>Add</code> trait 重载 <code>Point</code> 实例的 <code>+</code> 运算符</span></p>
<p><code>add</code> 方法将两个 <code>Point</code> 实例的 <code>x</code> 值和 <code>y</code> 值分别相加来创建一个新的 <code>Point</code><code>Add</code> trait 有一个叫做 <code>Output</code> 的关联类型,它用来决定 <code>add</code> 方法的返回值类型。</p>
<p>这里默认泛型类型位于 <code>Add</code> trait 中。这里是其定义:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>trait Add&lt;Rhs=Self&gt; {
type Output;
fn add(self, rhs: Rhs) -&gt; Self::Output;
}
<span class="boring">}</span></code></pre></pre>
<p>这些代码看来应该很熟悉,这是一个带有一个方法和一个关联类型的 trait。比较陌生的部分是尖括号中的 <code>Rhs=Self</code>:这个语法叫做 <strong>默认类型参数</strong><em>default type parameters</em>)。<code>Rhs</code> 是一个泛型类型参数“right hand side” 的缩写),它用于定义 <code>add</code> 方法中的 <code>rhs</code> 参数。如果实现 <code>Add</code> trait 时不指定 <code>Rhs</code> 的具体类型,<code>Rhs</code> 的类型将是默认的 <code>Self</code> 类型,也就是在其上实现 <code>Add</code> 的类型。</p>
<p>当为 <code>Point</code> 实现 <code>Add</code> 时,使用了默认的 <code>Rhs</code>,因为我们希望将两个 <code>Point</code> 实例相加。让我们看看一个实现 <code>Add</code> trait 时希望自定义 <code>Rhs</code> 类型而不是使用默认类型的例子。</p>
<p>这里有两个存放不同单元值的结构体,<code>Millimeters</code><code>Meters</code>。(这种将现有类型简单封装进另一个结构体的方式被称为 <strong>newtype 模式</strong><em>newtype pattern</em>,之后的 <a href="ch20-03-advanced-traits.html#newtype-%E6%A8%A1%E5%BC%8F%E7%94%A8%E4%BB%A5%E5%9C%A8%E5%A4%96%E9%83%A8%E7%B1%BB%E5%9E%8B%E4%B8%8A%E5%AE%9E%E7%8E%B0%E5%A4%96%E9%83%A8-trait">“为了类型安全和抽象而使用 newtype 模式”</a> 部分会详细介绍。)我们希望能够将毫米值与米值相加,并让 <code>Add</code> 的实现正确处理转换。可以为 <code>Millimeters</code> 实现 <code>Add</code> 并以 <code>Meters</code> 作为 <code>Rhs</code>,如示例 19-15 所示。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::ops::Add;
struct Millimeters(u32);
struct Meters(u32);
impl Add&lt;Meters&gt; for Millimeters {
type Output = Millimeters;
fn add(self, other: Meters) -&gt; Millimeters {
Millimeters(self.0 + (other.0 * 1000))
}
}</code></pre>
<p><span class="caption">示例 19-15: 在 <code>Millimeters</code> 上实现 <code>Add</code>,以便能够将 <code>Millimeters</code><code>Meters</code> 相加</span></p>
<p>为了使 <code>Millimeters</code><code>Meters</code> 能够相加,我们指定 <code>impl Add&lt;Meters&gt;</code> 来设定 <code>Rhs</code> 类型参数的值而不是使用默认的 <code>Self</code></p>
<p>默认参数类型主要用于如下两个方面:</p>
<ul>
<li>扩展类型而不破坏现有代码。</li>
<li>在大部分用户都不需要的特定情况进行自定义。</li>
</ul>
<p>标准库的 <code>Add</code> trait 就是一个第二个目的例子:大部分时候你会将两个相似的类型相加,不过它提供了自定义额外行为的能力。在 <code>Add</code> trait 定义中使用默认类型参数意味着大部分时候无需指定额外的参数。换句话说,一小部分实现的样板代码是不必要的,这样使用 trait 就更容易了。</p>
<p>第一个目的是相似的,但过程是反过来的:如果需要为现有 trait 增加类型参数,为其提供一个默认类型将允许我们在不破坏现有实现代码的基础上扩展 trait 的功能。</p>
<h3 id="完全限定语法与消歧义调用相同名称的方法"><a class="header" href="#完全限定语法与消歧义调用相同名称的方法">完全限定语法与消歧义:调用相同名称的方法</a></h3>
<p>Rust 既不能避免一个 trait 与另一个 trait 拥有相同名称的方法,也不能阻止为同一类型同时实现这两个 trait。甚至直接在类型上实现开始已经有的同名方法也是可能的</p>
<p>不过,当调用这些同名方法时,需要告诉 Rust 我们希望使用哪一个。考虑一下示例 19-16 中的代码,这里定义了 trait <code>Pilot</code><code>Wizard</code> 都拥有方法 <code>fly</code>。接着在一个本身已经实现了名为 <code>fly</code> 方法的类型 <code>Human</code> 上实现这两个 trait。每一个 <code>fly</code> 方法都进行了不同的操作:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">trait Pilot {
fn fly(&amp;self);
}
trait Wizard {
fn fly(&amp;self);
}
struct Human;
impl Pilot for Human {
fn fly(&amp;self) {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly(&amp;self) {
println!("Up!");
}
}
impl Human {
fn fly(&amp;self) {
println!("*waving arms furiously*");
}
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 19-16: 两个 trait 定义为拥有 <code>fly</code> 方法,并在直接定义有 <code>fly</code> 方法的 <code>Human</code> 类型上实现这两个 trait</span></p>
<p>当调用 <code>Human</code> 实例的 <code>fly</code> 时,编译器默认调用直接实现在类型上的方法,如示例 19-17 所示。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">trait Pilot {
</span><span class="boring"> fn fly(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">trait Wizard {
</span><span class="boring"> fn fly(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Human;
</span><span class="boring">
</span><span class="boring">impl Pilot for Human {
</span><span class="boring"> fn fly(&amp;self) {
</span><span class="boring"> println!("This is your captain speaking.");
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Wizard for Human {
</span><span class="boring"> fn fly(&amp;self) {
</span><span class="boring"> println!("Up!");
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Human {
</span><span class="boring"> fn fly(&amp;self) {
</span><span class="boring"> println!("*waving arms furiously*");
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let person = Human;
person.fly();
}</code></pre></pre>
<p><span class="caption">示例 19-17: 调用 <code>Human</code> 实例的 <code>fly</code></span></p>
<p>运行这段代码会打印出 <code>*waving arms furiously*</code>,这表明 Rust 调用了直接实现在 <code>Human</code> 上的 <code>fly</code> 方法。</p>
<p>为了能够调用 <code>Pilot</code> trait 或 <code>Wizard</code> trait 的 <code>fly</code> 方法,我们需要使用更明显的语法以便能指定我们指的是哪个 <code>fly</code> 方法。这个语法展示在示例 19-18 中:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">trait Pilot {
</span><span class="boring"> fn fly(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">trait Wizard {
</span><span class="boring"> fn fly(&amp;self);
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Human;
</span><span class="boring">
</span><span class="boring">impl Pilot for Human {
</span><span class="boring"> fn fly(&amp;self) {
</span><span class="boring"> println!("This is your captain speaking.");
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Wizard for Human {
</span><span class="boring"> fn fly(&amp;self) {
</span><span class="boring"> println!("Up!");
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Human {
</span><span class="boring"> fn fly(&amp;self) {
</span><span class="boring"> println!("*waving arms furiously*");
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let person = Human;
Pilot::fly(&amp;person);
Wizard::fly(&amp;person);
person.fly();
}</code></pre></pre>
<p><span class="caption">示例 19-18: 指定我们希望调用哪一个 trait 的 <code>fly</code> 方法</span></p>
<p>在方法名前指定 trait 名向 Rust 澄清了我们希望调用哪个 <code>fly</code> 实现。也可以选择写成 <code>Human::fly(&amp;person)</code>,这等同于示例 19-18 中的 <code>person.fly()</code>,不过如果无需消歧义的话这么写就有点长了。</p>
<p>运行这段代码会打印出:</p>
<pre><code class="language-console">$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.46s
Running `target/debug/traits-example`
This is your captain speaking.
Up!
*waving arms furiously*
</code></pre>
<p>因为 <code>fly</code> 方法获取一个 <code>self</code> 参数,如果有两个 <strong>类型</strong> 都实现了同一 <strong>trait</strong>Rust 可以根据 <code>self</code> 的类型计算出应该使用哪一个 trait 实现。</p>
<p>然而,不是方法的关联函数没有 <code>self</code> 参数。当存在多个类型或者 trait 定义了相同函数名的非方法函数时Rust 就不总是能计算出我们期望的是哪一个类型,除非使用 <strong>完全限定语法</strong><em>fully qualified syntax</em>)。例如示例 19-19 中的创建了一个希望将所有小狗叫做 <em>Spot</em> 的动物收容所的 trait。<code>Animal</code> trait 有一个关联非方法函数 <code>baby_name</code>。结构体 <code>Dog</code> 实现了 <code>Animal</code>,同时又直接提供了关联非方法函数 <code>baby_name</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">trait Animal {
fn baby_name() -&gt; String;
}
struct Dog;
impl Dog {
fn baby_name() -&gt; String {
String::from("Spot")
}
}
impl Animal for Dog {
fn baby_name() -&gt; String {
String::from("puppy")
}
}
fn main() {
println!("A baby dog is called a {}", Dog::baby_name());
}</code></pre></pre>
<p><span class="caption">示例 19-19: 一个带有关联函数的 trait 和一个带有同名关联函数并实现了此 trait 的类型</span></p>
<p><code>Dog</code> 上定义的关联函数 <code>baby_name</code> 的实现代码将所有的小狗起名为 Spot。<code>Dog</code> 类型还实现了 <code>Animal</code> trait它描述了所有动物的共有的特征。小狗被称为 puppy这表现为 <code>Dog</code><code>Animal</code> trait 实现中与 <code>Animal</code> trait 相关联的函数 <code>baby_name</code></p>
<p><code>main</code> 调用了 <code>Dog::baby_name</code> 函数,它直接调用了定义于 <code>Dog</code> 之上的关联函数。这段代码会打印出:</p>
<pre><code class="language-console">$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.54s
Running `target/debug/traits-example`
A baby dog is called a Spot
</code></pre>
<p>这并不是我们需要的。我们希望调用的是 <code>Dog</code><code>Animal</code> trait 实现那部分的 <code>baby_name</code> 函数,这样能够打印出 <code>A baby dog is called a puppy</code>。示例 19-18 中用到的技术在这并不管用;如果将 <code>main</code> 改为示例 19-20 中的代码,则会得到一个编译错误:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">trait Animal {
</span><span class="boring"> fn baby_name() -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Dog;
</span><span class="boring">
</span><span class="boring">impl Dog {
</span><span class="boring"> fn baby_name() -&gt; String {
</span><span class="boring"> String::from("Spot")
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Animal for Dog {
</span><span class="boring"> fn baby_name() -&gt; String {
</span><span class="boring"> String::from("puppy")
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
println!("A baby dog is called a {}", Animal::baby_name());
}</code></pre>
<p><span class="caption">示例 19-20: 尝试调用 <code>Animal</code> trait 的 <code>baby_name</code> 函数,不过 Rust 并不知道该使用哪一个实现</span></p>
<p>因为 <code>Animal::baby_name</code> 没有 <code>self</code> 参数,同时这可能会有其它类型实现了 <code>Animal</code> traitRust 无法计算出所需的是哪一个 <code>Animal::baby_name</code> 实现。我们会得到这个编译错误:</p>
<pre><code class="language-console">$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--&gt; src/main.rs:20:43
|
2 | fn baby_name() -&gt; String;
| ------------------------- `Animal::baby_name` defined here
...
20 | println!("A baby dog is called a {}", Animal::baby_name());
| ^^^^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use the fully-qualified path to the only available implementation
|
20 | println!("A baby dog is called a {}", &lt;Dog as Animal&gt;::baby_name());
| +++++++ +
For more information about this error, try `rustc --explain E0790`.
error: could not compile `traits-example` (bin "traits-example") due to 1 previous error
</code></pre>
<p>为了消歧义并告诉 Rust 我们希望使用的是 <code>Dog</code><code>Animal</code> 实现而不是其它类型的 <code>Animal</code> 实现,需要使用 <strong>完全限定语法</strong>,这是调用函数时最为明确的方式。示例 19-21 展示了如何使用完全限定语法:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">trait Animal {
</span><span class="boring"> fn baby_name() -&gt; String;
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Dog;
</span><span class="boring">
</span><span class="boring">impl Dog {
</span><span class="boring"> fn baby_name() -&gt; String {
</span><span class="boring"> String::from("Spot")
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Animal for Dog {
</span><span class="boring"> fn baby_name() -&gt; String {
</span><span class="boring"> String::from("puppy")
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
println!("A baby dog is called a {}", &lt;Dog as Animal&gt;::baby_name());
}</code></pre></pre>
<p><span class="caption">示例 19-21: 使用完全限定语法来指定我们希望调用的是 <code>Dog</code><code>Animal</code> trait 实现中的 <code>baby_name</code> 函数</span></p>
<p>我们在尖括号中向 Rust 提供了类型注解,并通过在此函数调用中将 <code>Dog</code> 类型当作 <code>Animal</code> 对待,来指定希望调用的是 <code>Dog</code><code>Animal</code> trait 实现中的 <code>baby_name</code> 函数。现在这段代码会打印出我们期望的数据:</p>
<pre><code class="language-console">$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/traits-example`
A baby dog is called a puppy
</code></pre>
<p>通常,完全限定语法定义为:</p>
<pre><code class="language-rust ignore">&lt;Type as Trait&gt;::function(receiver_if_method, next_arg, ...);</code></pre>
<p>对于不是方法的关联函数,其没有一个 <code>receiver</code>,故只会有其他参数的列表。可以选择在任何函数或方法调用处使用完全限定语法。然而,允许省略任何 Rust 能够从程序中的其他信息中计算出的部分。只有当存在多个同名实现而 Rust 需要帮助以便知道我们希望调用哪个实现时,才需要使用这个较为冗长的语法。</p>
<h3 id="父-trait-用于在另一个-trait-中使用某-trait-的功能"><a class="header" href="#父-trait-用于在另一个-trait-中使用某-trait-的功能">父 trait 用于在另一个 trait 中使用某 trait 的功能</a></h3>
<p>有时我们可能会需要编写一个依赖另一个 trait 的 trait 定义:对于一个实现了第一个 trait 的类型,你希望要求这个类型也实现了第二个 trait。如此就可使 trait 定义使用第二个 trait 的关联项。这个所需的 trait 是我们实现的 trait 的 <strong>trait</strong><em>supertrait</em>)。</p>
<p>例如我们希望创建一个带有 <code>outline_print</code> 方法的 trait <code>OutlinePrint</code>,它会将给定的值格式化为带有星号框。也就是说,给定一个实现了标准库 <code>Display</code> trait 的并返回 <code>(x, y)</code><code>Point</code>,当调用以 <code>1</code> 作为 <code>x</code><code>3</code> 作为 <code>y</code><code>Point</code> 实例的 <code>outline_print</code> 会显示如下:</p>
<pre><code class="language-text">**********
* *
* (1, 3) *
* *
**********
</code></pre>
<p><code>outline_print</code> 的实现中,因为希望能够使用 <code>Display</code> trait 的功能,则需要说明 <code>OutlinePrint</code> 只能用于同时也实现了 <code>Display</code> 并提供了 <code>OutlinePrint</code> 需要的功能的类型。可以通过在 trait 定义中指定 <code>OutlinePrint: Display</code> 来做到这一点。这类似于为 trait 增加 trait bound。示例 19-22 展示了一个 <code>OutlinePrint</code> trait 的实现:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::fmt;
trait OutlinePrint: fmt::Display {
fn outline_print(&amp;self) {
let output = self.to_string();
let len = output.len();
println!("{}", "*".repeat(len + 4));
println!("*{}*", " ".repeat(len + 2));
println!("* {output} *");
println!("*{}*", " ".repeat(len + 2));
println!("{}", "*".repeat(len + 4));
}
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre></pre>
<p><span class="caption">示例 19-22: 实现 <code>OutlinePrint</code> trait它要求来自 <code>Display</code> 的功能</span></p>
<p>因为指定了 <code>OutlinePrint</code> 需要 <code>Display</code> trait则可以在 <code>outline_print</code> 中使用 <code>to_string</code>,其会为任何实现 <code>Display</code> 的类型自动实现。如果不在 trait 名后增加 <code>: Display</code> 并尝试在 <code>outline_print</code> 中使用 <code>to_string</code>,则会得到一个错误说在当前作用域中没有找到用于 <code>&amp;Self</code> 类型的方法 <code>to_string</code></p>
<p>让我们看看如果尝试在一个没有实现 <code>Display</code> 的类型上实现 <code>OutlinePrint</code> 会发生什么,比如 <code>Point</code> 结构体:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::fmt;
</span><span class="boring">
</span><span class="boring">trait OutlinePrint: fmt::Display {
</span><span class="boring"> fn outline_print(&amp;self) {
</span><span class="boring"> let output = self.to_string();
</span><span class="boring"> let len = output.len();
</span><span class="boring"> println!("{}", "*".repeat(len + 4));
</span><span class="boring"> println!("*{}*", " ".repeat(len + 2));
</span><span class="boring"> println!("* {output} *");
</span><span class="boring"> println!("*{}*", " ".repeat(len + 2));
</span><span class="boring"> println!("{}", "*".repeat(len + 4));
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>struct Point {
x: i32,
y: i32,
}
impl OutlinePrint for Point {}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let p = Point { x: 1, y: 3 };
</span><span class="boring"> p.outline_print();
</span><span class="boring">}</span></code></pre>
<p>这样会得到一个错误说 <code>Display</code> 是必须的而未被实现:</p>
<pre><code class="language-console">$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
error[E0277]: `Point` doesn't implement `std::fmt::Display`
--&gt; src/main.rs:20:23
|
20 | impl OutlinePrint for Point {}
| ^^^^^ `Point` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `Point`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
note: required by a bound in `OutlinePrint`
--&gt; src/main.rs:3:21
|
3 | trait OutlinePrint: fmt::Display {
| ^^^^^^^^^^^^ required by this bound in `OutlinePrint`
error[E0277]: `Point` doesn't implement `std::fmt::Display`
--&gt; src/main.rs:24:7
|
24 | p.outline_print();
| ^^^^^^^^^^^^^ `Point` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `Point`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
note: required by a bound in `OutlinePrint::outline_print`
--&gt; src/main.rs:3:21
|
3 | trait OutlinePrint: fmt::Display {
| ^^^^^^^^^^^^ required by this bound in `OutlinePrint::outline_print`
4 | fn outline_print(&amp;self) {
| ------------- required by a bound in this associated function
For more information about this error, try `rustc --explain E0277`.
error: could not compile `traits-example` (bin "traits-example") due to 2 previous errors
</code></pre>
<p>一旦在 <code>Point</code> 上实现 <code>Display</code> 并满足 <code>OutlinePrint</code> 要求的限制,比如这样:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">trait OutlinePrint: fmt::Display {
</span><span class="boring"> fn outline_print(&amp;self) {
</span><span class="boring"> let output = self.to_string();
</span><span class="boring"> let len = output.len();
</span><span class="boring"> println!("{}", "*".repeat(len + 4));
</span><span class="boring"> println!("*{}*", " ".repeat(len + 2));
</span><span class="boring"> println!("* {output} *");
</span><span class="boring"> println!("*{}*", " ".repeat(len + 2));
</span><span class="boring"> println!("{}", "*".repeat(len + 4));
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Point {
</span><span class="boring"> x: i32,
</span><span class="boring"> y: i32,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl OutlinePrint for Point {}
</span><span class="boring">
</span>use std::fmt;
impl fmt::Display for Point {
fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let p = Point { x: 1, y: 3 };
</span><span class="boring"> p.outline_print();
</span><span class="boring">}</span></code></pre></pre>
<p>那么在 <code>Point</code> 上实现 <code>OutlinePrint</code> trait 将能成功编译,并可以在 <code>Point</code> 实例上调用 <code>outline_print</code> 来显示位于星号框中的点的值。</p>
<h3 id="newtype-模式用以在外部类型上实现外部-trait"><a class="header" href="#newtype-模式用以在外部类型上实现外部-trait">newtype 模式用以在外部类型上实现外部 trait</a></h3>
<p>在第十章的 <a href="ch10-02-traits.html#%E4%B8%BA%E7%B1%BB%E5%9E%8B%E5%AE%9E%E7%8E%B0-trait">“为类型实现 trait”</a> 部分我们提到了孤儿规则orphan rule它说明只要 trait 或类型对于当前 crate 是本地的话就可以在此类型上实现该 trait。一个绕开这个限制的方法是使用 <strong>newtype 模式</strong><em>newtype pattern</em>),它涉及到在一个元组结构体(第五章 <a href="ch05-01-defining-structs.html#%E4%BD%BF%E7%94%A8%E6%B2%A1%E6%9C%89%E5%91%BD%E5%90%8D%E5%AD%97%E6%AE%B5%E7%9A%84%E5%85%83%E7%BB%84%E7%BB%93%E6%9E%84%E4%BD%93%E6%9D%A5%E5%88%9B%E5%BB%BA%E4%B8%8D%E5%90%8C%E7%9A%84%E7%B1%BB%E5%9E%8B">“用没有命名字段的元组结构体来创建不同的类型”</a> 部分介绍了元组结构体)中创建一个新类型。这个元组结构体带有一个字段作为希望实现 trait 的类型的简单封装。接着这个封装类型对于 crate 是本地的,这样就可以在这个封装上实现 trait。<em>Newtype</em> 是一个源自 Haskell 编程语言的概念。使用这个模式没有运行时性能惩罚,这个封装类型在编译时就被省略了。</p>
<p>例如,如果想要在 <code>Vec&lt;T&gt;</code> 上实现 <code>Display</code>,而孤儿规则阻止我们直接这么做,因为 <code>Display</code> trait 和 <code>Vec&lt;T&gt;</code> 都定义于我们的 crate 之外。可以创建一个包含 <code>Vec&lt;T&gt;</code> 实例的 <code>Wrapper</code> 结构体,接着可以如列表 19-23 那样在 <code>Wrapper</code> 上实现 <code>Display</code> 并使用 <code>Vec&lt;T&gt;</code> 的值:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::fmt;
struct Wrapper(Vec&lt;String&gt;);
impl fmt::Display for Wrapper {
fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
fn main() {
let w = Wrapper(vec![String::from("hello"), String::from("world")]);
println!("w = {w}");
}</code></pre></pre>
<p><span class="caption">示例 19-23: 创建 <code>Wrapper</code> 类型封装 <code>Vec&lt;String&gt;</code> 以便能够实现 <code>Display</code></span></p>
<p><code>Display</code> 的实现使用 <code>self.0</code> 来访问其内部的 <code>Vec&lt;T&gt;</code>,因为 <code>Wrapper</code> 是元组结构体而 <code>Vec&lt;T&gt;</code> 是结构体总位于索引 0 的项。接着就可以使用 <code>Wrapper</code><code>Display</code> 的功能了。</p>
<p>此方法的缺点是,因为 <code>Wrapper</code> 是一个新类型,它没有定义于其值之上的方法;必须直接在 <code>Wrapper</code> 上实现 <code>Vec&lt;T&gt;</code> 的所有方法,这样就可以代理到<code>self.0</code> 上 —— 这就允许我们完全像 <code>Vec&lt;T&gt;</code> 那样对待 <code>Wrapper</code>。如果希望新类型拥有其内部类型的每一个方法,为封装类型实现 <code>Deref</code> trait第十五章 <a href="ch15-02-deref.html#%E9%80%9A%E8%BF%87%E5%AE%9E%E7%8E%B0-deref-trait-%E5%B0%86%E6%9F%90%E7%B1%BB%E5%9E%8B%E5%83%8F%E5%BC%95%E7%94%A8%E4%B8%80%E6%A0%B7%E5%A4%84%E7%90%86">“通过 <code>Deref</code> trait 将智能指针当作常规引用处理”</a> 部分讨论过)并返回其内部类型是一种解决方案。如果不希望封装类型拥有所有内部类型的方法 —— 比如为了限制封装类型的行为 —— 则必须只自行实现所需的方法。</p>
<p>甚至当不涉及 trait 时 newtype 模式也很有用。现在让我们将话题的焦点转移到一些与 Rust 类型系统交互的高级方法上来吧。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="高级类型"><a class="header" href="#高级类型">高级类型</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch20-04-advanced-types.md">ch20-04-advanced-types.md</a>
<br>
commit 95e931170404cb98d476b19017cbbdbc00d0834d</p>
</blockquote>
<p>Rust 的类型系统有一些我们曾经提到但没有讨论过的功能。首先我们从一个关于为什么 newtype 与类型一样有用的更宽泛的讨论开始。接着会转向类型别名type aliases一个类似于 newtype 但有着稍微不同的语义的功能。我们还会讨论 <code>!</code> 类型和动态大小类型。</p>
<blockquote>
<p>这一部分假设你已经阅读了之前的 <a href="ch20-03-advanced-traits.html#newtype-%E6%A8%A1%E5%BC%8F%E7%94%A8%E4%BB%A5%E5%9C%A8%E5%A4%96%E9%83%A8%E7%B1%BB%E5%9E%8B%E4%B8%8A%E5%AE%9E%E7%8E%B0%E5%A4%96%E9%83%A8-trait">“newtype 模式用于在外部类型上实现外部 trait”</a> 部分。</p>
</blockquote>
<h3 id="为了类型安全和抽象而使用-newtype-模式"><a class="header" href="#为了类型安全和抽象而使用-newtype-模式">为了类型安全和抽象而使用 newtype 模式</a></h3>
<p>newtype 模式也可以用于一些其他我们还未讨论的功能,包括静态的确保某值不被混淆,和用来表示一个值的单位。实际上示例 19-15 中已经有一个这样的例子:<code>Millimeters</code><code>Meters</code> 结构体都在 newtype 中封装了 <code>u32</code> 值。如果编写了一个有 <code>Millimeters</code> 类型参数的函数,不小心使用 <code>Meters</code> 或普通的 <code>u32</code> 值来调用该函数的程序是不能编译的。</p>
<p>newtype 模式也可以用于抽象掉一些类型的实现细节:例如,封装类型可以暴露出与直接使用其内部私有类型时所不同的公有 API。</p>
<p>newtype 也可以隐藏其内部的泛型类型。例如,可以提供一个封装了 <code>HashMap&lt;i32, String&gt;</code><code>People</code> 类型,用来储存人名以及相应的 ID。使用 <code>People</code> 的代码只需与提供的公有 API 交互即可,比如向 <code>People</code> 集合增加名字字符串的方法,这样这些代码就无需知道在内部我们将一个 <code>i32</code> ID 赋予了这个名字了。newtype 模式是一种实现第十八章 <a href="ch18-01-what-is-oo.html#%E5%B0%81%E8%A3%85%E9%9A%90%E8%97%8F%E4%BA%86%E5%AE%9E%E7%8E%B0%E7%BB%86%E8%8A%82">“封装隐藏了实现细节”</a> 部分所讨论的隐藏实现细节的封装的轻量级方法。</p>
<h3 id="类型别名用来创建类型同义词"><a class="header" href="#类型别名用来创建类型同义词">类型别名用来创建类型同义词</a></h3>
<p>Rust 提供了声明 <strong>类型别名</strong><em>type alias</em>)的能力,使用 <code>type</code> 关键字来给予现有类型另一个名字。例如,可以像这样创建 <code>i32</code> 的别名 <code>Kilometers</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> type Kilometers = i32;
<span class="boring">
</span><span class="boring"> let x: i32 = 5;
</span><span class="boring"> let y: Kilometers = 5;
</span><span class="boring">
</span><span class="boring"> println!("x + y = {}", x + y);
</span><span class="boring">}</span></code></pre></pre>
<p>这意味着 <code>Kilometers</code><code>i32</code><strong>同义词</strong><em>synonym</em>);不同于示例 19-15 中创建的 <code>Millimeters</code><code>Meters</code> 类型。<code>Kilometers</code> 不是一个新的、单独的类型。<code>Kilometers</code> 类型的值将被完全当作 <code>i32</code> 类型值来对待:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> type Kilometers = i32;
let x: i32 = 5;
let y: Kilometers = 5;
println!("x + y = {}", x + y);
<span class="boring">}</span></code></pre></pre>
<p>因为 <code>Kilometers</code><code>i32</code> 的别名,它们是同一类型,可以将 <code>i32</code><code>Kilometers</code> 相加,也可以将 <code>Kilometers</code> 传递给获取 <code>i32</code> 参数的函数。但通过这种手段无法获得上一部分讨论的 newtype 模式所提供的类型检查的好处。换句话说,如果在哪里混用 <code>Kilometers</code><code>i32</code> 的值,编译器也不会给出一个错误。</p>
<p>类型别名的主要用途是减少重复。例如,可能会有这样很长的类型:</p>
<pre><code class="language-rust ignore">Box&lt;dyn Fn() + Send + 'static&gt;</code></pre>
<p>在函数签名或类型注解中每次都书写这个类型将是枯燥且易于出错的。想象一下如示例 19-24 这样全是如此代码的项目:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let f: Box&lt;dyn Fn() + Send + 'static&gt; = Box::new(|| println!("hi"));
fn takes_long_type(f: Box&lt;dyn Fn() + Send + 'static&gt;) {
// --snip--
}
fn returns_long_type() -&gt; Box&lt;dyn Fn() + Send + 'static&gt; {
// --snip--
<span class="boring"> Box::new(|| ())
</span> }
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 19-24: 在很多地方使用名称很长的类型</span></p>
<p>类型别名通过减少项目中重复代码的数量来使其更加易于控制。这里我们为这个冗长的类型引入了一个叫做 <code>Thunk</code> 的别名,这样就可以如示例 19-25 所示将所有使用这个类型的地方替换为更短的 <code>Thunk</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> type Thunk = Box&lt;dyn Fn() + Send + 'static&gt;;
let f: Thunk = Box::new(|| println!("hi"));
fn takes_long_type(f: Thunk) {
// --snip--
}
fn returns_long_type() -&gt; Thunk {
// --snip--
<span class="boring"> Box::new(|| ())
</span> }
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 19-25: 引入类型别名 <code>Thunk</code> 来减少重复</span></p>
<p>这样读写起来就容易多了!为类型别名选择一个好名字也可以帮助你表达意图(单词 <em>thunk</em> 表示会在之后被计算的代码,所以这是一个存放闭包的合适的名字)。</p>
<p>类型别名也经常与 <code>Result&lt;T, E&gt;</code> 结合使用来减少重复。考虑一下标准库中的 <code>std::io</code> 模块。I/O 操作通常会返回一个 <code>Result&lt;T, E&gt;</code>,因为这些操作可能会失败。标准库中的 <code>std::io::Error</code> 结构体代表了所有可能的 I/O 错误。<code>std::io</code> 中大部分函数会返回 <code>Result&lt;T, E&gt;</code>,其中 <code>E</code><code>std::io::Error</code>,比如 <code>Write</code> trait 中的这些函数:</p>
<pre><code class="language-rust noplayground">use std::fmt;
use std::io::Error;
pub trait Write {
fn write(&amp;mut self, buf: &amp;[u8]) -&gt; Result&lt;usize, Error&gt;;
fn flush(&amp;mut self) -&gt; Result&lt;(), Error&gt;;
fn write_all(&amp;mut self, buf: &amp;[u8]) -&gt; Result&lt;(), Error&gt;;
fn write_fmt(&amp;mut self, fmt: fmt::Arguments) -&gt; Result&lt;(), Error&gt;;
}</code></pre>
<p>这里出现了很多的 <code>Result&lt;..., Error&gt;</code>。为此,<code>std::io</code> 有这个类型别名声明:</p>
<pre><code class="language-rust noplayground"><span class="boring">use std::fmt;
</span><span class="boring">
</span>type Result&lt;T&gt; = std::result::Result&lt;T, std::io::Error&gt;;
<span class="boring">
</span><span class="boring">pub trait Write {
</span><span class="boring"> fn write(&amp;mut self, buf: &amp;[u8]) -&gt; Result&lt;usize&gt;;
</span><span class="boring"> fn flush(&amp;mut self) -&gt; Result&lt;()&gt;;
</span><span class="boring">
</span><span class="boring"> fn write_all(&amp;mut self, buf: &amp;[u8]) -&gt; Result&lt;()&gt;;
</span><span class="boring"> fn write_fmt(&amp;mut self, fmt: fmt::Arguments) -&gt; Result&lt;()&gt;;
</span><span class="boring">}</span></code></pre>
<p>因为这位于 <code>std::io</code> 中,可用的完全限定的别名是 <code>std::io::Result&lt;T&gt;</code>;也就是说,<code>Result&lt;T, E&gt;</code><code>E</code> 放入了 <code>std::io::Error</code><code>Write</code> trait 中的函数最终看起来像这样:</p>
<pre><code class="language-rust noplayground"><span class="boring">use std::fmt;
</span><span class="boring">
</span><span class="boring">type Result&lt;T&gt; = std::result::Result&lt;T, std::io::Error&gt;;
</span><span class="boring">
</span>pub trait Write {
fn write(&amp;mut self, buf: &amp;[u8]) -&gt; Result&lt;usize&gt;;
fn flush(&amp;mut self) -&gt; Result&lt;()&gt;;
fn write_all(&amp;mut self, buf: &amp;[u8]) -&gt; Result&lt;()&gt;;
fn write_fmt(&amp;mut self, fmt: fmt::Arguments) -&gt; Result&lt;()&gt;;
}</code></pre>
<p>类型别名在两个方面有帮助:易于编写 <strong></strong> 在整个 <code>std::io</code> 中提供了一致的接口。因为这是一个别名,它只是另一个 <code>Result&lt;T, E&gt;</code>,这意味着可以在其上使用 <code>Result&lt;T, E&gt;</code> 的任何方法,以及像 <code>?</code> 这样的特殊语法。</p>
<h3 id="从不返回的-never-type"><a class="header" href="#从不返回的-never-type">从不返回的 never type</a></h3>
<p>Rust 有一个叫做 <code>!</code> 的特殊类型。在类型理论术语中,它被称为 <em>empty type</em>,因为它没有值。我们更倾向于称之为 <em>never type</em>。这个名字描述了它的作用:在函数从不返回的时候充当返回值。例如:</p>
<pre><code class="language-rust noplayground">fn bar() -&gt; ! {
// --snip--
<span class="boring"> panic!();
</span>}</code></pre>
<p>这读 “函数 <code>bar</code> 从不返回”,而从不返回的函数被称为 <strong>发散函数</strong><em>diverging functions</em>)。不能创建 <code>!</code> 类型的值,所以 <code>bar</code> 也不可能返回值。</p>
<p>不过一个不能创建值的类型有什么用呢?如果你回想一下示例 2-5 中的代码,曾经有一些看起来像这样的代码,如示例 19-26 所重现的:</p>
<pre><code class="language-rust ignore"><span class="boring">use rand::Rng;
</span><span class="boring">use std::cmp::Ordering;
</span><span class="boring">use std::io;
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> println!("Guess the number!");
</span><span class="boring">
</span><span class="boring"> let secret_number = rand::thread_rng().gen_range(1..=100);
</span><span class="boring">
</span><span class="boring"> println!("The secret number is: {secret_number}");
</span><span class="boring">
</span><span class="boring"> loop {
</span><span class="boring"> println!("Please input your guess.");
</span><span class="boring">
</span><span class="boring"> let mut guess = String::new();
</span><span class="boring">
</span><span class="boring"> // --snip--
</span><span class="boring">
</span><span class="boring"> io::stdin()
</span><span class="boring"> .read_line(&amp;mut guess)
</span><span class="boring"> .expect("Failed to read line");
</span><span class="boring">
</span> let guess: u32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
<span class="boring">
</span><span class="boring"> println!("You guessed: {guess}");
</span><span class="boring">
</span><span class="boring"> // --snip--
</span><span class="boring">
</span><span class="boring"> match guess.cmp(&amp;secret_number) {
</span><span class="boring"> Ordering::Less =&gt; println!("Too small!"),
</span><span class="boring"> Ordering::Greater =&gt; println!("Too big!"),
</span><span class="boring"> Ordering::Equal =&gt; {
</span><span class="boring"> println!("You win!");
</span><span class="boring"> break;
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 19-26: <code>match</code> 语句和一个以 <code>continue</code> 结束的分支</span></p>
<p>当时我们忽略了代码中的一些细节。在第六章 <a href="ch06-02-match.html#match-%E6%8E%A7%E5%88%B6%E6%B5%81%E7%BB%93%E6%9E%84"><code>match</code> 控制流运算符”</a> 部分,我们学习了 <code>match</code> 的分支必须返回相同的类型。如下代码不能工作:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span><span class="boring"> let guess = "3";
</span> let guess = match guess.trim().parse() {
Ok(_) =&gt; 5,
Err(_) =&gt; "hello",
};
<span class="boring">}</span></code></pre>
<p>这里的 <code>guess</code> 必须既是整型 <strong>也是</strong> 字符串,而 Rust 要求 <code>guess</code> 只能是一个类型。那么 <code>continue</code> 返回了什么呢?为什么示例 19-26 中会允许一个分支返回 <code>u32</code> 而另一个分支却以 <code>continue</code> 结束呢?</p>
<p>正如你可能猜到的,<code>continue</code> 的值是 <code>!</code>。也就是说,当 Rust 要计算 <code>guess</code> 的类型时,它查看这两个分支。前者是 <code>u32</code> 值,而后者是 <code>!</code> 值。因为 <code>!</code> 并没有一个值Rust 决定 <code>guess</code> 的类型是 <code>u32</code></p>
<p>描述 <code>!</code> 的行为的正式方式是 never type 可以强转为任何其他类型。允许 <code>match</code> 的分支以 <code>continue</code> 结束是因为 <code>continue</code> 并不真正返回一个值;相反它把控制权交回上层循环,所以在 <code>Err</code> 的情况,事实上并未对 <code>guess</code> 赋值。</p>
<p>never type 的另一个用途是 <code>panic!</code>。还记得 <code>Option&lt;T&gt;</code> 上的 <code>unwrap</code> 函数吗?它产生一个值或 panic。这里是它的定义</p>
<pre><code class="language-rust ignore"><span class="boring">enum Option&lt;T&gt; {
</span><span class="boring"> Some(T),
</span><span class="boring"> None,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">use crate::Option::*;
</span><span class="boring">
</span>impl&lt;T&gt; Option&lt;T&gt; {
pub fn unwrap(self) -&gt; T {
match self {
Some(val) =&gt; val,
None =&gt; panic!("called `Option::unwrap()` on a `None` value"),
}
}
}</code></pre>
<p>这里与示例 19-34 中的 <code>match</code> 发生了相同的情况Rust 知道 <code>val</code><code>T</code> 类型,<code>panic!</code><code>!</code> 类型,所以整个 <code>match</code> 表达式的结果是 <code>T</code> 类型。这能工作是因为 <code>panic!</code> 并不产生一个值;它会终止程序。对于 <code>None</code> 的情况,<code>unwrap</code> 并不返回一个值,所以这些代码是有效的。</p>
<p>最后一个有着 <code>!</code> 类型的表达式是 <code>loop</code></p>
<pre><code class="language-rust ignore"><span class="boring">fn main() {
</span> print!("forever ");
loop {
print!("and ever ");
}
<span class="boring">}</span></code></pre>
<p>这里,循环永远也不结束,所以此表达式的值是 <code>!</code>。但是如果引入 <code>break</code> 这就不为真了,因为循环在执行到 <code>break</code> 后就会终止。</p>
<h3 id="动态大小类型和-sized-trait"><a class="header" href="#动态大小类型和-sized-trait">动态大小类型和 <code>Sized</code> trait</a></h3>
<p>Rust 需要知道有关类型的某些细节,例如为特定类型的值需要分配多少空间。这便是起初留下的一个类型系统中令人迷惑的角落:即 <strong>动态大小类型</strong><em>dynamically sized types</em>)。这有时被称为 “DST” 或 “unsized types”这些类型允许我们处理只有在运行时才知道大小的类型。</p>
<p>让我们深入研究一个贯穿本书都在使用的动态大小类型的细节:<code>str</code>。没错,不是 <code>&amp;str</code>,而是 <code>str</code> 本身。<code>str</code> 是一个 DST直到运行时我们都不知道字符串有多长。因为直到运行时都不能知道其大小也就意味着不能创建 <code>str</code> 类型的变量,也不能获取 <code>str</code> 类型的参数。考虑一下这些代码,它们不能工作:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let s1: str = "Hello there!";
let s2: str = "How's it going?";
<span class="boring">}</span></code></pre>
<p>Rust 需要知道应该为特定类型的值分配多少内存,同时所有同一类型的值必须使用相同数量的内存。如果允许编写这样的代码,也就意味着这两个 <code>str</code> 需要占用完全相同大小的空间,不过它们有着不同的长度。这也就是为什么不可能创建一个存放动态大小类型的变量的原因。</p>
<p>那么该怎么办呢?你已经知道了这种问题的答案:<code>s1</code><code>s2</code> 的类型是 <code>&amp;str</code> 而不是 <code>str</code>。如果你回想第四章 <a href="ch04-03-slices.html#%E5%AD%97%E7%AC%A6%E4%B8%B2-slice">“字符串 slice”</a> 部分slice 数据结构仅仅储存了开始位置和 slice 的长度。所以虽然 <code>&amp;T</code> 是一个储存了 <code>T</code> 所在的内存位置的单个值,<code>&amp;str</code> 则是 <strong>两个</strong> 值:<code>str</code> 的地址和其长度。这样,<code>&amp;str</code> 就有了一个在编译时可以知道的大小:它是 <code>usize</code> 长度的两倍。也就是说,我们总是知道 <code>&amp;str</code> 的大小,而无论其引用的字符串是多长。这里是 Rust 中动态大小类型的常规用法:它们有一些额外的元信息来储存动态信息的大小。这引出了动态大小类型的黄金规则:必须将动态大小类型的值置于某种指针之后。</p>
<p>可以将 <code>str</code> 与所有类型的指针结合:比如 <code>Box&lt;str&gt;</code><code>Rc&lt;str&gt;</code>。事实上之前我们已经见过了不过是另一个动态大小类型trait。每一个 trait 都是一个可以通过 trait 名称来引用的动态大小类型。在第十八章 <a href="ch18-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> 部分,我们提到了为了将 trait 用于 trait 对象,必须将它们放入指针之后,比如 <code>&amp;dyn Trait</code><code>Box&lt;dyn Trait&gt;</code><code>Rc&lt;dyn Trait&gt;</code> 也可以)。</p>
<p>为了处理 DSTRust 提供了 <code>Sized</code> trait 来决定一个类型的大小是否在编译时可知。这个 trait 自动为编译器在编译时就知道大小的类型实现。另外Rust 隐式的为每一个泛型函数增加了 <code>Sized</code> bound。也就是说对于如下泛型函数定义</p>
<pre><code class="language-rust ignore">fn generic&lt;T&gt;(t: T) {
// --snip--
}</code></pre>
<p>实际上被当作如下处理:</p>
<pre><code class="language-rust ignore">fn generic&lt;T: Sized&gt;(t: T) {
// --snip--
}</code></pre>
<p>泛型函数默认只能用于在编译时已知大小的类型。然而可以使用如下特殊语法来放宽这个限制:</p>
<pre><code class="language-rust ignore">fn generic&lt;T: ?Sized&gt;(t: &amp;T) {
// --snip--
}</code></pre>
<p><code>?Sized</code> 上的 trait bound 意味着 “<code>T</code> 可能是也可能不是 <code>Sized</code>” 同时这个注解会覆盖泛型类型必须在编译时拥有固定大小的默认规则。这种意义的 <code>?Trait</code> 语法只能用于 <code>Sized</code> ,而不能用于任何其他 trait。</p>
<p>另外注意我们将 <code>t</code> 参数的类型从 <code>T</code> 变为了 <code>&amp;T</code>:因为其类型可能不是 <code>Sized</code> 的,所以需要将其置于某种指针之后。在这个例子中选择了引用。</p>
<p>接下来,让我们讨论一下函数和闭包!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="高级函数与闭包"><a class="header" href="#高级函数与闭包">高级函数与闭包</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch20-05-advanced-functions-and-closures.md">ch20-05-advanced-functions-and-closures.md</a>
<br>
commit 21cf840842bdf768a798869f06373c96c1cc5122</p>
</blockquote>
<p>本部分将探索一些有关函数和闭包的高级功能,这包括函数指针以及返回值闭包。</p>
<h3 id="函数指针"><a class="header" href="#函数指针">函数指针</a></h3>
<p>我们讨论过了如何向函数传递闭包;也可以向函数传递常规函数!这个技术在我们希望传递已经定义的函数而不是重新定义闭包作为参数时很有用。函数满足类型 <code>fn</code>(小写的 f不要与闭包 trait 的 <code>Fn</code> 相混淆。<code>fn</code> 被称为 <strong>函数指针</strong><em>function pointer</em>)。通过函数指针允许我们使用函数作为另一个函数的参数。</p>
<p>指定参数为函数指针的语法类似于闭包,如示例 19-27 所示,这里定义了一个 <code>add_one</code> 函数将其参数加一。<code>do_twice</code> 函数获取两个参数:一个指向任何获取一个 <code>i32</code> 参数并返回一个 <code>i32</code> 的函数指针,和一个 <code>i32</code> 值。<code>do_twice</code> 函数传递 <code>arg</code> 参数调用 <code>f</code> 函数两次,接着将两次函数调用的结果相加。<code>main</code> 函数使用 <code>add_one</code><code>5</code> 作为参数调用 <code>do_twice</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn add_one(x: i32) -&gt; i32 {
x + 1
}
fn do_twice(f: fn(i32) -&gt; i32, arg: i32) -&gt; i32 {
f(arg) + f(arg)
}
fn main() {
let answer = do_twice(add_one, 5);
println!("The answer is: {answer}");
}</code></pre></pre>
<p><span class="caption">示例 19-27: 使用 <code>fn</code> 类型接受函数指针作为参数</span></p>
<p>这会打印出 <code>The answer is: 12</code><code>do_twice</code> 中的 <code>f</code> 被指定为一个接受一个 <code>i32</code> 参数并返回 <code>i32</code><code>fn</code>。接着就可以在 <code>do_twice</code> 函数体中调用 <code>f</code>。在 <code>main</code> 中,可以将函数名 <code>add_one</code> 作为第一个参数传递给 <code>do_twice</code></p>
<p>不同于闭包,<code>fn</code> 是一个类型而不是一个 trait所以直接指定 <code>fn</code> 作为参数而不是声明一个带有 <code>Fn</code> 作为 trait bound 的泛型参数。</p>
<p>函数指针实现了所有三个闭包 trait<code>Fn</code><code>FnMut</code><code>FnOnce</code>),所以总是可以在调用期望闭包的函数时传递函数指针作为参数。倾向于编写使用泛型和闭包 trait 的函数,这样它就能接受函数或闭包作为参数。</p>
<p>一个只期望接受 <code>fn</code> 而不接受闭包的情况的例子是与不存在闭包的外部代码交互时C 语言的函数可以接受函数作为参数,但 C 语言没有闭包。</p>
<p>作为一个既可以使用内联定义的闭包又可以使用命名函数的例子,让我们看看一个 <code>map</code> 的应用。使用 <code>map</code> 函数将一个数字 vector 转换为一个字符串 vector就可以使用闭包比如这样</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let list_of_numbers = vec![1, 2, 3];
let list_of_strings: Vec&lt;String&gt; =
list_of_numbers.iter().map(|i| i.to_string()).collect();
<span class="boring">}</span></code></pre></pre>
<p>或者可以将函数作为 <code>map</code> 的参数来代替闭包,像是这样:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> let list_of_numbers = vec![1, 2, 3];
let list_of_strings: Vec&lt;String&gt; =
list_of_numbers.iter().map(ToString::to_string).collect();
<span class="boring">}</span></code></pre></pre>
<p>注意这里必须使用 <a href="ch20-03-advanced-traits.html#%E9%AB%98%E7%BA%A7-trait">“高级 trait”</a> 部分讲到的完全限定语法,因为存在多个叫做 <code>to_string</code> 的函数;这里使用了定义于 <code>ToString</code> trait 的 <code>to_string</code> 函数,标准库为所有实现了 <code>Display</code> 的类型实现了这个 trait。</p>
<p>回忆一下第六章 <a href="ch06-01-defining-an-enum.html#%E6%9E%9A%E4%B8%BE%E5%80%BC">“枚举值”</a> 部分中定义的每一个枚举成员也变成了一个构造函数。我们可以使用这些构造函数作为实现了闭包 trait 的函数指针,这意味着可以指定构造函数作为接受闭包的方法的参数,如下:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
</span> enum Status {
Value(u32),
Stop,
}
let list_of_statuses: Vec&lt;Status&gt; = (0u32..20).map(Status::Value).collect();
<span class="boring">}</span></code></pre></pre>
<p>这里创建了 <code>Status::Value</code> 实例,它通过 <code>map</code> 用范围的每一个 <code>u32</code> 值调用 <code>Status::Value</code> 的初始化函数。一些人倾向于函数风格,一些人喜欢闭包。这两种形式最终都会产生同样的代码,所以请使用对你来说更明白的形式吧。</p>
<h3 id="返回闭包"><a class="header" href="#返回闭包">返回闭包</a></h3>
<p>闭包表现为 trait这意味着不能直接返回闭包。对于大部分需要返回 trait 的情况,可以使用实现了期望返回的 trait 的具体类型来替代函数的返回值。但是这不能用于闭包,因为它们没有一个可返回的具体类型;例如不允许使用函数指针 <code>fn</code> 作为返回值类型。</p>
<p>这段代码尝试直接返回闭包,它并不能编译:</p>
<pre><code class="language-rust ignore does_not_compile">fn returns_closure() -&gt; dyn Fn(i32) -&gt; i32 {
|x| x + 1
}</code></pre>
<p>编译器给出的错误是:</p>
<pre><code class="language-console">$ cargo build
Compiling functions-example v0.1.0 (file:///projects/functions-example)
error[E0746]: return type cannot have an unboxed trait object
--&gt; src/lib.rs:1:25
|
1 | fn returns_closure() -&gt; dyn Fn(i32) -&gt; i32 {
| ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
help: consider returning an `impl Trait` instead of a `dyn Trait`
|
1 | fn returns_closure() -&gt; impl Fn(i32) -&gt; i32 {
| ~~~~
help: alternatively, box the return type, and wrap all of the returned values in `Box::new`
|
1 ~ fn returns_closure() -&gt; Box&lt;dyn Fn(i32) -&gt; i32&gt; {
2 ~ Box::new(|x| x + 1)
|
For more information about this error, try `rustc --explain E0746`.
error: could not compile `functions-example` (lib) due to 1 previous error
</code></pre>
<p>错误又一次指向了 <code>Sized</code> traitRust 并不知道需要多少空间来储存闭包。不过我们在上一部分见过这种情况的解决办法:可以使用 trait 对象:</p>
<pre><code class="language-rust noplayground">fn returns_closure() -&gt; Box&lt;dyn Fn(i32) -&gt; i32&gt; {
Box::new(|x| x + 1)
}</code></pre>
<p>这段代码正好可以编译。关于 trait 对象的更多内容,请回顾第十八章的 <a href="ch18-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>
<p>接下来让我们学习宏!</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="宏"><a class="header" href="#宏"></a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch20-06-macros.md">ch20-06-macros.md</a>
<br>
commit 95e931170404cb98d476b19017cbbdbc00d0834d</p>
</blockquote>
<p>我们已经在本书中使用过像 <code>println!</code> 这样的宏了,不过还没完全探索什么是宏以及它是如何工作的。<strong></strong><em>Macro</em>)指的是 Rust 中一系列的功能:使用 <code>macro_rules!</code><strong>声明</strong><em>Declarative</em>)宏,和三种 <strong>过程</strong><em>Procedural</em>)宏:</p>
<ul>
<li>自定义 <code>#[derive]</code> 宏在结构体和枚举上指定通过 <code>derive</code> 属性添加的代码</li>
<li>类属性Attribute-like宏定义可用于任意项的自定义属性</li>
<li>类函数宏看起来像函数不过作用于作为参数传递的 token</li>
</ul>
<p>我们会依次讨论每一种宏,不过首要的是,为什么已经有了函数还需要宏呢?</p>
<h3 id="宏和函数的区别"><a class="header" href="#宏和函数的区别">宏和函数的区别</a></h3>
<p>从根本上来说,宏是一种为写其他代码而写代码的方式,即所谓的 <strong>元编程</strong><em>metaprogramming</em>)。在附录 C 中会探讨 <code>derive</code> 属性,其生成各种 trait 的实现。我们也在本书中使用过 <code>println!</code> 宏和 <code>vec!</code> 宏。所有的这些宏以 <strong>展开</strong> 的方式来生成比你所手写出的更多的代码。</p>
<p>元编程对于减少大量编写和维护的代码是非常有用的,它也扮演了函数扮演的角色。但宏有一些函数所没有的附加能力。</p>
<p>一个函数签名必须声明函数参数个数和类型。相比之下,宏能够接收不同数量的参数:用一个参数调用 <code>println!("hello")</code> 或用两个参数调用 <code>println!("hello {}", name)</code> 。而且,宏可以在编译器翻译代码前展开,例如,宏可以在一个给定类型上实现 trait。而函数则不行因为函数是在运行时被调用同时 trait 需要在编译时实现。</p>
<p>实现宏不如实现函数的一面是宏定义要比函数定义更复杂,因为你正在编写生成 Rust 代码的 Rust 代码。由于这样的间接性,宏定义通常要比函数定义更难阅读、理解以及维护。</p>
<p>宏和函数的最后一个重要的区别是:在一个文件里调用宏 <strong>之前</strong> 必须定义它,或将其引入作用域,而函数则可以在任何地方定义和调用。</p>
<h3 id="使用-macro_rules-的声明宏用于通用元编程"><a class="header" href="#使用-macro_rules-的声明宏用于通用元编程">使用 <code>macro_rules!</code> 的声明宏用于通用元编程</a></h3>
<p>Rust 最常用的宏形式是 <strong>声明宏</strong><em>declarative macros</em>)。它们有时也被称为 “macros by example”、“<code>macro_rules!</code> 宏” 或者就是 “macros”。其核心概念是声明宏允许我们编写一些类似 Rust <code>match</code> 表达式的代码。正如在第六章讨论的那样,<code>match</code> 表达式是控制结构,其接收一个表达式,与表达式的结果进行模式匹配,然后根据模式匹配执行相关代码。宏也将一个值和包含相关代码的模式进行比较;此种情况下,该值是传递给宏的 Rust 源代码字面值,模式用于和前面提到的源代码字面值进行比较,每个模式的相关代码会替换传递给宏的代码。所有这一切都发生于编译时。</p>
<p>可以使用 <code>macro_rules!</code> 来定义宏。让我们通过查看 <code>vec!</code> 宏定义来探索如何使用 <code>macro_rules!</code> 结构。第八章讲述了如何使用 <code>vec!</code> 宏来生成一个给定值的 vector。例如下面的宏用三个整数创建一个 vector</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let v: Vec&lt;u32&gt; = vec![1, 2, 3];
<span class="boring">}</span></code></pre></pre>
<p>也可以使用 <code>vec!</code> 宏来构造两个整数的 vector 或五个字符串 slice 的 vector。但却无法使用函数做相同的事情因为我们无法预先知道参数值的数量和类型。</p>
<p>在示例 19-28 中展示了一个 <code>vec!</code> 稍微简化的定义。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">#[macro_export]
macro_rules! vec {
( $( $x:expr ),* ) =&gt; {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}</code></pre>
<p><span class="caption">示例 19-28: 一个 <code>vec!</code> 宏定义的简化版本</span></p>
<blockquote>
<p>注意:标准库中实际定义的 <code>vec!</code> 包括预分配适当量的内存的代码。这部分为代码优化,为了让示例简化,此处并没有包含在内。</p>
</blockquote>
<p><code>#[macro_export]</code> 注解表明只要导入了定义这个宏的 crate该宏就应该是可用的。如果没有该注解这个宏不能被引入作用域。</p>
<p>接着使用 <code>macro_rules!</code> 和宏名称开始宏定义,且所定义的宏并 <strong>不带</strong> 感叹号。名字后跟大括号表示宏定义体,在该例中宏名称是 <code>vec</code></p>
<p><code>vec!</code> 宏的结构和 <code>match</code> 表达式的结构类似。此处有一个分支模式 <code>( $( $x:expr ),* )</code> ,后跟 <code>=&gt;</code> 以及和模式相关的代码块。如果模式匹配,该相关代码块将被执行。这里这个宏只有一个模式,那就只有一个有效匹配方向,其他任何模式方向(译者注:不匹配这个模式)都会导致错误。更复杂的宏会有多个分支模式。</p>
<p>宏定义中有效模式语法和在第十九章提及的模式语法是不同的,因为宏模式所匹配的是 Rust 代码结构而不是值。回过头来检查下示例 19-28 中模式片段什么意思。对于全部的宏模式语法,请查阅 <a href="https://doc.rust-lang.org/reference/macros-by-example.html">Rust 参考</a></p>
<p>首先,一对括号包含了整个模式。我们使用美元符号(<code>$</code>)在宏系统中声明一个变量来包含匹配该模式的 Rust 代码。美元符号明确表明这是一个宏变量而不是普通 Rust 变量。之后是一对括号,其捕获了符合括号内模式的值用以在替代代码中使用。<code>$()</code> 内则是 <code>$x:expr</code> ,其匹配 Rust 的任意表达式,并将该表达式命名为 <code>$x</code></p>
<p><code>$()</code> 之后的逗号说明一个可有可无的逗号分隔符可以出现在 <code>$()</code> 所匹配的代码之后。紧随逗号之后的 <code>*</code> 说明该模式匹配零个或更多个 <code>*</code> 之前的任何模式。</p>
<p>当以 <code>vec![1, 2, 3];</code> 调用宏时,<code>$x</code> 模式与三个表达式 <code>1</code><code>2</code><code>3</code> 进行了三次匹配。</p>
<p>现在让我们来看看与此分支模式相关联的代码块中的模式:匹配到模式中的<code>$()</code>的每一部分,都会在(<code>=&gt;</code>右侧)<code>$()*</code> 里生成<code>temp_vec.push($x)</code>,生成零次还是多次取决于模式匹配到多少次。<code>$x</code> 由每个与之相匹配的表达式所替换。当以 <code>vec![1, 2, 3];</code> 调用该宏时,替换该宏调用所生成的代码会是下面这样:</p>
<pre><code class="language-rust ignore">{
let mut temp_vec = Vec::new();
temp_vec.push(1);
temp_vec.push(2);
temp_vec.push(3);
temp_vec
}</code></pre>
<p>我们已经定义了一个宏,其可以接收任意数量和类型的参数,同时可以生成能够创建包含指定元素的 vector 的代码。</p>
<p>请查阅在线文档或其他资源,如 <a href="https://veykril.github.io/tlborm/">“The Little Book of Rust Macros”</a> 来更多地了解如何写宏,该书由 Daniel Keep 开始编写并由 Lukas Wirth 继续维护。</p>
<h3 id="用于从属性生成代码的过程宏"><a class="header" href="#用于从属性生成代码的过程宏">用于从属性生成代码的过程宏</a></h3>
<p>第二种形式的宏被称为 <strong>过程宏</strong><em>procedural macros</em>),因为它们更像函数(一种过程类型)。过程宏接收 Rust 代码作为输入在这些代码上进行操作然后产生另一些代码作为输出而非像声明式宏那样匹配对应模式然后以另一部分代码替换当前代码。有三种类型的过程宏自定义派生derive类属性和类函数不过它们的工作方式都类似。</p>
<p>创建过程宏时,其定义必须驻留在它们自己的具有特殊 crate 类型的 crate 中。这么做出于复杂的技术原因,将来我们希望能够消除这些限制。在示例 19-29 中展示了如何定义过程宏,其中 <code>some_attribute</code> 是一个使用特定宏变体的占位符。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore">use proc_macro;
#[some_attribute]
pub fn some_name(input: TokenStream) -&gt; TokenStream {
}</code></pre>
<p><span class="caption">示例 19-29: 一个定义过程宏的例子</span></p>
<p>定义过程宏的函数接收一个 TokenStream 作为输入并生成 TokenStream 作为输出。<code>TokenStream</code> 是定义于<code>proc_macro</code> crate 里代表一系列 token 的类型Rust 默认携带了<code>proc_macro</code> crate。这就是宏的核心宏所处理的源代码组成了输入 <code>TokenStream</code>,宏生成的代码是输出 <code>TokenStream</code>。函数上还有一个属性;这个属性指明了我们创建的过程宏的类型。在同一 crate 中可以有多种的过程宏。</p>
<p>让我们看看不同种类的程序宏。我们将从一个自定义的派生宏开始,然后解释使其他形式不同的小差异。</p>
<h3 id="如何编写自定义-derive-宏"><a class="header" href="#如何编写自定义-derive-宏">如何编写自定义 <code>derive</code></a></h3>
<p>让我们创建一个 <code>hello_macro</code> crate其包含名为 <code>HelloMacro</code> 的 trait 和关联函数 <code>hello_macro</code>。不同于让用户为其每一个类型实现 <code>HelloMacro</code> trait我们将会提供一个过程式宏以便用户可以使用 <code>#[derive(HelloMacro)]</code> 注解它们的类型来得到 <code>hello_macro</code> 函数的默认实现。该默认实现会打印 <code>Hello, Macro! My name is TypeName!</code>,其中 <code>TypeName</code> 为定义了 trait 的类型名。换言之,我们会创建一个 crate使程序员能够写类似示例 19-30 中的代码。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use hello_macro::HelloMacro;
use hello_macro_derive::HelloMacro;
#[derive(HelloMacro)]
struct Pancakes;
fn main() {
Pancakes::hello_macro();
}</code></pre>
<p><span class="caption">示例 19-30: crate 用户所写的能够使用过程式宏的代码</span></p>
<p>运行该代码将会打印 <code>Hello, Macro! My name is Pancakes!</code> 第一步是像下面这样新建一个库 crate</p>
<pre><code class="language-console">$ cargo new hello_macro --lib
</code></pre>
<p>接下来,会定义 <code>HelloMacro</code> trait 以及其关联函数:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub trait HelloMacro {
fn hello_macro();
}</code></pre>
<p>现在有了一个包含函数的 trait。此时crate 用户可以实现该 trait 以达到其期望的功能,像这样:</p>
<pre><code class="language-rust ignore">use hello_macro::HelloMacro;
struct Pancakes;
impl HelloMacro for Pancakes {
fn hello_macro() {
println!("Hello, Macro! My name is Pancakes!");
}
}
fn main() {
Pancakes::hello_macro();
}</code></pre>
<p>然而,他们需要为每一个他们想使用 <code>hello_macro</code> 的类型编写实现的代码块。我们希望为其节约这些工作。</p>
<p>另外,我们也无法为 <code>hello_macro</code> 函数提供一个能够打印实现了该 trait 的类型的名字的默认实现Rust 没有反射的能力,因此其无法在运行时获取类型名。我们需要一个在编译时生成代码的宏。</p>
<p>下一步是定义过程式宏。在编写本部分时,过程式宏必须在其自己的 crate 内。该限制最终可能被取消。构造 crate 和其中宏的惯例如下:对于一个 <code>foo</code> 的包来说,一个自定义的派生过程宏的包被称为 <code>foo_derive</code> 。在 <code>hello_macro</code> 项目中新建名为 <code>hello_macro_derive</code> 的包。</p>
<pre><code class="language-console">$ cargo new hello_macro_derive --lib
</code></pre>
<p>由于两个 crate 紧密相关,因此在 <code>hello_macro</code> 包的目录下创建过程式宏的 crate。如果改变在 <code>hello_macro</code> 中定义的 trait同时也必须改变在 <code>hello_macro_derive</code> 中实现的过程式宏。这两个包需要分别发布,编程人员如果使用这些包,则需要同时添加这两个依赖并将其引入作用域。我们也可以只用 <code>hello_macro</code> 包而将 <code>hello_macro_derive</code> 作为一个依赖,并重新导出过程式宏的代码。但现在我们组织项目的方式使编程人员在无需 <code>derive</code> 功能时也能够单独使用 <code>hello_macro</code></p>
<p>我们需要声明 <code>hello_macro_derive</code> crate 是过程宏 (proc-macro) crate。我们还需要 <code>syn</code><code>quote</code> crate 中的功能,正如你即将看到的,需要将它们加到依赖中。将下面的代码加入到 <code>hello_macro_derive</code><em>Cargo.toml</em> 文件中。</p>
<p><span class="filename">文件名hello_macro_derive/Cargo.toml</span></p>
<pre><code class="language-toml">[lib]
proc-macro = true
[dependencies]
syn = "2.0"
quote = "1.0"
</code></pre>
<p>为定义一个过程式宏,请将示例 19-31 中的代码放在 <code>hello_macro_derive</code> crate 的 <em>src/lib.rs</em> 文件里面。注意这段代码在我们添加 <code>impl_hello_macro</code> 函数的定义之前是无法编译的。</p>
<p><span class="filename">文件名hello_macro_derive/src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile">use proc_macro::TokenStream;
use quote::quote;
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -&gt; TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let ast = syn::parse(input).unwrap();
// Build the trait implementation
impl_hello_macro(&amp;ast)
}</code></pre>
<p><span class="caption">示例 19-31: 大多数过程式宏处理 Rust 代码时所需的代码</span></p>
<p>注意我们将代码分成了<code>hello_macro_derive</code><code>impl_hello_macro</code> 两个函数,前者负责解析 <code>TokenStream</code>,后者负责转换语法树:这使得编写过程宏更方便。几乎你看到或者创建的每一个过程宏的外部函数(这里是<code>hello_macro_derive</code>)中的代码都跟这里是一样的。你放入内部函数(这里是<code>impl_hello_macro</code>)中的代码根据你的过程宏的设计目的会有所不同。</p>
<p>现在,我们已经引入了三个新的 crate<code>proc_macro</code><a href="https://crates.io/crates/syn"><code>syn</code></a><a href="https://crates.io/crates/quote"><code>quote</code></a> 。Rust 自带 <code>proc_macro</code> crate因此无需将其加到 <em>Cargo.toml</em> 文件的依赖中。<code>proc_macro</code> crate 是编译器用来读取和操作我们 Rust 代码的 API。</p>
<p><code>syn</code> crate 将字符串中的 Rust 代码解析成为一个可以操作的数据结构。<code>quote</code> 则将 <code>syn</code> 解析的数据结构转换回 Rust 代码。这些 crate 让解析任何我们所要处理的 Rust 代码变得更简单:为 Rust 编写整个的解析器并不是一件简单的工作。</p>
<p>当用户在一个类型上指定 <code>#[derive(HelloMacro)]</code> 时,<code>hello_macro_derive</code> 函数将会被调用。因为我们已经使用 <code>proc_macro_derive</code> 及其指定名称<code>HelloMacro</code><code>hello_macro_derive</code> 函数进行了注解,指定名称<code>HelloMacro</code>就是 trait 名,这是大多数过程宏遵循的习惯。</p>
<p>该函数首先将来自 <code>TokenStream</code><code>input</code> 转换为一个我们可以解释和操作的数据结构。这正是 <code>syn</code> 派上用场的地方。<code>syn</code> 中的 <code>parse</code> 函数获取一个 <code>TokenStream</code> 并返回一个表示解析出 Rust 代码的 <code>DeriveInput</code> 结构体。示例 19-32 展示了从字符串 <code>struct Pancakes;</code> 中解析出来的 <code>DeriveInput</code> 结构体的相关部分:</p>
<pre><code class="language-rust ignore">DeriveInput {
// --snip--
ident: Ident {
ident: "Pancakes",
span: #0 bytes(95..103)
},
data: Struct(
DataStruct {
struct_token: Struct,
fields: Unit,
semi_token: Some(
Semi
)
}
)
}</code></pre>
<p><span class="caption">示例 19-32: 解析示例 19-30 中带有宏属性的代码时得到的 <code>DeriveInput</code> 实例</span></p>
<p>该结构体的字段展示了我们解析的 Rust 代码是一个类单元结构体,其 <code>ident</code>identifier表示名字<code>Pancakes</code>。该结构体里面有更多字段描述了所有类型的 Rust 代码,查阅 <a href="https://docs.rs/syn/1.0/syn/struct.DeriveInput.html"><code>syn</code><code>DeriveInput</code> 的文档</a> 以获取更多信息。</p>
<p>很快我们将定义 <code>impl_hello_macro</code> 函数,其用于构建所要包含在内的 Rust 新代码。但在此之前,注意其输出也是 <code>TokenStream</code>。所返回的 <code>TokenStream</code> 会被加到我们的 crate 用户所写的代码中,因此,当用户编译他们的 crate 时,他们会通过修改后的 <code>TokenStream</code> 获取到我们所提供的额外功能。</p>
<p>你可能也注意到了,当调用 <code>syn::parse</code> 函数失败时,我们用 <code>unwrap</code> 来使 <code>hello_macro_derive</code> 函数 panic。在错误时 panic 对过程宏来说是必须的,因为 <code>proc_macro_derive</code> 函数必须返回 <code>TokenStream</code> 而不是 <code>Result</code>,以此来符合过程宏的 API。这里选择用 <code>unwrap</code> 来简化了这个例子;在生产代码中,则应该通过 <code>panic!</code><code>expect</code> 来提供关于发生何种错误的更加明确的错误信息。</p>
<p>现在我们有了将注解的 Rust 代码从 <code>TokenStream</code> 转换为 <code>DeriveInput</code> 实例的代码,让我们来创建在注解类型上实现 <code>HelloMacro</code> trait 的代码,如示例 19-33 所示。</p>
<p><span class="filename">文件名hello_macro_derive/src/lib.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use proc_macro::TokenStream;
</span><span class="boring">use quote::quote;
</span><span class="boring">
</span><span class="boring">#[proc_macro_derive(HelloMacro)]
</span><span class="boring">pub fn hello_macro_derive(input: TokenStream) -&gt; TokenStream {
</span><span class="boring"> // Construct a representation of Rust code as a syntax tree
</span><span class="boring"> // that we can manipulate
</span><span class="boring"> let ast = syn::parse(input).unwrap();
</span><span class="boring">
</span><span class="boring"> // Build the trait implementation
</span><span class="boring"> impl_hello_macro(&amp;ast)
</span><span class="boring">}
</span><span class="boring">
</span>fn impl_hello_macro(ast: &amp;syn::DeriveInput) -&gt; TokenStream {
let name = &amp;ast.ident;
let gen = quote! {
impl HelloMacro for #name {
fn hello_macro() {
println!("Hello, Macro! My name is {}!", stringify!(#name));
}
}
};
gen.into()
}</code></pre>
<p><span class="caption">示例 19-33: 使用解析过的 Rust 代码实现 <code>HelloMacro</code> trait</span></p>
<p>我们得到一个包含以 <code>ast.ident</code> 作为注解类型名字(标识符)的 <code>Ident</code> 结构体实例。示例 19-32 中的结构体表明当 <code>impl_hello_macro</code> 函数运行于示例 19-30 中的代码上时 <code>ident</code> 字段的值是 <code>"Pancakes"</code>。因此,示例 19-33 中 <code>name</code> 变量会包含一个 <code>Ident</code> 结构体的实例,当打印时,会是字符串 <code>"Pancakes"</code>,也就是示例 19-30 中结构体的名称。</p>
<p><code>quote!</code> 宏能让我们编写希望返回的 Rust 代码。<code>quote!</code> 宏执行的直接结果并不是编译器所期望的所以需要转换为 <code>TokenStream</code>。为此需要调用 <code>into</code> 方法它会消费这个中间表示intermediate representationIR并返回所需的 <code>TokenStream</code> 类型值。</p>
<p>这个宏也提供了一些非常酷的模板机制;我们可以写 <code>#name</code> ,然后 <code>quote!</code> 会以名为 <code>name</code> 的变量值来替换它。你甚至可以做一些类似常用宏那样的重复代码的工作。查阅 <a href="https://docs.rs/quote"><code>quote</code> crate 的文档</a> 来获取详尽的介绍。</p>
<p>我们期望我们的过程式宏能够为通过 <code>#name</code> 获取到的用户注解类型生成 <code>HelloMacro</code> trait 的实现。该 trait 的实现有一个函数 <code>hello_macro</code> ,其函数体包括了我们期望提供的功能:打印 <code>Hello, Macro! My name is</code> 和注解的类型名。</p>
<p>此处所使用的 <code>stringify!</code> 为 Rust 内置宏。其接收一个 Rust 表达式,如 <code>1 + 2</code> ,然后在编译时将表达式转换为一个字符串常量,如 <code>"1 + 2"</code> 。这与 <code>format!</code><code>println!</code> 是不同的,它计算表达式并将结果转换为 <code>String</code> 。有一种可能的情况是,所输入的 <code>#name</code> 可能是一个需要打印的表达式,因此我们用 <code>stringify!</code><code>stringify!</code> 也能通过在编译时将 <code>#name</code> 转换为字符串来节省内存分配。</p>
<p>此时,<code>cargo build</code> 应该都能成功编译 <code>hello_macro</code><code>hello_macro_derive</code> 。我们将这些 crate 连接到示例 19-30 的代码中来看看过程宏的行为!在 <em>projects</em> 目录下用 <code>cargo new pancakes</code> 命令新建一个二进制项目。需要将 <code>hello_macro</code><code>hello_macro_derive</code> 作为依赖加到 <code>pancakes</code> 包的 <em>Cargo.toml</em> 文件中去。如果你正将 <code>hello_macro</code><code>hello_macro_derive</code> 的版本发布到 <a href="https://crates.io/">crates.io</a> 上,其应为常规依赖;如果不是,则可以像下面这样将其指定为 <code>path</code> 依赖:</p>
<pre><code class="language-toml">hello_macro = { path = "../hello_macro" }
hello_macro_derive = { path = "../hello_macro/hello_macro_derive" }
</code></pre>
<p>把示例 19-30 中的代码放在 <em>src/main.rs</em> ,然后执行 <code>cargo run</code>:其应该打印 <code>Hello, Macro! My name is Pancakes!</code>。其包含了该过程宏中 <code>HelloMacro</code> trait 的实现,而无需 <code>pancakes</code> crate 实现它;<code>#[derive(HelloMacro)]</code> 增加了该 trait 实现。</p>
<p>接下来,让我们探索一下其他类型的过程宏与自定义派生宏有何区别。</p>
<h3 id="类属性宏"><a class="header" href="#类属性宏">类属性宏</a></h3>
<p>类属性宏与自定义派生宏相似,不同的是 <code>derive</code> 属性生成代码,它们(类属性宏)能让你创建新的属性。它们也更为灵活;<code>derive</code> 只能用于结构体和枚举;属性还可以用于其它的项,比如函数。作为一个使用类属性宏的例子,可以创建一个名为 <code>route</code> 的属性用于注解 web 应用程序框架web application framework的函数</p>
<pre><code class="language-rust ignore">#[route(GET, "/")]
fn index() {</code></pre>
<p><code>#[route]</code> 属性将由框架本身定义为一个过程宏。其宏定义的函数签名看起来像这样:</p>
<pre><code class="language-rust ignore">#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -&gt; TokenStream {</code></pre>
<p>这里有两个 <code>TokenStream</code> 类型的参数;第一个用于属性内容本身,也就是 <code>GET, "/"</code> 部分。第二个是属性所标记的项:在本例中,是 <code>fn index() {}</code> 和剩下的函数体。</p>
<p>除此之外,类属性宏与自定义派生宏工作方式一致:创建 <code>proc-macro</code> crate 类型的 crate 并实现希望生成代码的函数!</p>
<h3 id="类函数宏"><a class="header" href="#类函数宏">类函数宏</a></h3>
<p>类函数Function-like宏的定义看起来像函数调用的宏。类似于 <code>macro_rules!</code>,它们比函数更灵活;例如,可以接受未知数量的参数。然而 <code>macro_rules!</code> 宏只能使用之前 <a href="ch20-06-macros.html#%E4%BD%BF%E7%94%A8-macro_rules-%E7%9A%84%E5%A3%B0%E6%98%8E%E5%AE%8F%E7%94%A8%E4%BA%8E%E9%80%9A%E7%94%A8%E5%85%83%E7%BC%96%E7%A8%8B">“使用 <code>macro_rules!</code> 的声明宏用于通用元编程”</a> 介绍的类匹配的语法定义。类函数宏获取 <code>TokenStream</code> 参数,其定义使用 Rust 代码操纵 <code>TokenStream</code>,就像另两种过程宏一样。一个类函数宏例子是可以像这样被调用的 <code>sql!</code> 宏:</p>
<pre><code class="language-rust ignore">let sql = sql!(SELECT * FROM posts WHERE id=1);</code></pre>
<p>这个宏会解析其中的 SQL 语句并检查其是否是句法正确的,这是比 <code>macro_rules!</code> 可以做到的更为复杂的处理。<code>sql!</code> 宏应该被定义为如此:</p>
<pre><code class="language-rust ignore">#[proc_macro]
pub fn sql(input: TokenStream) -&gt; TokenStream {</code></pre>
<p>这类似于自定义派生宏的签名:获取括号中的 token并返回希望生成的代码。</p>
<h2 id="总结-18"><a class="header" href="#总结-18">总结</a></h2>
<p>好的!现在我们学习了 Rust 并不常用但在特定情况下你可能用得着的功能。我们介绍了很多复杂的主题,这样若你在错误信息提示或阅读他人代码时遇到它们,至少可以说之前已经见过这些概念和语法了。你可以使用本章作为一个解决方案的参考。</p>
<p>接下来,我们将再开始一个项目,将本书所学的所有内容付与实践!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="最后的项目构建多线程-web-server"><a class="header" href="#最后的项目构建多线程-web-server">最后的项目:构建多线程 web server</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch21-00-final-project-a-web-server.md">ch21-00-final-project-a-web-server.md</a>
<br>
commit 5df6909c57b3ba55f156a4122a42b805436de90c</p>
</blockquote>
<p>这是一次漫长的旅途,不过我们到达了本书的结束。在本章中,我们将一同构建另一个项目,来展示最后几章所学,同时复习更早的章节。</p>
<p>作为最后的项目,我们将要实现一个返回 “hello” 的 web server它在浏览器中看起来就如图例 20-1 所示:</p>
<p><img src="img/trpl20-01.png" alt="hello from rust" /></p>
<p><span class="caption">图例 20-1: 我们最后将一起分享的项目</span></p>
<p>如下是构建 web server 的计划:</p>
<ol>
<li>学习一些 TCP 与 HTTP 知识</li>
<li>在套接字socket上监听 TCP 请求</li>
<li>解析少量的 HTTP 请求</li>
<li>创建一个合适的 HTTP 响应</li>
<li>通过线程池改善 server 的吞吐量</li>
</ol>
<p>不过在开始之前,需要提到一点细节:这里使用的方法并不是使用 Rust 构建 web server 最好的方法。<a href="https://crates.io/">crates.io</a> 上有很多可用于生产环境的 crate它们提供了比我们所要编写的更为完整的 web server 和线程池实现。然而,本章的目的在于学习,而不是走捷径。因为 Rust 是一个系统编程语言,我们能够选择处理什么层次的抽象,并能够选择比其他语言可能或可用的层次更低的层次。因此我们将自己编写一个基础的 HTTP server 和线程池,以便学习将来可能用到的 crate 背后的通用理念和技术。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="构建单线程-web-server"><a class="header" href="#构建单线程-web-server">构建单线程 web server</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch21-01-single-threaded.md">ch21-01-single-threaded.md</a>
<br>
commit 5df6909c57b3ba55f156a4122a42b805436de90c</p>
</blockquote>
<p>首先让我们创建一个可运行的单线程 web server不过在开始之前我们将快速了解一下构建 web server 所涉及到的协议。这些协议的细节超出了本书的范畴,不过一个简单的概括会提供我们所需的信息。</p>
<p>web server 中涉及到的两个主要协议是 <strong>超文本传输协议</strong><em>Hypertext Transfer Protocol</em><em>HTTP</em>)和 <strong>传输控制协议</strong><em>Transmission Control Protocol</em><em>TCP</em>)。这两者都是 <strong>请求 - 响应</strong><em>request-response</em>)协议,也就是说,有 <strong>客户端</strong><em>client</em>)来初始化请求,并有 <strong>服务端</strong><em>server</em>)监听请求并向客户端提供响应。请求与响应的内容由协议本身定义。</p>
<p>TCP 是一个底层协议,它描述了信息如何从一个 server 到另一个的细节不过其并不指定信息是什么。HTTP 构建于 TCP 之上,它定义了请求和响应的内容。为此,技术上讲可将 HTTP 用于其他协议之上不过对于绝大部分情况HTTP 通过 TCP 传输。我们将要做的就是处理 TCP 和 HTTP 请求与响应的原始字节数据。</p>
<h3 id="监听-tcp-连接"><a class="header" href="#监听-tcp-连接">监听 TCP 连接</a></h3>
<p>我们的 web server 所需做的第一件事,是监听 TCP 连接。标准库提供了 <code>std::net</code> 模块处理这些功能。让我们一如既往新建一个项目:</p>
<pre><code class="language-console">$ cargo new hello
Created binary (application) `hello` project
$ cd hello
</code></pre>
<p>现在,在 <code>src/main.rs</code> 输入示例 20-1 中的代码,作为一个开始。这段代码会在地址 <code>127.0.0.1:7878</code> 上监听传入的 TCP 流。当获取到传入的流,它会打印出 <code>Connection established!</code></p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021">use std::net::TcpListener;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
println!("Connection established!");
}
}</code></pre></pre>
<p><span class="caption">示例 20-1: 监听传入的流并在接收到流时打印信息</span></p>
<p><code>TcpListener</code> 用于监听 TCP 连接。我们选择监听本地地址 <code>127.0.0.1:7878</code>。将这个地址拆开来看,冒号之前的部分是一个代表本机的 IP 地址(在每台计算机上,这个地址都指本机,并不特指作者的计算机),而 <code>7878</code> 是端口。选择这个端口出于两个原因:通常 HTTP 服务器不在这个端口上接受请求,所以它不太可能与你机器上运行的其它 web server 的端口冲突;而且 7878 在电话上打出来就是 "rust"(译者注:九宫格键盘上的英文)。</p>
<p>在这个场景中 <code>bind</code> 函数类似于 <code>new</code> 函数,在这里它返回一个新的 <code>TcpListener</code> 实例。这个函数叫做 <code>bind</code> 是因为在网络领域连接到要监听的端口称为“绑定到端口”“binding to a port”</p>
<p><code>bind</code> 函数返回 <code>Result&lt;T, E&gt;</code>,这表明绑定可能会失败。例如,监听 80 端口需要管理员权限(非管理员用户只能监听大于 1023 的端口),所以如果尝试监听 80 端口而没有管理员权限,则会绑定失败。再比如,如果我们运行这个程序的两个实例,并因此有两个实例监听同一个端口,那么绑定也将失败。我们是出于学习目的来编写一个基础的服务器,不用关心处理这类错误,而仅仅使用 <code>unwrap</code> 在出现这些情况时直接停止程序。</p>
<p><code>TcpListener</code><code>incoming</code> 方法返回一个迭代器,它提供了一系列的流(更准确的说是 <code>TcpStream</code> 类型的流)。<strong></strong><em>stream</em>)代表一个客户端和服务端之间打开的连接。<strong>连接</strong><em>connection</em>)代表客户端连接服务端、服务端生成响应以及服务端关闭连接的全部请求 / 响应过程。为此,我们会从 <code>TcpStream</code> 读取客户端发送了什么并接着向流发送响应以向客户端发回数据。总体来说,这个 <code>for</code> 循环会依次处理每个连接并产生一系列的流供我们处理。</p>
<p>目前,处理流的代码中也有一个 <code>unwrap</code> 调用,如果 <code>stream</code> 出现任何错误会终止程序;如果没有任何错误,则打印出信息。下一个例子中,我们将为成功的情况增加更多功能。当客户端连接到服务端时,<code>incoming</code> 方法是可能返回错误的,因为我们实际上不是在遍历连接,而是遍历 <strong>连接尝试</strong><em>connection attempts</em>)。连接的尝试可能会因为多种原因不能成功,大部分是操作系统相关的。例如,很多系统限制同时打开的连接数,超出数量限制的新连接尝试会产生错误,直到一些现有的连接关闭为止。</p>
<p>让我们试试这段代码!首先在终端执行 <code>cargo run</code>,接着在浏览器中打开 <code>127.0.0.1:7878</code>。浏览器会显示出看起来类似于“连接重置”“Connection reset”的错误信息因为 server 目前并没响应任何数据。如果我们观察终端,会发现当浏览器连接我们的服务端时,会打印出一系列的信息!</p>
<pre><code class="language-text"> Running `target/debug/hello`
Connection established!
Connection established!
Connection established!
</code></pre>
<p>有时,对于一次浏览器请求,可能会打印出多条信息;这可能是因为,浏览器在请求页面的同时,还请求了其他资源,比如出现在浏览器标签页开头的图标(<em>favicon.ico</em>)。</p>
<p>这也可能是因为浏览器尝试多次连接服务端,因为服务端没有响应任何数据。作为 <code>drop</code> 实现的一部分,当 <code>stream</code> 在循环的结尾离开作用域并被丢弃,其连接将被关闭。浏览器有时通过重连来处理关闭的连接,因为对于一般网站而言,这些问题可能是暂时的。这些都不重要;现在重要的是,我们成功的处理了 TCP 连接!</p>
<p>记得当运行完特定版本的代码后,使用 <span class="keystroke">ctrl-C</span> 来停止程序。并通过执行 <code>cargo run</code> 命令在做出最新的代码修改之后重启服务。</p>
<h3 id="读取请求"><a class="header" href="#读取请求">读取请求</a></h3>
<p>让我们实现读取来自浏览器请求的功能!为了分离“获取连接”以及“接下来对连接的操作”,我们将开始写一个新函数来处理连接。在这个新的 <code>handle_connection</code> 函数中,我们从 TCP 流中读取数据,并打印出来,以便观察浏览器发送过来的数据。将代码修改为如示例 20-2 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021">use std::{
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
};
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&amp;stream);
let http_request: Vec&lt;_&gt; = buf_reader
.lines()
.map(|result| result.unwrap())
.take_while(|line| !line.is_empty())
.collect();
println!("Request: {http_request:#?}");
}</code></pre></pre>
<p><span class="caption">示例 20-2: 读取 <code>TcpStream</code> 并打印数据</span></p>
<p>这里将 <code>std::io::prelude</code><code>std::io::BufReader</code> 引入作用域,来获取读写流所需的特定 trait。在 <code>main</code> 函数的 <code>for</code> 循环中,相比获取到连接时打印信息,现在调用新的 <code>handle_connection</code> 函数并向其传递 <code>stream</code></p>
<p><code>handle_connection</code> 中,我们新建了一个 <code>BufReader</code> 实例来封装一个 <code>stream</code> 的可变引用。<code>BufReader</code> 增加了缓存来替我们管理 <code>std::io::Read</code> trait 方法的调用。</p>
<p>我们创建了一个 <code>http_request</code> 变量来收集浏览器发送给服务端的请求行。这里增加了 <code>Vec&lt;_&gt;</code> 类型注解表明希望将这些行收集到一个 vector 中。</p>
<p><code>BufReader</code> 实现了 <code>std::io::BufRead</code> trait它提供了 <code>lines</code> 方法。<code>lines</code> 方法通过遇到换行符newline字节就切分数据流的方式返回一个 <code>Result&lt;String, std::io::Error&gt;</code> 的迭代器。为了获取每一个 <code>String</code>,通过 map 并 <code>unwrap</code> 每一个 <code>Result</code>。如果数据不是有效的 UTF-8 编码或者读取流遇到问题时,<code>Result</code> 可能是一个错误。一如既往生产环境的程序应该更优雅地处理这些错误,不过出于简单的目的我们选择在错误情况下停止程序。</p>
<p>浏览器通过连续发送两个换行符来代表一个 HTTP 请求的结束,所以为了从流中获取一个请求,我们获取行直到它们不为空。一旦将这些行收集进 vector就可以使用友好的 debug 格式化打印它们,以便看看 web 浏览器发送给服务端的指令。</p>
<p>让我们试一试!启动程序并再次在浏览器中发起请求。注意浏览器中仍然会出现错误页面,不过终端中程序的输出现在看起来像这样:</p>
<pre><code class="language-console">$ cargo run
Compiling hello v0.1.0 (file:///projects/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.42s
Running `target/debug/hello`
Request: [
"GET / HTTP/1.1",
"Host: 127.0.0.1:7878",
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:99.0) Gecko/20100101 Firefox/99.0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language: en-US,en;q=0.5",
"Accept-Encoding: gzip, deflate, br",
"DNT: 1",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
"Sec-Fetch-Dest: document",
"Sec-Fetch-Mode: navigate",
"Sec-Fetch-Site: none",
"Sec-Fetch-User: ?1",
"Cache-Control: max-age=0",
]
</code></pre>
<p>根据使用的浏览器不同可能会出现稍微不同的数据。现在我们打印出了请求数据,可以通过观察第一行 <code>GET</code> 之后的路径来解释为何会从浏览器得到多个连接。如果重复的连接都是请求 <em>/</em>,就知道了浏览器尝试重复获取 <em>/</em> 因为它没有从程序得到响应。</p>
<p>让我们拆开请求数据来理解浏览器向程序请求了什么。</p>
<h4 id="仔细观察-http-请求"><a class="header" href="#仔细观察-http-请求">仔细观察 HTTP 请求</a></h4>
<p>HTTP 是一个基于文本的协议,同时一个请求有如下格式:</p>
<pre><code class="language-text">Method Request-URI HTTP-Version CRLF
headers CRLF
message-body
</code></pre>
<p>第一行叫做 <strong>请求行</strong><em>request line</em>),它存放了客户端请求了什么的信息。请求行的第一部分是所使用的 <em>method</em>,比如 <code>GET</code><code>POST</code>,这描述了客户端如何进行请求。这里客户端使用了 <code>GET</code> 请求,表明它在请求信息。</p>
<p>请求行接下来的部分是 <em>/</em>,它代表客户端请求的 <strong>统一资源标识符</strong><em>Uniform Resource Identifier</em><em>URI</em> —— URI 大体上类似,但也不完全类似于 URL<strong>统一资源定位符</strong><em>Uniform Resource Locators</em>。URI 和 URL 之间的区别对于本章的目的来说并不重要,不过 HTTP 规范使用术语 URI所以这里可以简单的将 URL 理解为 URI。</p>
<p>最后一部分是客户端使用的 HTTP 版本,然后请求行以 <strong>CRLF 序列</strong> CRLF 代表回车和换行,<em>carriage return line feed</em>这是打字机时代的术语结束。CRLF 序列也可以写成<code>\r\n</code>,其中<code>\r</code>是回车符,<code>\n</code>是换行符。CRLF 序列将请求行与其余请求数据分开。请注意,打印 CRLF 时,我们会看到一个新行,而不是<code>\r\n</code></p>
<p>观察目前运行程序所接收到的数据的请求行,可以看到 <code>GET</code> 是 method<em>/</em> 是请求 URI<code>HTTP/1.1</code> 是版本。</p>
<p><code>Host:</code> 开始的其余的行是 headers<code>GET</code> 请求没有 body。</p>
<p>如果你希望的话,尝试用不同的浏览器发送请求,或请求不同的地址,比如 <code>127.0.0.1:7878/test</code>,来观察请求数据如何变化。</p>
<p>现在我们知道了浏览器请求了什么。让我们返回一些数据!</p>
<h3 id="编写响应"><a class="header" href="#编写响应">编写响应</a></h3>
<p>我们将实现在客户端请求的响应中发送数据的功能。响应有如下格式:</p>
<pre><code class="language-text">HTTP-Version Status-Code Reason-Phrase CRLF
headers CRLF
message-body
</code></pre>
<p>第一行叫做 <strong>状态行</strong><em>status line</em>),它包含响应的 HTTP 版本、一个数字状态码用以总结请求的结果和一个描述之前状态码的文本原因短语。CRLF 序列之后是任意 header另一个 CRLF 序列,和响应的 body。</p>
<p>这里是一个使用 HTTP 1.1 版本的响应例子,其状态码为 200原因短语为 OK没有 header也没有 body</p>
<pre><code class="language-text">HTTP/1.1 200 OK\r\n\r\n
</code></pre>
<p>状态码 200 是一个标准的成功响应。这些文本是一个微型的成功 HTTP 响应。让我们将这些文本写入流作为成功请求的响应!在 <code>handle_connection</code> 函数中,我们需要去掉打印请求数据的 <code>println!</code>,并替换为示例 20-3 中的代码:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">use std::{
</span><span class="boring"> io::{prelude::*, BufReader},
</span><span class="boring"> net::{TcpListener, TcpStream},
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
</span><span class="boring">
</span><span class="boring"> for stream in listener.incoming() {
</span><span class="boring"> let stream = stream.unwrap();
</span><span class="boring">
</span><span class="boring"> handle_connection(stream);
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&amp;stream);
let http_request: Vec&lt;_&gt; = buf_reader
.lines()
.map(|result| result.unwrap())
.take_while(|line| !line.is_empty())
.collect();
let response = "HTTP/1.1 200 OK\r\n\r\n";
stream.write_all(response.as_bytes()).unwrap();
}</code></pre></pre>
<p><span class="caption">示例 20-3: 将一个微型成功 HTTP 响应写入流</span></p>
<p>新代码中的第一行定义了变量 <code>response</code> 来存放将要返回的成功响应的数据。接着,在 <code>response</code> 上调用 <code>as_bytes</code>,因为 <code>stream</code><code>write_all</code> 方法获取一个 <code>&amp;[u8]</code> 并直接将这些字节发送给连接。因为 <code>write_all</code> 操作可能会失败,所以像之前那样对任何错误结果使用 <code>unwrap</code>。同理,在真实世界的应用中这里需要添加错误处理。</p>
<p>有了这些修改,运行我们的代码并进行请求!我们不再向终端打印任何数据,所以不会再看到除了 Cargo 以外的任何输出。不过当在浏览器中加载 <em>127.0.0.1:7878</em> 时,会得到一个空页面而不是错误。太棒了!我们刚刚手写收发了一个 HTTP 请求与响应。</p>
<h3 id="返回真正的-html"><a class="header" href="#返回真正的-html">返回真正的 HTML</a></h3>
<p>让我们实现不只是返回空页面的功能。在项目根目录创建一个新文件,<em>hello.html</em> —— 也就是说,不是在 <code>src</code> 目录。在此可以放入任何你期望的 HTML列表 20-4 展示了一个可能的文本:</p>
<p><span class="filename">文件名hello.html</span></p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;Hello!&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Hello!&lt;/h1&gt;
&lt;p&gt;Hi from Rust&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p><span class="caption">示例 20-4: 一个简单的 HTML 文件用来作为响应</span></p>
<p>这是一个极小化的 HTML5 文档,它有一个标题和一小段文本。为了在 server 接受请求时返回它,需要如示例 20-5 所示修改 <code>handle_connection</code> 来读取 HTML 文件,将其加入到响应的 body 中,并发送:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021">use std::{
fs,
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
};
// --snip--
<span class="boring">fn main() {
</span><span class="boring"> let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
</span><span class="boring">
</span><span class="boring"> for stream in listener.incoming() {
</span><span class="boring"> let stream = stream.unwrap();
</span><span class="boring">
</span><span class="boring"> handle_connection(stream);
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&amp;stream);
let http_request: Vec&lt;_&gt; = buf_reader
.lines()
.map(|result| result.unwrap())
.take_while(|line| !line.is_empty())
.collect();
let status_line = "HTTP/1.1 200 OK";
let contents = fs::read_to_string("hello.html").unwrap();
let length = contents.len();
let response =
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(response.as_bytes()).unwrap();
}</code></pre></pre>
<p><span class="caption">示例 20-5: 将 <em>hello.html</em> 的内容作为响应 body 发送</span></p>
<p>我们在开头 <code>use</code> 语句将标准库的文件系统模块 <code>fs</code> 引入作用域。打开和读取文件的代码应该看起来很熟悉,因为第十二章 I/O 项目的示例 12-4 中读取文件内容时出现过类似的代码。</p>
<p>接下来,使用 <code>format!</code> 将文件内容加入到将要写入流的成功响应的 body 中。</p>
<p>使用 <code>cargo run</code> 运行程序,在浏览器加载 <em>127.0.0.1:7878</em>,你应该会看到渲染出来的 HTML 文件!</p>
<p>目前忽略了 <code>http_request</code> 中的请求数据并无条件的发送了 HTML 文件的内容。这意味着如果尝试在浏览器中请求 <em>127.0.0.1:7878/something-else</em> 也会得到同样的 HTML 响应。目前我们的 server 的作用是非常有限的,也不是大部分 server 所做的让我们检查请求并只对格式良好well-formed的请求 <code>/</code> 发送 HTML 文件。</p>
<h3 id="验证请求并有选择的进行响应"><a class="header" href="#验证请求并有选择的进行响应">验证请求并有选择的进行响应</a></h3>
<p>目前我们的 web server 不管客户端请求什么都会返回相同的 HTML 文件。让我们增加在返回 HTML 文件前检查浏览器是否请求 <em>/</em>,并在其请求任何其他内容时返回错误的功能。为此需要如示例 20-6 那样修改 <code>handle_connection</code>。新代码接收到的请求的内容与已知的 <em>/</em> 请求的一部分做比较,并增加了 <code>if</code><code>else</code> 块来区别处理请求:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">use std::{
</span><span class="boring"> fs,
</span><span class="boring"> io::{prelude::*, BufReader},
</span><span class="boring"> net::{TcpListener, TcpStream},
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
</span><span class="boring">
</span><span class="boring"> for stream in listener.incoming() {
</span><span class="boring"> let stream = stream.unwrap();
</span><span class="boring">
</span><span class="boring"> handle_connection(stream);
</span><span class="boring"> }
</span><span class="boring">}
</span>// --snip--
fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&amp;stream);
let request_line = buf_reader.lines().next().unwrap().unwrap();
if request_line == "GET / HTTP/1.1" {
let status_line = "HTTP/1.1 200 OK";
let contents = fs::read_to_string("hello.html").unwrap();
let length = contents.len();
let response = format!(
"{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
);
stream.write_all(response.as_bytes()).unwrap();
} else {
// some other request
}
}</code></pre></pre>
<p><span class="caption">示例 20-6: 以不同于其它请求的方式处理 <em>/</em> 请求</span></p>
<p>我们只看 HTTP 请求的第一行,所以不同于将整个请求读取进 vector 中,这里调用 <code>next</code> 从迭代器中获取第一项。第一个 <code>unwrap</code> 负责处理 <code>Option</code> 并在迭代器没有项时停止程序。第二个 <code>unwrap</code> 处理 <code>Result</code> 并与示例 20-2 中增加的 <code>map</code> 中的 <code>unwrap</code> 有着相同的效果。</p>
<p>接下来检查 <code>request_line</code> 是否等于一个 <em>/</em> 路径的 GET 请求。如果是,<code>if</code> 代码块返回 HTML 文件的内容。</p>
<p>如果 <code>request_line</code> <strong></strong> 等于一个 <em>/</em> 路径的 GET 请求,就说明接收的是其他请求。我们之后会在 <code>else</code> 块中增加代码来响应所有其他请求。</p>
<p>现在如果运行代码并请求 <em>127.0.0.1:7878</em>,就会得到 <em>hello.html</em> 中的 HTML。如果进行任何其他请求比如 <em>127.0.0.1:7878/something-else</em>,则会得到像运行示例 20-1 和 20-2 中代码那样的连接错误。</p>
<p>现在向示例 20-7 的 <code>else</code> 块增加代码来返回一个带有 404 状态码的响应,这代表了所请求的内容没有找到。接着也会返回一个 HTML 向浏览器终端用户表明此意:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">use std::{
</span><span class="boring"> fs,
</span><span class="boring"> io::{prelude::*, BufReader},
</span><span class="boring"> net::{TcpListener, TcpStream},
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
</span><span class="boring">
</span><span class="boring"> for stream in listener.incoming() {
</span><span class="boring"> let stream = stream.unwrap();
</span><span class="boring">
</span><span class="boring"> handle_connection(stream);
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn handle_connection(mut stream: TcpStream) {
</span><span class="boring"> let buf_reader = BufReader::new(&amp;stream);
</span><span class="boring"> let request_line = buf_reader.lines().next().unwrap().unwrap();
</span><span class="boring">
</span><span class="boring"> if request_line == "GET / HTTP/1.1" {
</span><span class="boring"> let status_line = "HTTP/1.1 200 OK";
</span><span class="boring"> let contents = fs::read_to_string("hello.html").unwrap();
</span><span class="boring"> let length = contents.len();
</span><span class="boring">
</span><span class="boring"> let response = format!(
</span><span class="boring"> "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
</span><span class="boring"> );
</span><span class="boring">
</span><span class="boring"> stream.write_all(response.as_bytes()).unwrap();
</span> // --snip--
} else {
let status_line = "HTTP/1.1 404 NOT FOUND";
let contents = fs::read_to_string("404.html").unwrap();
let length = contents.len();
let response = format!(
"{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
);
stream.write_all(response.as_bytes()).unwrap();
}
<span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 20-7: 对于任何不是 <em>/</em> 的请求返回 <code>404</code> 状态码的响应和错误页面</span></p>
<p>这里,响应的状态行有状态码 404 和原因短语 <code>NOT FOUND</code>。仍然没有返回任何 header而其 body 将是 <em>404.html</em> 文件中的 HTML。需要在 <em>hello.html</em> 同级目录创建 <em>404.html</em> 文件作为错误页面;这一次也可以随意使用任何 HTML 或使用示例 20-8 中的示例 HTML</p>
<p><span class="filename">文件名404.html</span></p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;Hello!&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Oops!&lt;/h1&gt;
&lt;p&gt;Sorry, I don't know what you're asking for.&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p><span class="caption">示例 20-8: 任何 404 响应所返回错误页面内容样例</span></p>
<p>有了这些修改,再次运行 server。请求 <em>127.0.0.1:7878</em> 应该会返回 <em>hello.html</em> 的内容,而对于任何其他请求,比如 <em>127.0.0.1:7878/foo</em>,应该会返回 <em>404.html</em> 中的错误 HTML</p>
<h3 id="少量代码重构"><a class="header" href="#少量代码重构">少量代码重构</a></h3>
<p>目前 <code>if</code><code>else</code> 块中的代码有很多的重复:他们都读取文件并将其内容写入流。唯一的区别是状态行和文件名。为了使代码更为简明,将这些区别分别提取到一行 <code>if</code><code>else</code> 中,对状态行和文件名变量赋值;然后在读取文件和写入响应的代码中无条件的使用这些变量。重构后取代了大段 <code>if</code><code>else</code> 块代码后的结果如示例 20-9 所示:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">use std::{
</span><span class="boring"> fs,
</span><span class="boring"> io::{prelude::*, BufReader},
</span><span class="boring"> net::{TcpListener, TcpStream},
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
</span><span class="boring">
</span><span class="boring"> for stream in listener.incoming() {
</span><span class="boring"> let stream = stream.unwrap();
</span><span class="boring">
</span><span class="boring"> handle_connection(stream);
</span><span class="boring"> }
</span><span class="boring">}
</span>// --snip--
fn handle_connection(mut stream: TcpStream) {
// --snip--
<span class="boring"> let buf_reader = BufReader::new(&amp;stream);
</span><span class="boring"> let request_line = buf_reader.lines().next().unwrap().unwrap();
</span>
let (status_line, filename) = if request_line == "GET / HTTP/1.1" {
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();
let response =
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(response.as_bytes()).unwrap();
}</code></pre></pre>
<p><span class="caption">示例 20-9: 重构使得 <code>if</code><code>else</code> 块中只包含两个情况所不同的代码</span></p>
<p>现在 <code>if</code><code>else</code> 块所做的唯一的事就是在一个元组中返回合适的状态行和文件名的值;接着使用第十九章讲到的使用模式的 <code>let</code> 语句通过解构元组的两部分为 <code>filename</code><code>header</code> 赋值。</p>
<p>之前读取文件和写入响应的冗余代码现在位于 <code>if</code><code>else</code> 块之外,并会使用变量 <code>status_line</code><code>filename</code>。这样更易于观察这两种情况真正有何不同,还意味着如果需要改变如何读取文件或写入响应时只需要更新一处的代码。示例 20-9 中代码的行为与示例 20-8 完全一样。</p>
<p>好极了!我们有了一个 40 行左右 Rust 代码的小而简单的 server它对一个请求返回页面内容而对所有其他请求返回 404 响应。</p>
<p>目前 server 运行于单线程中,它一次只能处理一个请求。让我们模拟一些慢请求来看看这如何会成为一个问题,并进行修复以便 server 可以一次处理多个请求。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="将单线程-server-变为多线程-server"><a class="header" href="#将单线程-server-变为多线程-server">将单线程 server 变为多线程 server</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch21-02-multithreaded.md">ch21-02-multithreaded.md</a>
<br>
commit 98c6225e5fb8255349ec0dc235433530ed3fb534</p>
</blockquote>
<p>目前 server 会依次处理每一个请求,意味着它在完成第一个连接的处理之前不会处理第二个连接。如果 server 正接收越来越多的请求,这类串行操作会使性能越来越差。如果一个请求花费很长时间来处理,随后而来的请求则不得不等待这个长请求结束,即便这些新请求可以很快就处理完。我们需要修复这种情况,不过首先让我们实际尝试一下这个问题。</p>
<h3 id="在当前-server-实现中模拟慢请求"><a class="header" href="#在当前-server-实现中模拟慢请求">在当前 server 实现中模拟慢请求</a></h3>
<p>让我们看看一个慢请求如何影响当前 server 实现中的其他请求。示例 20-10 通过模拟慢响应实现了 <em>/sleep</em> 请求处理,它会使 server 在响应之前休眠五秒。</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021">use std::{
fs,
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
thread,
time::Duration,
};
// --snip--
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
</span><span class="boring">
</span><span class="boring"> for stream in listener.incoming() {
</span><span class="boring"> let stream = stream.unwrap();
</span><span class="boring">
</span><span class="boring"> handle_connection(stream);
</span><span class="boring"> }
</span><span class="boring">}
</span>
fn handle_connection(mut stream: TcpStream) {
// --snip--
<span class="boring"> let buf_reader = BufReader::new(&amp;stream);
</span><span class="boring"> let request_line = buf_reader.lines().next().unwrap().unwrap();
</span><span class="boring">
</span> let (status_line, filename) = match &amp;request_line[..] {
"GET / HTTP/1.1" =&gt; ("HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" =&gt; {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
_ =&gt; ("HTTP/1.1 404 NOT FOUND", "404.html"),
};
// --snip--
<span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(filename).unwrap();
</span><span class="boring"> let length = contents.len();
</span><span class="boring">
</span><span class="boring"> let response =
</span><span class="boring"> format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
</span><span class="boring">
</span><span class="boring"> stream.write_all(response.as_bytes()).unwrap();
</span>}</code></pre></pre>
<p><span class="caption">示例 20-10: 通过休眠五秒来模拟慢请求</span></p>
<p><code>if</code> 切换到 <code>match</code> 后现在有三个分支了。我们需要显式匹配一个 slice 的 <code>request_line</code> 以匹配字符串字面值的模式。<code>match</code> 不会像相等方法那样自动引用和解引用。</p>
<p>第一个分支与示例 20-9 中的 <code>if</code> 代码块相同。第二个分支匹配一个 <em>/sleep</em> 请求。当接收到这个请求时server 在渲染成功 HTML 页面之前会先休眠五秒。第三个分支与示例 20-9 中的 <code>else</code> 代码块相同。</p>
<p>现在就可以真切的看出我们的 server 有多么的原始:真实的库将会以更简洁的方式处理多请求识别问题!</p>
<p>使用 <code>cargo run</code> 启动 server并接着打开两个浏览器窗口一个请求 <em>http://127.0.0.1:7878/</em> 而另一个请求 <em>http://127.0.0.1:7878/sleep</em> 。如果像之前一样多次请求 <em>/</em>,会发现响应的比较快速。不过如果请求 <em>/sleep</em> 之后再请求 <em>/</em>,就会看到 <em>/</em> 会等待直到 <code>sleep</code> 休眠完五秒之后才出现。</p>
<p>有多种技术可以用来避免所有请求都排在慢请求之后;我们将要实现的一个便是线程池。</p>
<h3 id="使用线程池改善吞吐量"><a class="header" href="#使用线程池改善吞吐量">使用线程池改善吞吐量</a></h3>
<p><strong>线程池</strong><em>thread pool</em>)是一组预先分配的等待或准备处理任务的线程。当程序收到一个新任务,线程池中的一个线程会被分配任务,这个线程会离开并处理任务。其余的线程则可用于处理在第一个线程处理任务的同时处理其他接收到的任务。当第一个线程处理完任务时,它会返回空闲线程池中等待处理新任务。线程池允许我们并发处理连接,增加 server 的吞吐量。</p>
<p>我们会将池中线程限制为较少的数量以防拒绝服务Denial of ServiceDoS攻击如果程序为每一个接收的请求都新建一个线程某人向 server 发起千万级的请求时会耗尽服务器的资源并导致所有请求的处理都被终止。</p>
<p>不同于分配无限的线程,线程池中将有固定数量的等待线程。当新进请求时,将请求发送到线程池中做处理。线程池会维护一个接收请求的队列。每一个线程会从队列中取出一个请求,处理请求,接着向队列索取另一个请求。通过这种设计,则可以并发处理 <code>N</code> 个请求,其中 <code>N</code> 为线程数。如果每一个线程都在响应慢请求,之后的请求仍然会阻塞队列,不过相比之前增加了能处理的慢请求的数量。</p>
<p>这个设计仅仅是多种改善 web server 吞吐量的方法之一。其他可供探索的方法有 <strong>fork/join 模型</strong><em>fork/join model</em>)、<strong>单线程异步 I/O 模型</strong><em>single-threaded async I/O model</em>)或者<strong>多线程异步 I/O 模型</strong><em>multi-threaded async I/O model</em>)。如果你对这个主题感兴趣,则可以阅读更多关于其他解决方案的内容并尝试实现它们;对于一个像 Rust 这样的底层语言,所有这些方法都是可能的。</p>
<p>在开始之前,让我们讨论一下线程池应用看起来怎样。当尝试设计代码时,首先编写客户端接口确实有助于指导代码设计。以期望的调用方式来构建 API 代码的结构,接着在这个结构之内实现功能,而不是先实现功能再设计公有 API。</p>
<p>类似于第十二章项目中使用的测试驱动开发。这里将要使用编译器驱动开发compiler-driven development。我们将编写调用所期望的函数的代码接着观察编译器错误告诉我们接下来需要修改什么使得代码可以工作。不过在开始之前我们将探索不会作为起点的技术。</p>
<h4 id="为每一个请求分配线程"><a class="header" href="#为每一个请求分配线程">为每一个请求分配线程</a></h4>
<p>首先,让我们探索一下为每一个连接都创建一个线程的代码看起来如何。这并不是最终方案,因为正如之前讲到的它会潜在的分配无限的线程,不过这是一个可用的多线程 server 的起点。接着我们会增加线程池作为改进,这样比较两个方案将会更容易。示例 20-11 展示了 <code>main</code> 的改变,它在 <code>for</code> 循环中为每一个流分配了一个新线程进行处理:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">use std::{
</span><span class="boring"> fs,
</span><span class="boring"> io::{prelude::*, BufReader},
</span><span class="boring"> net::{TcpListener, TcpStream},
</span><span class="boring"> thread,
</span><span class="boring"> time::Duration,
</span><span class="boring">};
</span><span class="boring">
</span>fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
thread::spawn(|| {
handle_connection(stream);
});
}
}
<span class="boring">
</span><span class="boring">fn handle_connection(mut stream: TcpStream) {
</span><span class="boring"> let buf_reader = BufReader::new(&amp;stream);
</span><span class="boring"> let request_line = buf_reader.lines().next().unwrap().unwrap();
</span><span class="boring">
</span><span class="boring"> let (status_line, filename) = match &amp;request_line[..] {
</span><span class="boring"> "GET / HTTP/1.1" =&gt; ("HTTP/1.1 200 OK", "hello.html"),
</span><span class="boring"> "GET /sleep HTTP/1.1" =&gt; {
</span><span class="boring"> thread::sleep(Duration::from_secs(5));
</span><span class="boring"> ("HTTP/1.1 200 OK", "hello.html")
</span><span class="boring"> }
</span><span class="boring"> _ =&gt; ("HTTP/1.1 404 NOT FOUND", "404.html"),
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(filename).unwrap();
</span><span class="boring"> let length = contents.len();
</span><span class="boring">
</span><span class="boring"> let response =
</span><span class="boring"> format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
</span><span class="boring">
</span><span class="boring"> stream.write_all(response.as_bytes()).unwrap();
</span><span class="boring">}</span></code></pre></pre>
<p><span class="caption">示例 20-11: 为每一个流新建一个线程</span></p>
<p>正如第十六章讲到的,<code>thread::spawn</code> 会创建一个新线程并在其中运行闭包中的代码。如果运行这段代码并在在浏览器中加载 <em>/sleep</em>,接着在另两个浏览器标签页中加载 <em>/</em>,确实会发现 <em>/</em> 请求不必等待 <em>/sleep</em> 结束。不过正如之前提到的,这最终会使系统崩溃因为我们无限制的创建新线程。</p>
<h4 id="创建有限数量的线程"><a class="header" href="#创建有限数量的线程">创建有限数量的线程</a></h4>
<p>我们期望线程池以类似且熟悉的方式工作,以便从线程切换到线程池并不会对使用该 API 的代码做出较大的修改。示例 20-12 展示我们希望用来替换 <code>thread::spawn</code><code>ThreadPool</code> 结构体的假想接口:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::{
</span><span class="boring"> fs,
</span><span class="boring"> io::{prelude::*, BufReader},
</span><span class="boring"> net::{TcpListener, TcpStream},
</span><span class="boring"> thread,
</span><span class="boring"> time::Duration,
</span><span class="boring">};
</span><span class="boring">
</span>fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming() {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
}
<span class="boring">
</span><span class="boring">fn handle_connection(mut stream: TcpStream) {
</span><span class="boring"> let buf_reader = BufReader::new(&amp;stream);
</span><span class="boring"> let request_line = buf_reader.lines().next().unwrap().unwrap();
</span><span class="boring">
</span><span class="boring"> let (status_line, filename) = match &amp;request_line[..] {
</span><span class="boring"> "GET / HTTP/1.1" =&gt; ("HTTP/1.1 200 OK", "hello.html"),
</span><span class="boring"> "GET /sleep HTTP/1.1" =&gt; {
</span><span class="boring"> thread::sleep(Duration::from_secs(5));
</span><span class="boring"> ("HTTP/1.1 200 OK", "hello.html")
</span><span class="boring"> }
</span><span class="boring"> _ =&gt; ("HTTP/1.1 404 NOT FOUND", "404.html"),
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(filename).unwrap();
</span><span class="boring"> let length = contents.len();
</span><span class="boring">
</span><span class="boring"> let response =
</span><span class="boring"> format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
</span><span class="boring">
</span><span class="boring"> stream.write_all(response.as_bytes()).unwrap();
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 20-12: 假想的 <code>ThreadPool</code> 接口</span></p>
<p>这里使用 <code>ThreadPool::new</code> 来创建一个新的线程池,它有一个可配置的线程数的参数,在这里是四。这样在 <code>for</code> 循环中,<code>pool.execute</code> 有着类似 <code>thread::spawn</code> 的接口,它获取一个线程池运行于每一个流的闭包。<code>pool.execute</code> 需要实现为获取闭包并传递给池中的线程运行。这段代码还不能编译,不过通过尝试,编译器会指导我们如何修复它。</p>
<h4 id="采用编译器驱动构建-threadpool"><a class="header" href="#采用编译器驱动构建-threadpool">采用编译器驱动构建 <code>ThreadPool</code></a></h4>
<p>继续并对示例 20-12 中的 <em>src/main.rs</em> 做出修改,并利用来自 <code>cargo check</code> 的编译器错误来驱动开发。下面是我们得到的第一个错误:</p>
<pre><code class="language-console">$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0433]: failed to resolve: use of undeclared type `ThreadPool`
--&gt; src/main.rs:11:16
|
11 | let pool = ThreadPool::new(4);
| ^^^^^^^^^^ use of undeclared type `ThreadPool`
For more information about this error, try `rustc --explain E0433`.
error: could not compile `hello` (bin "hello") due to 1 previous error
</code></pre>
<p>好的,这告诉我们需要一个 <code>ThreadPool</code> 类型或模块,所以我们将构建一个。<code>ThreadPool</code> 的实现会与 web server 的特定工作相独立,所以让我们从 <code>hello</code> crate 切换到存放 <code>ThreadPool</code> 实现的新库 crate。这也意味着可以在任何工作中使用这个单独的线程池库而不仅仅是处理网络请求。</p>
<p>创建 <em>src/lib.rs</em> 文件,它包含了目前可用的最简单的 <code>ThreadPool</code> 定义:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub struct ThreadPool;</code></pre>
<p>接着编辑 <em>main.rs</em> 文件通过在 <em>src/main.rs</em> 的开头增加如下代码将 <code>ThreadPool</code> 从库 crate 引入作用域:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use hello::ThreadPool;
<span class="boring">use std::{
</span><span class="boring"> fs,
</span><span class="boring"> io::{prelude::*, BufReader},
</span><span class="boring"> net::{TcpListener, TcpStream},
</span><span class="boring"> thread,
</span><span class="boring"> time::Duration,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
</span><span class="boring"> let pool = ThreadPool::new(4);
</span><span class="boring">
</span><span class="boring"> for stream in listener.incoming() {
</span><span class="boring"> let stream = stream.unwrap();
</span><span class="boring">
</span><span class="boring"> pool.execute(|| {
</span><span class="boring"> handle_connection(stream);
</span><span class="boring"> });
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn handle_connection(mut stream: TcpStream) {
</span><span class="boring"> let buf_reader = BufReader::new(&amp;stream);
</span><span class="boring"> let request_line = buf_reader.lines().next().unwrap().unwrap();
</span><span class="boring">
</span><span class="boring"> let (status_line, filename) = match &amp;request_line[..] {
</span><span class="boring"> "GET / HTTP/1.1" =&gt; ("HTTP/1.1 200 OK", "hello.html"),
</span><span class="boring"> "GET /sleep HTTP/1.1" =&gt; {
</span><span class="boring"> thread::sleep(Duration::from_secs(5));
</span><span class="boring"> ("HTTP/1.1 200 OK", "hello.html")
</span><span class="boring"> }
</span><span class="boring"> _ =&gt; ("HTTP/1.1 404 NOT FOUND", "404.html"),
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(filename).unwrap();
</span><span class="boring"> let length = contents.len();
</span><span class="boring">
</span><span class="boring"> let response =
</span><span class="boring"> format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
</span><span class="boring">
</span><span class="boring"> stream.write_all(response.as_bytes()).unwrap();
</span><span class="boring">}</span></code></pre>
<p>这仍然不能工作,再次尝试运行来得到下一个需要解决的错误:</p>
<pre><code class="language-console">$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no function or associated item named `new` found for struct `ThreadPool` in the current scope
--&gt; src/main.rs:12:28
|
12 | let pool = ThreadPool::new(4);
| ^^^ function or associated item not found in `ThreadPool`
For more information about this error, try `rustc --explain E0599`.
error: could not compile `hello` (bin "hello") due to 1 previous error
</code></pre>
<p>这告诉我们下一步是为 <code>ThreadPool</code> 创建一个叫做 <code>new</code> 的关联函数。我们还知道 <code>new</code> 需要有一个参数可以接受 <code>4</code>,而且 <code>new</code> 应该返回 <code>ThreadPool</code> 实例。让我们实现拥有此特征的最小化 <code>new</code> 函数:</p>
<p><span class="filename">文件夹src/lib.rs</span></p>
<pre><code class="language-rust noplayground">pub struct ThreadPool;
impl ThreadPool {
pub fn new(size: usize) -&gt; ThreadPool {
ThreadPool
}
}</code></pre>
<p>这里选择 <code>usize</code> 作为 <code>size</code> 参数的类型,因为我们知道为负的线程数没有意义。我们还知道将使用 4 作为线程集合的元素数量,这也就是使用 <code>usize</code> 类型的原因,如第三章 <a href="ch03-02-data-types.html#%E6%95%B4%E5%9E%8B">“整型”</a> 部分所讲。</p>
<p>再次编译检查这段代码:</p>
<pre><code class="language-console">$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no method named `execute` found for struct `ThreadPool` in the current scope
--&gt; src/main.rs:17:14
|
17 | pool.execute(|| {
| -----^^^^^^^ method not found in `ThreadPool`
For more information about this error, try `rustc --explain E0599`.
error: could not compile `hello` (bin "hello") due to 1 previous error
</code></pre>
<p>现在有了一个警告和一个错误。暂时先忽略警告,发生错误是因为并没有 <code>ThreadPool</code> 上的 <code>execute</code> 方法。回忆 <a href="ch21-02-multithreaded.html#%E5%88%9B%E5%BB%BA%E6%9C%89%E9%99%90%E6%95%B0%E9%87%8F%E7%9A%84%E7%BA%BF%E7%A8%8B">“创建有限数量的线程”</a> 部分我们决定线程池应该有与 <code>thread::spawn</code> 类似的接口,同时我们将实现 <code>execute</code> 函数来获取传递的闭包并将其传递给池中的空闲线程执行。</p>
<p>我们会在 <code>ThreadPool</code> 上定义 <code>execute</code> 函数来获取一个闭包参数。回忆第十三章的 <a href="ch13-01-closures.html#%E5%B0%86%E8%A2%AB%E6%8D%95%E8%8E%B7%E7%9A%84%E5%80%BC%E7%A7%BB%E5%87%BA%E9%97%AD%E5%8C%85%E5%92%8C-fn-trait">“将被捕获的值移出闭包和 <code>Fn</code> trait”</a> 部分,闭包作为参数时可以使用三个不同的 trait<code>Fn</code><code>FnMut</code><code>FnOnce</code>。我们需要决定这里应该使用哪种闭包。最终需要实现的类似于标准库的 <code>thread::spawn</code>,所以我们可以观察 <code>thread::spawn</code> 的签名在其参数中使用了何种 bound。查看文档会发现</p>
<pre><code class="language-rust ignore">pub fn spawn&lt;F, T&gt;(f: F) -&gt; JoinHandle&lt;T&gt;
where
F: FnOnce() -&gt; T,
F: Send + 'static,
T: Send + 'static,</code></pre>
<p><code>F</code> 是这里我们关心的参数;<code>T</code> 与返回值有关所以我们并不关心。考虑到 <code>spawn</code> 使用 <code>FnOnce</code> 作为 <code>F</code> 的 trait bound这可能也是我们需要的因为最终会将传递给 <code>execute</code> 的参数传给 <code>spawn</code>。因为处理请求的线程只会执行闭包一次,这也进一步确认了 <code>FnOnce</code> 是我们需要的 trait这里符合 <code>FnOnce</code><code>Once</code> 的意思。</p>
<p><code>F</code> 还有 trait bound <code>Send</code> 和生命周期绑定 <code>'static</code>,这对我们的情况也是有意义的:需要 <code>Send</code> 来将闭包从一个线程转移到另一个线程,而 <code>'static</code> 是因为并不知道线程会执行多久。让我们编写一个使用带有这些 bound 的泛型参数 <code>F</code><code>ThreadPool</code><code>execute</code> 方法:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct ThreadPool;
</span><span class="boring">
</span>impl ThreadPool {
// --snip--
<span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> ThreadPool
</span><span class="boring"> }
</span><span class="boring">
</span> pub fn execute&lt;F&gt;(&amp;self, f: F)
where
F: FnOnce() + Send + 'static,
{
}
}</code></pre>
<p><code>FnOnce</code> trait 仍然需要之后的 <code>()</code>,因为这里的 <code>FnOnce</code> 代表一个没有参数也没有返回值的闭包。正如函数的定义,返回值类型可以从签名中省略,不过即便没有参数也需要括号。</p>
<p>这里再一次增加了 <code>execute</code> 方法的最小化实现:它没有做任何工作,只是尝试让代码能够编译。再次进行检查:</p>
<pre><code class="language-console">$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.24s
</code></pre>
<p>现在就只有警告了!这意味着能够编译了!注意如果尝试 <code>cargo run</code> 运行程序并在浏览器中发起请求,仍会在浏览器中出现在本章开始时那样的错误。这个库实际上还没有调用传递给 <code>execute</code> 的闭包!</p>
<blockquote>
<p>一个你可能听说过的关于像 Haskell 和 Rust 这样有严格编译器的语言的说法是 “如果代码能够编译,它就能工作”。这是一个提醒大家的好时机,实际上这并不是普适的。我们的项目可以编译,不过它完全没有做任何工作!如果构建一个真实且功能完整的项目,则需花费大量的时间来开始编写单元测试来检查代码能否编译 <strong>并且</strong> 拥有期望的行为。</p>
</blockquote>
<h4 id="在-new-中验证池中线程数量"><a class="header" href="#在-new-中验证池中线程数量"><code>new</code> 中验证池中线程数量</a></h4>
<p>这里仍然存在警告是因为其并没有对 <code>new</code><code>execute</code> 的参数做任何操作。让我们用期望的行为来实现这些函数。以考虑 <code>new</code> 作为开始。之前选择使用无符号类型作为 <code>size</code> 参数的类型,因为线程数为负的线程池没有意义。然而,线程数为零的线程池同样没有意义,不过零是一个完全有效的 <code>usize</code> 值。让我们增加在返回 <code>ThreadPool</code> 实例之前检查 <code>size</code> 是否大于零的代码,并使用 <code>assert!</code> 宏在得到零时 panic如示例 20-13 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">pub struct ThreadPool;
</span><span class="boring">
</span>impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -&gt; ThreadPool {
assert!(size &gt; 0);
ThreadPool
}
// --snip--
<span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> }
</span>}</code></pre>
<p><span class="caption">示例 20-13: 实现 <code>ThreadPool::new</code><code>size</code> 为零时 panic</span></p>
<p>这里也用文档注释为 <code>ThreadPool</code> 增加了一些文档。注意这里遵循了良好的文档实践并增加了一个部分来提示函数会 panic 的情况,正如第十四章所讨论的。尝试运行 <code>cargo doc --open</code> 并点击 <code>ThreadPool</code> 结构体来查看生成的 <code>new</code> 的文档看起来如何!</p>
<p>相比像这里使用 <code>assert!</code> 宏,也可以让 <code>new</code> 像之前 I/O 项目中示例 12-9 中 <code>Config::build</code> 那样将 <code>new</code> 更改为 <code>build</code> 并返回一个 <code>Result</code>,不过在这里我们选择创建一个没有任何线程的线程池应该是不可恢复的错误。如果你想做的更好,尝试编写一个采用如下签名的名为 <code>build</code> 的函数来对比一下 <code>new</code> 函数:</p>
<pre><code class="language-rust ignore">pub fn build(size: usize) -&gt; Result&lt;ThreadPool, PoolCreationError&gt; {</code></pre>
<h4 id="分配空间以储存线程"><a class="header" href="#分配空间以储存线程">分配空间以储存线程</a></h4>
<p>现在有了一个有效的线程池线程数,就可以实际创建这些线程并在返回结构体之前将它们储存在 <code>ThreadPool</code> 结构体中。不过如何 “储存” 一个线程?让我们再看看 <code>thread::spawn</code> 的签名:</p>
<pre><code class="language-rust ignore">pub fn spawn&lt;F, T&gt;(f: F) -&gt; JoinHandle&lt;T&gt;
where
F: FnOnce() -&gt; T,
F: Send + 'static,
T: Send + 'static,</code></pre>
<p><code>spawn</code> 返回 <code>JoinHandle&lt;T&gt;</code>,其中 <code>T</code> 是闭包返回的类型。尝试使用 <code>JoinHandle</code> 来看看会发生什么。在我们的情况中,传递给线程池的闭包会处理连接并不返回任何值,所以 <code>T</code> 将会是单元类型 <code>()</code></p>
<p>示例 20-14 中的代码可以编译,不过实际上还并没有创建任何线程。我们改变了 <code>ThreadPool</code> 的定义来存放一个 <code>thread::JoinHandle&lt;()&gt;</code> 的 vector 实例,使用 <code>size</code> 容量来初始化,并设置一个 <code>for</code> 循环来运行创建线程的代码,并返回包含这些线程的 <code>ThreadPool</code> 实例:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore not_desired_behavior">use std::thread;
pub struct ThreadPool {
threads: Vec&lt;thread::JoinHandle&lt;()&gt;&gt;,
}
impl ThreadPool {
// --snip--
<span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span> pub fn new(size: usize) -&gt; ThreadPool {
assert!(size &gt; 0);
let mut threads = Vec::with_capacity(size);
for _ in 0..size {
// create some threads and store them in the vector
}
ThreadPool { threads }
}
// --snip--
<span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> }
</span>}</code></pre>
<p><span class="caption">示例 20-14: 为 <code>ThreadPool</code> 创建一个 vector 来存放线程</span></p>
<p>这里将 <code>std::thread</code> 引入库 crate 的作用域,因为使用了 <code>thread::JoinHandle</code> 作为 <code>ThreadPool</code> 中 vector 元素的类型。</p>
<p>在得到了有效的数量之后,<code>ThreadPool</code> 新建一个存放 <code>size</code> 个元素的 vector。<code>with_capacity</code> 函数与 <code>Vec::new</code> 做了同样的工作,不过有一个重要的区别:它为 vector 预先分配空间。因为已经知道了 vector 中需要 <code>size</code> 个元素,预先进行分配比仅仅 <code>Vec::new</code> 要稍微有效率一些,因为 <code>Vec::new</code> 随着插入元素而重新改变大小。</p>
<p>如果再次运行 <code>cargo check</code>,它应该会成功。</p>
<h4 id="worker-结构体负责从-threadpool-中将代码传递给线程"><a class="header" href="#worker-结构体负责从-threadpool-中将代码传递给线程"><code>Worker</code> 结构体负责从 <code>ThreadPool</code> 中将代码传递给线程</a></h4>
<p>示例 20-14 的 <code>for</code> 循环中留下了一个关于创建线程的注释。如何实际创建线程呢?这是一个难题。标准库提供的创建线程的方法,<code>thread::spawn</code>,它期望获取一些一旦创建线程就应该执行的代码。然而,我们希望开始线程并使其等待稍后传递的代码。标准库的线程实现并没有包含这么做的方法;我们必须自己实现。</p>
<p>我们将要实现的行为是创建线程并稍后发送代码,这会在 <code>ThreadPool</code> 和线程间引入一个新数据类型来管理这种新行为。这个数据结构称为 <em>Worker</em>,这是一个池实现中的常见概念。想象一下在餐馆厨房工作的员工:员工等待来自客户的订单,他们负责接受这些订单并完成它们。</p>
<p>不同于在线程池中储存一个 <code>JoinHandle&lt;()&gt;</code> 实例的 vector我们会储存 <code>Worker</code> 结构体的实例。每一个 <code>Worker</code> 会储存一个单独的 <code>JoinHandle&lt;()&gt;</code> 实例。接着会在 <code>Worker</code> 上实现一个方法,它会获取需要允许代码的闭包并将其发送给已经运行的线程执行。我们还会赋予每一个 worker <code>id</code>,这样就可以在日志和调试中区别线程池中的不同 worker。</p>
<p>如下是创建 <code>ThreadPool</code> 时会发生的新过程。在通过如下方式设置完 <code>Worker</code> 之后,我们会实现向线程发送闭包的代码:</p>
<ol>
<li>定义 <code>Worker</code> 结构体存放 <code>id</code><code>JoinHandle&lt;()&gt;</code></li>
<li>修改 <code>ThreadPool</code> 存放一个 <code>Worker</code> 实例的 vector</li>
<li>定义 <code>Worker::new</code> 函数,它获取一个 <code>id</code> 数字并返回一个带有 <code>id</code> 和用空闭包分配的线程的 <code>Worker</code> 实例</li>
<li><code>ThreadPool::new</code> 中,使用 <code>for</code> 循环计数生成 <code>id</code>,使用这个 <code>id</code> 新建 <code>Worker</code>,并储存进 vector 中</li>
</ol>
<p>如果你渴望挑战,在查示例 20-15 中的代码之前尝试自己实现这些修改。</p>
<p>准备好了吗?示例 20-15 就是一个做出了这些修改的例子:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::thread;
pub struct ThreadPool {
workers: Vec&lt;Worker&gt;,
}
impl ThreadPool {
// --snip--
<span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span> pub fn new(size: usize) -&gt; ThreadPool {
assert!(size &gt; 0);
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id));
}
ThreadPool { workers }
}
// --snip--
<span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> }
</span>}
struct Worker {
id: usize,
thread: thread::JoinHandle&lt;()&gt;,
}
impl Worker {
fn new(id: usize) -&gt; Worker {
let thread = thread::spawn(|| {});
Worker { id, thread }
}
}</code></pre>
<p><span class="caption">示例 20-15: 修改 <code>ThreadPool</code> 存放 <code>Worker</code> 实例而不是直接存放线程</span></p>
<p>这里将 <code>ThreadPool</code> 中字段名从 <code>threads</code> 改为 <code>workers</code>,因为它现在储存 <code>Worker</code> 而不是 <code>JoinHandle&lt;()&gt;</code>。使用 <code>for</code> 循环中的计数作为 <code>Worker::new</code> 的参数,并将每一个新建的 <code>Worker</code> 储存在叫做 <code>workers</code> 的 vector 中。</p>
<p><code>Worker</code> 结构体和其 <code>new</code> 函数是私有的,因为外部代码(比如 <em>src/main.rs</em> 中的 server并不需要知道关于 <code>ThreadPool</code> 中使用 <code>Worker</code> 结构体的实现细节。<code>Worker::new</code> 函数使用 <code>id</code> 参数并储存了使用一个空闭包创建的 <code>JoinHandle&lt;()&gt;</code></p>
<blockquote>
<p>注意:如果操作系统因为没有足够的系统资源而无法创建线程时,<code>thread::spawn</code> 会 panic。这会导致整个 server panic即使一些线程可能创建成功了。出于简单的考虑这个行为是可行的不过在一个生产级别的线程池实现中你可能会希望使用 <a href="https://doc.rust-lang.org/std/thread/struct.Builder.html"><code>std::thread::Builder</code></a> 和其 <a href="https://doc.rust-lang.org/std/thread/struct.Builder.html#method.spawn"><code>spawn</code></a> 方法来返回一个 <code>Result</code></p>
</blockquote>
<p>这段代码能够编译并用指定给 <code>ThreadPool::new</code> 的参数创建储存了一系列的 <code>Worker</code> 实例,不过 <strong>仍然</strong> 没有处理 <code>execute</code> 中得到的闭包。让我们聊聊接下来怎么做。</p>
<h4 id="使用信道向线程发送请求"><a class="header" href="#使用信道向线程发送请求">使用信道向线程发送请求</a></h4>
<p>下一个需要解决的问题是传递给 <code>thread::spawn</code> 的闭包完全没有做任何工作。目前,我们在 <code>execute</code> 方法中获得期望执行的闭包,不过在创建 <code>ThreadPool</code> 的过程中创建每一个 <code>Worker</code> 时需要向 <code>thread::spawn</code> 传递一个闭包。</p>
<p>我们希望刚创建的 <code>Worker</code> 结构体能够从 <code>ThreadPool</code> 的队列中获取需要执行的代码,并发送到线程中执行它们。</p>
<p>在第十六章,我们学习了 <strong>信道</strong> —— 一个沟通两个线程的简单手段 —— 对于这个例子来说则是绝佳的。这里信道将充当任务队列的作用,<code>execute</code> 将通过 <code>ThreadPool</code> 向其中线程正在寻找工作的 <code>Worker</code> 实例发送任务。如下是这个计划:</p>
<ol>
<li><code>ThreadPool</code> 会创建一个信道并充当发送者。</li>
<li>每个 <code>Worker</code> 将会充当接收者。</li>
<li>新建一个 <code>Job</code> 结构体来存放用于向信道中发送的闭包。</li>
<li><code>execute</code> 方法会在发送者发出期望执行的任务。</li>
<li>在线程中,<code>Worker</code> 会遍历接收者并执行任何接收到的任务。</li>
</ol>
<p>让我们以在 <code>ThreadPool::new</code> 中创建信道并让 <code>ThreadPool</code> 实例充当发送者开始,如示例 20-16 所示。<code>Job</code> 是将在信道中发出的类型,目前它是一个没有任何内容的结构体:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::{sync::mpsc, thread};
pub struct ThreadPool {
workers: Vec&lt;Worker&gt;,
sender: mpsc::Sender&lt;Job&gt;,
}
struct Job;
impl ThreadPool {
// --snip--
<span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span> pub fn new(size: usize) -&gt; ThreadPool {
assert!(size &gt; 0);
let (sender, receiver) = mpsc::channel();
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id));
}
ThreadPool { workers, sender }
}
// --snip--
<span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> }
</span>}
<span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: thread::JoinHandle&lt;()&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Worker {
</span><span class="boring"> fn new(id: usize) -&gt; Worker {
</span><span class="boring"> let thread = thread::spawn(|| {});
</span><span class="boring">
</span><span class="boring"> Worker { id, thread }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 20-16: 修改 <code>ThreadPool</code> 来储存一个传输 <code>Job</code> 实例的发送者</span></p>
<p><code>ThreadPool::new</code> 中,新建了一个信道,并接着让线程池在接收端等待。这段代码能够成功编译。</p>
<p>让我们尝试在线程池创建每个 worker 时将接收者传递给它们。须知我们希望在 worker 所分配的线程中使用接收者,所以将在闭包中引用 <code>receiver</code> 参数。示例 20-17 中展示的代码还不能编译:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::{sync::mpsc, thread};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Job;
</span><span class="boring">
</span>impl ThreadPool {
// --snip--
<span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span> pub fn new(size: usize) -&gt; ThreadPool {
assert!(size &gt; 0);
let (sender, receiver) = mpsc::channel();
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, receiver));
}
ThreadPool { workers, sender }
}
// --snip--
<span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> }
</span>}
// --snip--
<span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: thread::JoinHandle&lt;()&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>impl Worker {
fn new(id: usize, receiver: mpsc::Receiver&lt;Job&gt;) -&gt; Worker {
let thread = thread::spawn(|| {
receiver;
});
Worker { id, thread }
}
}</code></pre>
<p><span class="caption">示例 20-17: 将信道的接收端传递给 worker</span></p>
<p>这是一些小而直观的修改:将接收者传递进了 <code>Worker::new</code>,并接着在闭包中使用它。</p>
<p>如果尝试 check 代码,会得到这个错误:</p>
<pre><code class="language-console">$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0382]: use of moved value: `receiver`
--&gt; src/lib.rs:26:42
|
21 | let (sender, receiver) = mpsc::channel();
| -------- move occurs because `receiver` has type `std::sync::mpsc::Receiver&lt;Job&gt;`, which does not implement the `Copy` trait
...
25 | for id in 0..size {
| ----------------- inside of this loop
26 | workers.push(Worker::new(id, receiver));
| ^^^^^^^^ value moved here, in previous iteration of loop
|
note: consider changing this parameter type in method `new` to borrow instead if owning the value isn't necessary
--&gt; src/lib.rs:47:33
|
47 | fn new(id: usize, receiver: mpsc::Receiver&lt;Job&gt;) -&gt; Worker {
| --- in this method ^^^^^^^^^^^^^^^^^^^ this parameter takes ownership of the value
help: consider moving the expression out of the loop so it is only moved once
|
25 ~ let mut value = Worker::new(id, receiver);
26 ~ for id in 0..size {
27 ~ workers.push(value);
|
For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` (lib) due to 1 previous error
</code></pre>
<p>这段代码尝试将 <code>receiver</code> 传递给多个 <code>Worker</code> 实例。这是不行的回忆第十六章Rust 所提供的信道实现是多 <strong>生产者</strong>,单 <strong>消费者</strong> 的。这意味着不能简单的克隆信道的消费端来解决问题。我们也不希望将一个消息向多个消费者发送多次;我们希望有一个消息列表和多个 worker 这样每个消息就只会处理一次。</p>
<p>另外,从信道队列中取出任务涉及到修改 <code>receiver</code>,所以这些线程需要一个能安全的共享和修改 <code>receiver</code> 的方式,否则可能导致竞争状态(参考第十六章)。</p>
<p>回忆一下第十六章讨论的线程安全智能指针,为了在多个线程间共享所有权并允许线程修改其值,需要使用 <code>Arc&lt;Mutex&lt;T&gt;&gt;</code><code>Arc</code> 使得多个 worker 拥有接收端,而 <code>Mutex</code> 则确保一次只有一个 worker 能从接收端得到任务。示例 20-18 展示了所需的修改:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
// --snip--
<span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Job;
</span><span class="boring">
</span>impl ThreadPool {
// --snip--
<span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span> pub fn new(size: usize) -&gt; ThreadPool {
assert!(size &gt; 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
}
ThreadPool { workers, sender }
}
// --snip--
<span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> }
</span>}
// --snip--
<span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: thread::JoinHandle&lt;()&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>impl Worker {
fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
// --snip--
<span class="boring"> let thread = thread::spawn(|| {
</span><span class="boring"> receiver;
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> Worker { id, thread }
</span> }
}</code></pre>
<p><span class="caption">示例 20-18: 使用 <code>Arc</code><code>Mutex</code> 在 worker 间共享接收者</span></p>
<p><code>ThreadPool::new</code> 中,将接收者放入一个 <code>Arc</code> 和一个 <code>Mutex</code> 中。对于每一个新 worker克隆 <code>Arc</code> 来增加引用计数,如此这些 worker 就可以共享接收者的所有权了。</p>
<p>通过这些修改,代码可以编译了!我们做到了!</p>
<h4 id="实现-execute-方法"><a class="header" href="#实现-execute-方法">实现 <code>execute</code> 方法</a></h4>
<p>最后让我们实现 <code>ThreadPool</code> 上的 <code>execute</code> 方法。同时也要修改 <code>Job</code> 结构体:它将不再是结构体,<code>Job</code> 将是一个有着 <code>execute</code> 接收到的闭包类型的 trait 对象的类型别名。第二十章 <a href="ch20-04-advanced-types.html#%E7%B1%BB%E5%9E%8B%E5%88%AB%E5%90%8D%E7%94%A8%E6%9D%A5%E5%88%9B%E5%BB%BA%E7%B1%BB%E5%9E%8B%E5%90%8C%E4%B9%89%E8%AF%8D">“类型别名用来创建类型同义词”</a> 部分提到过,类型别名允许将长的类型变短。观察示例 20-19</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>// --snip--
type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
impl ThreadPool {
// --snip--
<span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span><span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> ThreadPool { workers, sender }
</span><span class="boring"> }
</span>
pub fn execute&lt;F&gt;(&amp;self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
// --snip--
<span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: thread::JoinHandle&lt;()&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Worker {
</span><span class="boring"> fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
</span><span class="boring"> let thread = thread::spawn(|| {
</span><span class="boring"> receiver;
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> Worker { id, thread }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 20-19: 为存放每一个闭包的 <code>Box</code> 创建一个 <code>Job</code> 类型别名,接着在信道中发出任务</span></p>
<p>在使用 <code>execute</code> 得到的闭包新建 <code>Job</code> 实例之后,将这些任务从信道的发送端发出。这里调用 <code>send</code> 上的 <code>unwrap</code>,因为发送可能会失败,这可能发生于例如停止了所有线程执行的情况,这意味着接收端停止接收新消息了。不过目前我们无法停止线程执行;只要线程池存在它们就会一直执行。使用 <code>unwrap</code> 是因为我们知道失败不可能发生,即便编译器不这么认为。</p>
<p>不过到此事情还没有结束!在 worker 中,传递给 <code>thread::spawn</code> 的闭包仍然还只是 <strong>引用</strong> 了信道的接收端。相反我们需要闭包一直循环,向信道的接收端请求任务,并在得到任务时执行它们。如示例 20-20 对 <code>Worker::new</code> 做出修改:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
</span><span class="boring">
</span><span class="boring">impl ThreadPool {
</span><span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span><span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> ThreadPool { workers, sender }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> let job = Box::new(f);
</span><span class="boring">
</span><span class="boring"> self.sender.send(job).unwrap();
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: thread::JoinHandle&lt;()&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>// --snip--
impl Worker {
fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
let thread = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv().unwrap();
println!("Worker {id} got a job; executing.");
job();
});
Worker { id, thread }
}
}</code></pre>
<p><span class="caption">示例 20-20: 在 worker 线程中接收并执行任务</span></p>
<p>这里,首先在 <code>receiver</code> 上调用了 <code>lock</code> 来获取互斥器,接着 <code>unwrap</code> 在出现任何错误时 panic。如果互斥器处于一种叫做 <strong>被污染</strong><em>poisoned</em>)的状态时获取锁可能会失败,这可能发生于其他线程在持有锁时 panic 了且没有释放锁。在这种情况下,调用 <code>unwrap</code> 使其 panic 是正确的行为。请随意将 <code>unwrap</code> 改为包含有意义错误信息的 <code>expect</code></p>
<p>如果锁定了互斥器,接着调用 <code>recv</code> 从信道中接收 <code>Job</code>。最后的 <code>unwrap</code> 也绕过了一些错误,这可能发生于持有信道发送端的线程停止的情况,类似于如果接收端关闭时 <code>send</code> 方法如何返回 <code>Err</code> 一样。</p>
<p>调用 <code>recv</code> 会阻塞当前线程,所以如果还没有任务,其会等待直到有可用的任务。<code>Mutex&lt;T&gt;</code> 确保一次只有一个 <code>Worker</code> 线程尝试请求任务。</p>
<p>现在线程池处于可以运行的状态了!执行 <code>cargo run</code> 并发起一些请求:</p>
<pre><code class="language-console">$ cargo run
Compiling hello v0.1.0 (file:///projects/hello)
warning: field is never read: `workers`
--&gt; src/lib.rs:7:5
|
7 | workers: Vec&lt;Worker&gt;,
| ^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: field is never read: `id`
--&gt; src/lib.rs:48:5
|
48 | id: usize,
| ^^^^^^^^^
warning: field is never read: `thread`
--&gt; src/lib.rs:49:5
|
49 | thread: thread::JoinHandle&lt;()&gt;,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: `hello` (lib) generated 3 warnings
Finished dev [unoptimized + debuginfo] target(s) in 1.40s
Running `target/debug/hello`
Worker 0 got a job; executing.
Worker 2 got a job; executing.
Worker 1 got a job; executing.
Worker 3 got a job; executing.
Worker 0 got a job; executing.
Worker 2 got a job; executing.
Worker 1 got a job; executing.
Worker 3 got a job; executing.
Worker 0 got a job; executing.
Worker 2 got a job; executing.
</code></pre>
<p>成功了!现在我们有了一个可以异步执行连接的线程池!它绝不会创建超过四个线程,所以当 server 收到大量请求时系统也不会负担过重。如果请求 <em>/sleep</em>server 也能够通过另外一个线程处理其他请求。</p>
<blockquote>
<p>注意如果同时在多个浏览器窗口打开 <em>/sleep</em>,它们可能会彼此间隔地加载 5 秒,因为一些浏览器出于缓存的原因会顺序执行相同请求的多个实例。这些限制并不是由于我们的 web server 造成的。</p>
</blockquote>
<p>在学习了第十七章和第十八章的 <code>while let</code> 循环之后,你可能会好奇为何不能如此编写 worker 线程,如示例 20-21 所示:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore not_desired_behavior"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
</span><span class="boring">
</span><span class="boring">impl ThreadPool {
</span><span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span><span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> ThreadPool { workers, sender }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> let job = Box::new(f);
</span><span class="boring">
</span><span class="boring"> self.sender.send(job).unwrap();
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: thread::JoinHandle&lt;()&gt;,
</span><span class="boring">}
</span>// --snip--
impl Worker {
fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
let thread = thread::spawn(move || {
while let Ok(job) = receiver.lock().unwrap().recv() {
println!("Worker {id} got a job; executing.");
job();
}
});
Worker { id, thread }
}
}</code></pre>
<p><span class="caption">示例 20-21: 一个使用 <code>while let</code><code>Worker::new</code> 替代实现</span></p>
<p>这段代码可以编译和运行,但是并不会产生所期望的线程行为:一个慢请求仍然会导致其他请求等待执行。其原因有些微妙:<code>Mutex</code> 结构体没有公有 <code>unlock</code> 方法,因为锁的所有权依赖 <code>lock</code> 方法返回的 <code>LockResult&lt;MutexGuard&lt;T&gt;&gt;</code><code>MutexGuard&lt;T&gt;</code> 的生命周期。这允许借用检查器在编译时确保绝不会在没有持有锁的情况下访问由 <code>Mutex</code> 守护的资源,不过如果没有认真的思考 <code>MutexGuard&lt;T&gt;</code> 的生命周期的话,也可能会导致比预期更久的持有锁。</p>
<p>示例 20-20 中的代码使用的 <code>let job = receiver.lock().unwrap().recv().unwrap();</code> 之所以可以工作是因为对于 <code>let</code> 来说,当 <code>let</code> 语句结束时任何表达式中等号右侧使用的临时值都会立即被丢弃。然而 <code>while let</code><code>if let</code><code>match</code>)直到相关的代码块结束都不会丢弃临时值。在示例 20-21 中,<code>job()</code> 调用期间锁一直持续,这也意味着其他的 worker 无法接受任务。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="优雅停机与清理"><a class="header" href="#优雅停机与清理">优雅停机与清理</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch21-03-graceful-shutdown-and-cleanup.md">ch21-03-graceful-shutdown-and-cleanup.md</a>
<br>
commit 3e5105b52f7e8d3d95def07ffade4dcb1cfdee27</p>
</blockquote>
<p>示例 20-20 中的代码如期通过使用线程池异步的响应请求。这里有一些警告说 <code>workers</code><code>id</code><code>thread</code> 字段没有直接被使用,这提醒了我们并没有清理所有的内容。当使用不那么优雅的 <span class="keystroke">ctrl-c</span> 终止主线程时,所有其他线程也会立刻停止,即便它们正处于处理请求的过程中。</p>
<p>现在我们要为 <code>ThreadPool</code> 实现 <code>Drop</code> trait 对线程池中的每一个线程调用 <code>join</code>,这样这些线程将会执行完它们的请求。接着会为 <code>ThreadPool</code> 实现一个告诉线程它们应该停止接收新请求并结束的方式。为了实践这些代码,修改 server 在优雅停机graceful shutdown之前只接受两个请求。</p>
<h3 id="为-threadpool-实现-drop-trait"><a class="header" href="#为-threadpool-实现-drop-trait"><code>ThreadPool</code> 实现 <code>Drop</code> Trait</a></h3>
<p>现在开始为线程池实现 <code>Drop</code>。当线程池被丢弃时,应该 join 所有线程以确保它们完成其操作。示例 20-22 展示了 <code>Drop</code> 实现的第一次尝试;这些代码还不能够编译:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
</span><span class="boring">
</span><span class="boring">impl ThreadPool {
</span><span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span><span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> ThreadPool { workers, sender }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> let job = Box::new(f);
</span><span class="boring">
</span><span class="boring"> self.sender.send(job).unwrap();
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>impl Drop for ThreadPool {
fn drop(&amp;mut self) {
for worker in &amp;mut self.workers {
println!("Shutting down worker {}", worker.id);
worker.thread.join().unwrap();
}
}
}
<span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: thread::JoinHandle&lt;()&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Worker {
</span><span class="boring"> fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
</span><span class="boring"> let thread = thread::spawn(move || loop {
</span><span class="boring"> let job = receiver.lock().unwrap().recv().unwrap();
</span><span class="boring">
</span><span class="boring"> println!("Worker {id} got a job; executing.");
</span><span class="boring">
</span><span class="boring"> job();
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> Worker { id, thread }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 20-22: 当线程池离开作用域时 join 每个线程</span></p>
<p>这里首先遍历线程池中的每个 <code>workers</code>。这里使用了 <code>&amp;mut</code> 因为 <code>self</code> 本身是一个可变引用而且也需要能够修改 <code>worker</code>。对于每一个线程,会打印出说明信息表明此特定 worker 正在关闭,接着在 worker 线程上调用 <code>join</code>。如果 <code>join</code> 调用失败,通过 <code>unwrap</code> 使得 panic 并进行不优雅的关闭。</p>
<p>如下是尝试编译代码时得到的错误:</p>
<pre><code class="language-console">$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference
--&gt; src/lib.rs:52:13
|
52 | worker.thread.join().unwrap();
| ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call
| |
| move occurs because `worker.thread` has type `JoinHandle&lt;()&gt;`, which does not implement the `Copy` trait
|
note: `JoinHandle::&lt;T&gt;::join` takes ownership of the receiver `self`, which moves `worker.thread`
--&gt; /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/std/src/thread/mod.rs:1778:17
For more information about this error, try `rustc --explain E0507`.
error: could not compile `hello` (lib) due to 1 previous error
</code></pre>
<p>这里的错误告诉我们并不能调用 <code>join</code>,因为我们只有每一个 <code>worker</code> 的可变借用,而 <code>join</code> 需要获取其参数的所有权。为了解决这个问题,需要一个方法将 <code>thread</code> 移动出拥有其所有权的 <code>Worker</code> 实例以便 <code>join</code> 可以消费这个线程。示例 17-15 中我们曾见过这么做的方法:如果 <code>Worker</code> 存放的是 <code>Option&lt;thread::JoinHandle&lt;()&gt;</code>,就可以在 <code>Option</code> 上调用 <code>take</code> 方法将值从 <code>Some</code> 成员中移动出来而对 <code>None</code> 成员不做处理。换句话说,正在运行的 <code>Worker</code><code>thread</code> 将是 <code>Some</code> 成员值,而当需要清理 worker 时,将 <code>Some</code> 替换为 <code>None</code>,这样 worker 就没有可以运行的线程了。</p>
<p>为此需要更新 <code>Worker</code> 的定义为如下:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
</span><span class="boring">
</span><span class="boring">impl ThreadPool {
</span><span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span><span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> ThreadPool { workers, sender }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> let job = Box::new(f);
</span><span class="boring">
</span><span class="boring"> self.sender.send(job).unwrap();
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Drop for ThreadPool {
</span><span class="boring"> fn drop(&amp;mut self) {
</span><span class="boring"> for worker in &amp;mut self.workers {
</span><span class="boring"> println!("Shutting down worker {}", worker.id);
</span><span class="boring">
</span><span class="boring"> worker.thread.join().unwrap();
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>struct Worker {
id: usize,
thread: Option&lt;thread::JoinHandle&lt;()&gt;&gt;,
}
<span class="boring">
</span><span class="boring">impl Worker {
</span><span class="boring"> fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
</span><span class="boring"> let thread = thread::spawn(move || loop {
</span><span class="boring"> let job = receiver.lock().unwrap().recv().unwrap();
</span><span class="boring">
</span><span class="boring"> println!("Worker {id} got a job; executing.");
</span><span class="boring">
</span><span class="boring"> job();
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> Worker { id, thread }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>现在依靠编译器来找出其他需要修改的地方。check 代码会得到两个错误:</p>
<pre><code class="language-console">$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no method named `join` found for enum `Option` in the current scope
--&gt; src/lib.rs:52:27
|
52 | worker.thread.join().unwrap();
| ^^^^ method not found in `Option&lt;JoinHandle&lt;()&gt;&gt;`
|
note: the method `join` exists on the type `JoinHandle&lt;()&gt;`
--&gt; /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/std/src/thread/mod.rs:1778:5
help: consider using `Option::expect` to unwrap the `JoinHandle&lt;()&gt;` value, panicking if the value is an `Option::None`
|
52 | worker.thread.expect("REASON").join().unwrap();
| +++++++++++++++++
error[E0308]: mismatched types
--&gt; src/lib.rs:72:22
|
72 | Worker { id, thread }
| ^^^^^^ expected `Option&lt;JoinHandle&lt;()&gt;&gt;`, found `JoinHandle&lt;_&gt;`
|
= note: expected enum `Option&lt;JoinHandle&lt;()&gt;&gt;`
found struct `JoinHandle&lt;_&gt;`
help: try wrapping the expression in `Some`
|
72 | Worker { id, thread: Some(thread) }
| +++++++++++++ +
Some errors have detailed explanations: E0308, E0599.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `hello` (lib) due to 2 previous errors
</code></pre>
<p>让我们修复第二个错误,它指向 <code>Worker::new</code> 结尾的代码;当新建 <code>Worker</code> 时需要将 <code>thread</code> 值封装进 <code>Some</code>。做出如下改变以修复问题:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
</span><span class="boring">
</span><span class="boring">impl ThreadPool {
</span><span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span><span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> ThreadPool { workers, sender }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> let job = Box::new(f);
</span><span class="boring">
</span><span class="boring"> self.sender.send(job).unwrap();
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Drop for ThreadPool {
</span><span class="boring"> fn drop(&amp;mut self) {
</span><span class="boring"> for worker in &amp;mut self.workers {
</span><span class="boring"> println!("Shutting down worker {}", worker.id);
</span><span class="boring">
</span><span class="boring"> worker.thread.join().unwrap();
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: Option&lt;thread::JoinHandle&lt;()&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>impl Worker {
fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
// --snip--
<span class="boring"> let thread = thread::spawn(move || loop {
</span><span class="boring"> let job = receiver.lock().unwrap().recv().unwrap();
</span><span class="boring">
</span><span class="boring"> println!("Worker {id} got a job; executing.");
</span><span class="boring">
</span><span class="boring"> job();
</span><span class="boring"> });
</span><span class="boring">
</span> Worker {
id,
thread: Some(thread),
}
}
}</code></pre>
<p>第一个错误位于 <code>Drop</code> 实现中。之前提到过要调用 <code>Option</code> 上的 <code>take</code><code>thread</code> 移动出 <code>worker</code>。如下改变会修复问题:</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust ignore not_desired_behavior"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: mpsc::Sender&lt;Job&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
</span><span class="boring">
</span><span class="boring">impl ThreadPool {
</span><span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span><span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> ThreadPool { workers, sender }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> let job = Box::new(f);
</span><span class="boring">
</span><span class="boring"> self.sender.send(job).unwrap();
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span>impl Drop for ThreadPool {
fn drop(&amp;mut self) {
for worker in &amp;mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
<span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: Option&lt;thread::JoinHandle&lt;()&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Worker {
</span><span class="boring"> fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
</span><span class="boring"> let thread = thread::spawn(move || loop {
</span><span class="boring"> let job = receiver.lock().unwrap().recv().unwrap();
</span><span class="boring">
</span><span class="boring"> println!("Worker {id} got a job; executing.");
</span><span class="boring">
</span><span class="boring"> job();
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> Worker {
</span><span class="boring"> id,
</span><span class="boring"> thread: Some(thread),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p>如第十八章我们见过的,<code>Option</code> 上的 <code>take</code> 方法会取出 <code>Some</code> 而留下 <code>None</code>。使用 <code>if let</code> 解构 <code>Some</code> 并得到线程,接着在线程上调用 <code>join</code>。如果 worker 的线程已然是 <code>None</code>,就知道此时这个 worker 已经清理了其线程所以无需做任何操作。</p>
<h3 id="向线程发送信号使其停止接收任务"><a class="header" href="#向线程发送信号使其停止接收任务">向线程发送信号使其停止接收任务</a></h3>
<p>有了所有这些修改,代码就能编译且没有任何警告。不过也有坏消息,这些代码还不能以我们期望的方式运行。问题的关键在于 <code>Worker</code> 中分配的线程所运行的闭包中的逻辑:调用 <code>join</code> 并不会关闭线程,因为它们一直 <code>loop</code> 来寻找任务。如果采用这个实现来尝试丢弃 <code>ThreadPool</code>,则主线程会永远阻塞在等待第一个线程结束上。</p>
<p>为了修复这个问题,我们将修改 <code>ThreadPool</code><code>drop</code> 实现并修改 <code>Worker</code> 循环。</p>
<p>首先修改 <code>ThreadPool</code><code>drop</code> 实现在等待线程结束前显式丢弃 <code>sender</code>。示例 20-23 展示了 <code>ThreadPool</code> 显式丢弃 <code>sender</code> 所作的修改。我们使用了与之前处理线程时相同的 <code>Option</code><code>take</code> 技术以便能从 <code>ThreadPool</code> 中移动 <code>sender</code></p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground not_desired_behavior"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span>pub struct ThreadPool {
workers: Vec&lt;Worker&gt;,
sender: Option&lt;mpsc::Sender&lt;Job&gt;&gt;,
}
// --snip--
<span class="boring">
</span><span class="boring">type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
</span><span class="boring">
</span>impl ThreadPool {
<span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span> pub fn new(size: usize) -&gt; ThreadPool {
// --snip--
<span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span> ThreadPool {
workers,
sender: Some(sender),
}
}
pub fn execute&lt;F&gt;(&amp;self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.as_ref().unwrap().send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&amp;mut self) {
drop(self.sender.take());
for worker in &amp;mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
<span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: Option&lt;thread::JoinHandle&lt;()&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Worker {
</span><span class="boring"> fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
</span><span class="boring"> let thread = thread::spawn(move || loop {
</span><span class="boring"> let job = receiver.lock().unwrap().recv().unwrap();
</span><span class="boring">
</span><span class="boring"> println!("Worker {id} got a job; executing.");
</span><span class="boring">
</span><span class="boring"> job();
</span><span class="boring"> });
</span><span class="boring">
</span><span class="boring"> Worker {
</span><span class="boring"> id,
</span><span class="boring"> thread: Some(thread),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 20-23: 在 join worker 线程之前显式丢弃 <code>sender</code></span></p>
<p>丢弃 <code>sender</code> 会关闭信道,这表明不会有更多的消息被发送。这时 worker 中的无限循环中的所有 <code>recv</code> 调用都会返回错误。在示例 20-24 中,我们修改 <code>Worker</code> 循环在这种情况下优雅地退出,这意味着当 <code>ThreadPool</code><code>drop</code> 实现调用 <code>join</code> 时线程会结束。</p>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground"><span class="boring">use std::{
</span><span class="boring"> sync::{mpsc, Arc, Mutex},
</span><span class="boring"> thread,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">pub struct ThreadPool {
</span><span class="boring"> workers: Vec&lt;Worker&gt;,
</span><span class="boring"> sender: Option&lt;mpsc::Sender&lt;Job&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
</span><span class="boring">
</span><span class="boring">impl ThreadPool {
</span><span class="boring"> /// Create a new ThreadPool.
</span><span class="boring"> ///
</span><span class="boring"> /// The size is the number of threads in the pool.
</span><span class="boring"> ///
</span><span class="boring"> /// # Panics
</span><span class="boring"> ///
</span><span class="boring"> /// The `new` function will panic if the size is zero.
</span><span class="boring"> pub fn new(size: usize) -&gt; ThreadPool {
</span><span class="boring"> assert!(size &gt; 0);
</span><span class="boring">
</span><span class="boring"> let (sender, receiver) = mpsc::channel();
</span><span class="boring">
</span><span class="boring"> let receiver = Arc::new(Mutex::new(receiver));
</span><span class="boring">
</span><span class="boring"> let mut workers = Vec::with_capacity(size);
</span><span class="boring">
</span><span class="boring"> for id in 0..size {
</span><span class="boring"> workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> ThreadPool {
</span><span class="boring"> workers,
</span><span class="boring"> sender: Some(sender),
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> pub fn execute&lt;F&gt;(&amp;self, f: F)
</span><span class="boring"> where
</span><span class="boring"> F: FnOnce() + Send + 'static,
</span><span class="boring"> {
</span><span class="boring"> let job = Box::new(f);
</span><span class="boring">
</span><span class="boring"> self.sender.as_ref().unwrap().send(job).unwrap();
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Drop for ThreadPool {
</span><span class="boring"> fn drop(&amp;mut self) {
</span><span class="boring"> drop(self.sender.take());
</span><span class="boring">
</span><span class="boring"> for worker in &amp;mut self.workers {
</span><span class="boring"> println!("Shutting down worker {}", worker.id);
</span><span class="boring">
</span><span class="boring"> if let Some(thread) = worker.thread.take() {
</span><span class="boring"> thread.join().unwrap();
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">struct Worker {
</span><span class="boring"> id: usize,
</span><span class="boring"> thread: Option&lt;thread::JoinHandle&lt;()&gt;&gt;,
</span><span class="boring">}
</span><span class="boring">
</span>impl Worker {
fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv();
match message {
Ok(job) =&gt; {
println!("Worker {id} got a job; executing.");
job();
}
Err(_) =&gt; {
println!("Worker {id} disconnected; shutting down.");
break;
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}</code></pre>
<p><span class="caption">示例 20-24<code>recv</code> 返回错误时显式退出循环</span></p>
<p>为了实践这些代码,如示例 20-25 所示修改 <code>main</code> 在优雅停机 server 之前只接受两个请求:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore"><span class="boring">use hello::ThreadPool;
</span><span class="boring">use std::{
</span><span class="boring"> fs,
</span><span class="boring"> io::{prelude::*, BufReader},
</span><span class="boring"> net::{TcpListener, TcpStream},
</span><span class="boring"> thread,
</span><span class="boring"> time::Duration,
</span><span class="boring">};
</span><span class="boring">
</span>fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.");
}
<span class="boring">
</span><span class="boring">fn handle_connection(mut stream: TcpStream) {
</span><span class="boring"> let buf_reader = BufReader::new(&amp;stream);
</span><span class="boring"> let request_line = buf_reader.lines().next().unwrap().unwrap();
</span><span class="boring">
</span><span class="boring"> let (status_line, filename) = match &amp;request_line[..] {
</span><span class="boring"> "GET / HTTP/1.1" =&gt; ("HTTP/1.1 200 OK", "hello.html"),
</span><span class="boring"> "GET /sleep HTTP/1.1" =&gt; {
</span><span class="boring"> thread::sleep(Duration::from_secs(5));
</span><span class="boring"> ("HTTP/1.1 200 OK", "hello.html")
</span><span class="boring"> }
</span><span class="boring"> _ =&gt; ("HTTP/1.1 404 NOT FOUND", "404.html"),
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> let contents = fs::read_to_string(filename).unwrap();
</span><span class="boring"> let length = contents.len();
</span><span class="boring">
</span><span class="boring"> let response =
</span><span class="boring"> format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
</span><span class="boring">
</span><span class="boring"> stream.write_all(response.as_bytes()).unwrap();
</span><span class="boring">}</span></code></pre>
<p><span class="caption">示例 20-25: 在处理两个请求之后通过退出循环来停止 server</span></p>
<p>你不会希望真实世界的 web server 只处理两次请求就停机了,这只是为了展示优雅停机和清理处于正常工作状态。</p>
<p><code>take</code> 方法定义于 <code>Iterator</code> trait这里限制循环最多头 2 次。<code>ThreadPool</code> 会在 <code>main</code> 的结尾离开作用域,而且还会看到 <code>drop</code> 实现的运行。</p>
<p>使用 <code>cargo run</code> 启动 server并发起三个请求。第三个请求应该会失败而终端的输出应该看起来像这样</p>
<pre><code class="language-console">$ cargo run
Compiling hello v0.1.0 (file:///projects/hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.0s
Running `target/debug/hello`
Worker 0 got a job; executing.
Shutting down.
Shutting down worker 0
Worker 3 got a job; executing.
Worker 1 disconnected; shutting down.
Worker 2 disconnected; shutting down.
Worker 3 disconnected; shutting down.
Worker 0 disconnected; shutting down.
Shutting down worker 1
Shutting down worker 2
Shutting down worker 3
</code></pre>
<p>可能会出现不同顺序的 worker 和信息输出。可以从信息中看到服务是如何运行的worker 0 和 worker 3 获取了头两个请求。server 会在头第二个请求后停止接受请求,<code>ThreadPool</code><code>Drop</code> 实现甚至会在 worker 3 开始工作之前就开始执行。丢弃 <code>sender</code> 会断开所有 worker 的连接并让它们关闭。每个 worker 在断开时会打印出一个信息,接着线程池调用 <code>join</code> 来等待每一个 worker 线程结束。</p>
<p>这个特定的运行过程中一个有趣的地方在于:<code>ThreadPool</code> 丢弃 <code>sender</code>,而在任何线程收到消息之前,就尝试 join worker 0 了。worker 0 还没有从 <code>recv</code> 获得一个错误,所以主线程阻塞直到 worker 0 结束。与此同时worker 3 接收到一个任务接着所有线程会收到一个错误。一旦 worker 0 结束,主线程就等待余下其他 worker 结束。此时它们都退出了循环并停止。</p>
<p>恭喜!现在我们完成了这个项目,也有了一个使用线程池异步响应请求的基础 web server。我们能对 server 执行优雅停机,它会清理线程池中的所有线程。</p>
<p>如下是完整的代码参考:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><code class="language-rust ignore">use hello::ThreadPool;
use std::{
fs,
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
thread,
time::Duration,
};
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.");
}
fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&amp;stream);
let request_line = buf_reader.lines().next().unwrap().unwrap();
let (status_line, filename) = match &amp;request_line[..] {
"GET / HTTP/1.1" =&gt; ("HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" =&gt; {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
_ =&gt; ("HTTP/1.1 404 NOT FOUND", "404.html"),
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();
let response =
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(response.as_bytes()).unwrap();
}</code></pre>
<p><span class="filename">文件名src/lib.rs</span></p>
<pre><code class="language-rust noplayground">use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec&lt;Worker&gt;,
sender: Option&lt;mpsc::Sender&lt;Job&gt;&gt;,
}
type Job = Box&lt;dyn FnOnce() + Send + 'static&gt;;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -&gt; ThreadPool {
assert!(size &gt; 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&amp;receiver)));
}
ThreadPool {
workers,
sender: Some(sender),
}
}
pub fn execute&lt;F&gt;(&amp;self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.as_ref().unwrap().send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&amp;mut self) {
drop(self.sender.take());
for worker in &amp;mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
struct Worker {
id: usize,
thread: Option&lt;thread::JoinHandle&lt;()&gt;&gt;,
}
impl Worker {
fn new(id: usize, receiver: Arc&lt;Mutex&lt;mpsc::Receiver&lt;Job&gt;&gt;&gt;) -&gt; Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv();
match message {
Ok(job) =&gt; {
println!("Worker {id} got a job; executing.");
job();
}
Err(_) =&gt; {
println!("Worker {id} disconnected; shutting down.");
break;
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}</code></pre>
<p>这里还有很多可以做的事!如果你希望继续增强这个项目,如下是一些点子:</p>
<ul>
<li><code>ThreadPool</code> 和其公有方法增加更多文档</li>
<li>为库的功能增加测试</li>
<li><code>unwrap</code> 调用改为更健壮的错误处理</li>
<li>使用 <code>ThreadPool</code> 进行其他不同于处理网络请求的任务</li>
<li><a href="https://crates.io/">crates.io</a> 上寻找一个线程池 crate 并使用它实现一个类似的 web server将其 API 和鲁棒性与我们的实现做对比</li>
</ul>
<h2 id="总结-19"><a class="header" href="#总结-19">总结</a></h2>
<p>好极了!你结束了本书的学习!由衷感谢你同我们一道加入这次 Rust 之旅。现在你已经准备好出发并实现自己的 Rust 项目并帮助他人了。请不要忘记我们的社区,这里有其他 Rustaceans 正乐于帮助你迎接 Rust 之路上的任何挑战。</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="附录"><a class="header" href="#附录">附录</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/appendix-00.md">appendix-00.md</a>
<br>
commit 1fedfc4b96c2017f64ecfcf41a0a07e2e815f24f</p>
</blockquote>
<p>附录部分包含一些在你的 Rust 之旅中可能用到的参考资料。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="附录-a关键字"><a class="header" href="#附录-a关键字">附录 A关键字</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/appendix-01-keywords.md">appendix-01-keywords.md</a>
<br>
commit efbafdba3618487fbc9305318fcab9775132ac15</p>
</blockquote>
<p>下面的列表包含 Rust 中正在使用或者以后会用到的关键字。因此,这些关键字不能被用作标识符(除了 “<a href="appendix-01-keywords.html#%E5%8E%9F%E5%A7%8B%E6%A0%87%E8%AF%86%E7%AC%A6">原始标识符</a>” 部分介绍的原始标识符这包括函数、变量、参数、结构体字段、模块、crate、常量、宏、静态值、属性、类型、trait 或生命周期
的名字。</p>
<h3 id="目前正在使用的关键字"><a class="header" href="#目前正在使用的关键字">目前正在使用的关键字</a></h3>
<p>如下关键字目前有对应其描述的功能。</p>
<ul>
<li><code>as</code> - 强制类型转换,消除特定包含项的 trait 的歧义,或者对 <code>use</code> 语句中的项重命名</li>
<li><code>async</code> - 返回一个 <code>Future</code> 而不是阻塞当前线程</li>
<li><code>await</code> - 暂停执行直到 <code>Future</code> 的结果就绪</li>
<li><code>break</code> - 立刻退出循环</li>
<li><code>const</code> - 定义常量或不变裸指针constant raw pointer</li>
<li><code>continue</code> - 继续进入下一次循环迭代</li>
<li><code>crate</code> - 在模块路径中,代指 crate root</li>
<li><code>dyn</code> - 动态分发 trait 对象</li>
<li><code>else</code> - 作为 <code>if</code><code>if let</code> 控制流结构的 fallback</li>
<li><code>enum</code> - 定义一个枚举</li>
<li><code>extern</code> - 链接一个外部函数或变量</li>
<li><code>false</code> - 布尔字面值 <code>false</code></li>
<li><code>fn</code> - 定义一个函数或 <strong>函数指针类型</strong> (<em>function pointer type</em>)</li>
<li><code>for</code> - 遍历一个迭代器或实现一个 trait 或者指定一个更高级的生命周期</li>
<li><code>if</code> - 基于条件表达式的结果分支</li>
<li><code>impl</code> - 实现自有或 trait 功能</li>
<li><code>in</code> - <code>for</code> 循环语法的一部分</li>
<li><code>let</code> - 绑定一个变量</li>
<li><code>loop</code> - 无条件循环</li>
<li><code>match</code> - 模式匹配</li>
<li><code>mod</code> - 定义一个模块</li>
<li><code>move</code> - 使闭包获取其所捕获项的所有权</li>
<li><code>mut</code> - 表示引用、裸指针或模式绑定的可变性</li>
<li><code>pub</code> - 表示结构体字段、<code>impl</code> 块或模块的公有可见性</li>
<li><code>ref</code> - 通过引用绑定</li>
<li><code>return</code> - 从函数中返回</li>
<li><code>Self</code> - 定义或实现 trait 的类型的类型别名</li>
<li><code>self</code> - 表示方法本身或当前模块</li>
<li><code>static</code> - 表示全局变量或在整个程序执行期间保持其生命周期</li>
<li><code>struct</code> - 定义一个结构体</li>
<li><code>super</code> - 表示当前模块的父模块</li>
<li><code>trait</code> - 定义一个 trait</li>
<li><code>true</code> - 布尔字面值 <code>true</code></li>
<li><code>type</code> - 定义一个类型别名或关联类型</li>
<li><code>union</code> - 定义一个 <a href="https://doc.rust-lang.org/reference/items/unions.html">union</a> 并且是 union 声明中唯一用到的关键字</li>
<li><code>unsafe</code> - 表示不安全的代码、函数、trait 或实现</li>
<li><code>use</code> - 引入外部空间的符号</li>
<li><code>where</code> - 表示一个约束类型的从句</li>
<li><code>while</code> - 基于一个表达式的结果判断是否进行循环</li>
</ul>
<h3 id="保留做将来使用的关键字"><a class="header" href="#保留做将来使用的关键字">保留做将来使用的关键字</a></h3>
<p>如下关键字没有任何功能,不过由 Rust 保留以备将来的应用。</p>
<ul>
<li><code>abstract</code></li>
<li><code>become</code></li>
<li><code>box</code></li>
<li><code>do</code></li>
<li><code>final</code></li>
<li><code>macro</code></li>
<li><code>override</code></li>
<li><code>priv</code></li>
<li><code>try</code></li>
<li><code>typeof</code></li>
<li><code>unsized</code></li>
<li><code>virtual</code></li>
<li><code>yield</code></li>
</ul>
<h3 id="原始标识符"><a class="header" href="#原始标识符">原始标识符</a></h3>
<p>原始标识符Raw identifiers允许你使用通常不能使用的关键字其带有 <code>r#</code> 前缀。</p>
<p>例如,<code>match</code> 是关键字。如果尝试编译如下使用 <code>match</code> 作为名字的函数:</p>
<pre><code class="language-rust ignore does_not_compile">fn match(needle: &amp;str, haystack: &amp;str) -&gt; bool {
haystack.contains(needle)
}</code></pre>
<p>会得到这个错误:</p>
<pre><code class="language-text">error: expected identifier, found keyword `match`
--&gt; src/main.rs:4:4
|
4 | fn match(needle: &amp;str, haystack: &amp;str) -&gt; bool {
| ^^^^^ expected identifier, found keyword
</code></pre>
<p>该错误表示你不能将关键字 <code>match</code> 用作函数标识符。你可以使用原始标识符将 <code>match</code> 作为函数名称使用:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn r#match(needle: &amp;str, haystack: &amp;str) -&gt; bool {
haystack.contains(needle)
}
fn main() {
assert!(r#match("foo", "foobar"));
}</code></pre></pre>
<p>此代码编译没有任何错误。注意 <code>r#</code> 前缀需同时用于函数名定义和 <code>main</code> 函数中的调用。</p>
<p>原始标识符允许使用你选择的任何单词作为标识符,即使该单词恰好是保留关键字。这给予了我们更大的自由来选择名字,这样与其他语言交互式就不用考虑到关键字问题,在要交互的语言中这个名字不是关键字。此外,原始标识符允许你使用以不同于你的 crate 使用的 Rust 版本编写的库。比如,<code>try</code> 在 2015 edition 中不是关键字,而在 2018 edition 则是。所以如果用 2015 edition 编写的库中带有 <code>try</code> 函数,在 2018 edition 中调用时就需要使用原始标识符语法,在这里是 <code>r#try</code>。有关版本的更多信息,请参见<a href="appendix-05-editions.html">附录 E</a></p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="附录-b运算符与符号"><a class="header" href="#附录-b运算符与符号">附录 B运算符与符号</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/appendix-02-operators.md">appendix-02-operators.md</a>
<br />
commit 396fdb69de7fb18f24b15c7ad13491b1c1fa7231</p>
</blockquote>
<p>该附录包含了 Rust 语法的词汇表包括运算符以及其他的符号这些符号单独出现或出现在路径、泛型、trait bounds、宏、属性、注释、元组以及大括号上下文中。</p>
<h3 id="运算符"><a class="header" href="#运算符">运算符</a></h3>
<p>表 B-1 包含了 Rust 中的运算符、运算符如何出现在上下文中的示例、简短解释以及该运算符是否可重载。如果一个运算符是可重载的,则该运算符上用于重载的相关 trait 也会列出。</p>
<p><span class="caption">表 B-1: 运算符</span></p>
<div class="table-wrapper"><table><thead><tr><th>运算符</th><th>示例</th><th>解释</th><th>是否可重载</th></tr></thead><tbody>
<tr><td><code>!</code></td><td><code>ident!(...)</code>, <code>ident!{...}</code>, <code>ident![...]</code></td><td>宏展开</td><td></td></tr>
<tr><td><code>!</code></td><td><code>!expr</code></td><td>按位非或逻辑非</td><td><code>Not</code></td></tr>
<tr><td><code>!=</code></td><td><code>expr != expr</code></td><td>不等比较</td><td><code>PartialEq</code></td></tr>
<tr><td><code>%</code></td><td><code>expr % expr</code></td><td>算术取余</td><td><code>Rem</code></td></tr>
<tr><td><code>%=</code></td><td><code>var %= expr</code></td><td>算术取余与赋值</td><td><code>RemAssign</code></td></tr>
<tr><td><code>&amp;</code></td><td><code>&amp;expr</code>, <code>&amp;mut expr</code></td><td>借用</td><td></td></tr>
<tr><td><code>&amp;</code></td><td><code>&amp;type</code>, <code>&amp;mut type</code>, <code>&amp;'a type</code>, <code>&amp;'a mut type</code></td><td>借用指针类型</td><td></td></tr>
<tr><td><code>&amp;</code></td><td><code>expr &amp; expr</code></td><td>按位与</td><td><code>BitAnd</code></td></tr>
<tr><td><code>&amp;=</code></td><td><code>var &amp;= expr</code></td><td>按位与及赋值</td><td><code>BitAndAssign</code></td></tr>
<tr><td><code>&amp;&amp;</code></td><td><code>expr &amp;&amp; expr</code></td><td>短路Short-circuiting逻辑与</td><td></td></tr>
<tr><td><code>*</code></td><td><code>expr * expr</code></td><td>算术乘法</td><td><code>Mul</code></td></tr>
<tr><td><code>*=</code></td><td><code>var *= expr</code></td><td>算术乘法与赋值</td><td><code>MulAssign</code></td></tr>
<tr><td><code>*</code></td><td><code>*expr</code></td><td>解引用</td><td><code>Deref</code></td></tr>
<tr><td><code>*</code></td><td><code>*const type</code>, <code>*mut type</code></td><td>裸指针</td><td></td></tr>
<tr><td><code>+</code></td><td><code>trait + trait</code>, <code>'a + trait</code></td><td>复合类型限制</td><td></td></tr>
<tr><td><code>+</code></td><td><code>expr + expr</code></td><td>算术加法</td><td><code>Add</code></td></tr>
<tr><td><code>+=</code></td><td><code>var += expr</code></td><td>算术加法与赋值</td><td><code>AddAssign</code></td></tr>
<tr><td><code>,</code></td><td><code>expr, expr</code></td><td>参数以及元素分隔符</td><td></td></tr>
<tr><td><code>-</code></td><td><code>- expr</code></td><td>算术取负</td><td><code>Neg</code></td></tr>
<tr><td><code>-</code></td><td><code>expr - expr</code></td><td>算术减法</td><td><code>Sub</code></td></tr>
<tr><td><code>-=</code></td><td><code>var -= expr</code></td><td>算术减法与赋值</td><td><code>SubAssign</code></td></tr>
<tr><td><code>-&gt;</code></td><td><code>fn(...) -&gt; type</code>, <code>|...| -&gt; type</code></td><td>函数与闭包,返回类型</td><td></td></tr>
<tr><td><code>.</code></td><td><code>expr.ident</code></td><td>成员访问</td><td></td></tr>
<tr><td><code>..</code></td><td><code>..</code>, <code>expr..</code>, <code>..expr</code>, <code>expr..expr</code></td><td>右开区间范围</td><td><code>PartialOrd</code></td></tr>
<tr><td><code>..=</code></td><td><code>..=expr</code>, <code>expr..=expr</code></td><td>右闭区间范围模式</td><td><code>PartialOrd</code></td></tr>
<tr><td><code>..</code></td><td><code>..expr</code></td><td>结构体更新语法</td><td></td></tr>
<tr><td><code>..</code></td><td><code>variant(x, ..)</code>, <code>struct_type { x, .. }</code></td><td>“与剩余部分” 的模式绑定</td><td></td></tr>
<tr><td><code>...</code></td><td><code>expr...expr</code></td><td>Deprecated请使用 <code>..=</code>)在模式中:闭区间范围模式</td><td></td></tr>
<tr><td><code>/</code></td><td><code>expr / expr</code></td><td>算术除法</td><td><code>Div</code></td></tr>
<tr><td><code>/=</code></td><td><code>var /= expr</code></td><td>算术除法与赋值</td><td><code>DivAssign</code></td></tr>
<tr><td><code>:</code></td><td><code>pat: type</code>, <code>ident: type</code></td><td>约束</td><td></td></tr>
<tr><td><code>:</code></td><td><code>ident: expr</code></td><td>结构体字段初始化</td><td></td></tr>
<tr><td><code>:</code></td><td><code>'a: loop {...}</code></td><td>循环标志</td><td></td></tr>
<tr><td><code>;</code></td><td><code>expr;</code></td><td>语句和语句结束符</td><td></td></tr>
<tr><td><code>;</code></td><td><code>[...; len]</code></td><td>固定大小数组语法的部分</td><td></td></tr>
<tr><td><code>&lt;&lt;</code></td><td><code>expr &lt;&lt; expr</code></td><td>左移</td><td><code>Shl</code></td></tr>
<tr><td><code>&lt;&lt;=</code></td><td><code>var &lt;&lt;= expr</code></td><td>左移与赋值</td><td><code>ShlAssign</code></td></tr>
<tr><td><code>&lt;</code></td><td><code>expr &lt; expr</code></td><td>小于比较</td><td><code>PartialOrd</code></td></tr>
<tr><td><code>&lt;=</code></td><td><code>expr &lt;= expr</code></td><td>小于等于比较</td><td><code>PartialOrd</code></td></tr>
<tr><td><code>=</code></td><td><code>var = expr</code>, <code>ident = type</code></td><td>赋值/等值</td><td></td></tr>
<tr><td><code>==</code></td><td><code>expr == expr</code></td><td>等于比较</td><td><code>PartialEq</code></td></tr>
<tr><td><code>=&gt;</code></td><td><code>pat =&gt; expr</code></td><td>匹配准备语法的部分</td><td></td></tr>
<tr><td><code>&gt;</code></td><td><code>expr &gt; expr</code></td><td>大于比较</td><td><code>PartialOrd</code></td></tr>
<tr><td><code>&gt;=</code></td><td><code>expr &gt;= expr</code></td><td>大于等于比较</td><td><code>PartialOrd</code></td></tr>
<tr><td><code>&gt;&gt;</code></td><td><code>expr &gt;&gt; expr</code></td><td>右移</td><td><code>Shr</code></td></tr>
<tr><td><code>&gt;&gt;=</code></td><td><code>var &gt;&gt;= expr</code></td><td>右移与赋值</td><td><code>ShrAssign</code></td></tr>
<tr><td><code>@</code></td><td><code>ident @ pat</code></td><td>模式绑定</td><td></td></tr>
<tr><td><code>^</code></td><td><code>expr ^ expr</code></td><td>按位异或</td><td><code>BitXor</code></td></tr>
<tr><td><code>^=</code></td><td><code>var ^= expr</code></td><td>按位异或与赋值</td><td><code>BitXorAssign</code></td></tr>
<tr><td><code>|</code></td><td><code>pat | pat</code></td><td>模式选择</td><td></td></tr>
<tr><td><code>|</code></td><td><code>expr | expr</code></td><td>按位或</td><td><code>BitOr</code></td></tr>
<tr><td><code>|=</code></td><td><code>var |= expr</code></td><td>按位或与赋值</td><td><code>BitOrAssign</code></td></tr>
<tr><td><code>||</code></td><td><code>expr || expr</code></td><td>短路Short-circuiting逻辑或</td><td></td></tr>
<tr><td><code>?</code></td><td><code>expr?</code></td><td>错误传播</td><td></td></tr>
</tbody></table>
</div>
<h3 id="非运算符符号"><a class="header" href="#非运算符符号">非运算符符号</a></h3>
<p>下面的列表中包含了所有和运算符不一样功能的符号;也就是说,它们并不像函数调用或方法调用一样表现。</p>
<p>表 B-2 展示了以其自身出现以及出现在合法其他各个地方的符号。</p>
<p><span class="caption">表 B-2独立语法</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>解释</th></tr></thead><tbody>
<tr><td><code>'ident</code></td><td>命名生命周期或循环标签</td></tr>
<tr><td><code>...u8</code>, <code>...i32</code>, <code>...f64</code>, <code>...usize</code></td><td>指定类型的数值常量</td></tr>
<tr><td><code>"..."</code></td><td>字符串常量</td></tr>
<tr><td><code>r"..."</code>, <code>r#"..."#</code>, <code>r##"..."##</code>, etc.</td><td>原始字符串字面值,未处理的转义字符</td></tr>
<tr><td><code>b"..."</code></td><td>字节字符串字面值; 构造一个字节数组类型而非字符串</td></tr>
<tr><td><code>br"..."</code>, <code>br#"..."#</code>, <code>br##"..."##</code></td><td>原始字节字符串字面值,原始和字节字符串字面值的结合</td></tr>
<tr><td><code>'...'</code></td><td>字符字面值</td></tr>
<tr><td><code>b'...'</code></td><td>ASCII 码字节字面值</td></tr>
<tr><td><code>|...| expr</code></td><td>闭包</td></tr>
<tr><td><code>!</code></td><td>离散函数的总是为空的类型</td></tr>
<tr><td><code>_</code></td><td>“忽略” 模式绑定;也用于增强整型字面值的可读性</td></tr>
</tbody></table>
</div>
<p>表 B-3 展示了出现在从模块结构到项的路径上下文中的符号</p>
<p><span class="caption">表 B-3路径相关语法</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>解释</th></tr></thead><tbody>
<tr><td><code>ident::ident</code></td><td>命名空间路径</td></tr>
<tr><td><code>::path</code></td><td>与 crate 根相对的路径(如一个显式绝对路径)</td></tr>
<tr><td><code>self::path</code></td><td>与当前模块相对的路径(如一个显式相对路径)</td></tr>
<tr><td><code>super::path</code></td><td>与父模块相对的路径</td></tr>
<tr><td><code>type::ident</code>, <code>&lt;type as trait&gt;::ident</code></td><td>关联常量、函数以及类型</td></tr>
<tr><td><code>&lt;type&gt;::...</code></td><td>不可以被直接命名的关联项类型(如 <code>&lt;&amp;T&gt;::...</code><code>&lt;[T]&gt;::...</code>,等)</td></tr>
<tr><td><code>trait::method(...)</code></td><td>通过命名定义的 trait 来消除方法调用的二义性</td></tr>
<tr><td><code>type::method(...)</code></td><td>通过命名定义的类型来消除方法调用的二义性</td></tr>
<tr><td><code>&lt;type as trait&gt;::method(...)</code></td><td>通过命名 trait 和类型来消除方法调用的二义性</td></tr>
</tbody></table>
</div>
<p>表 B-4 展示了出现在泛型类型参数上下文中的符号。</p>
<p><span class="caption">表 B-4泛型</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>解释</th></tr></thead><tbody>
<tr><td><code>path&lt;...&gt;</code></td><td>为一个类型中的泛型指定具体参数(如 <code>Vec&lt;u8&gt;</code></td></tr>
<tr><td><code>path::&lt;...&gt;</code>, <code>method::&lt;...&gt;</code></td><td>为一个泛型、函数或表达式中的方法指定具体参数,通常指 turbofish<code>"42".parse::&lt;i32&gt;()</code></td></tr>
<tr><td><code>fn ident&lt;...&gt; ...</code></td><td>泛型函数定义</td></tr>
<tr><td><code>struct ident&lt;...&gt; ...</code></td><td>泛型结构体定义</td></tr>
<tr><td><code>enum ident&lt;...&gt; ...</code></td><td>泛型枚举定义</td></tr>
<tr><td><code>impl&lt;...&gt; ...</code></td><td>定义泛型实现</td></tr>
<tr><td><code>for&lt;...&gt; type</code></td><td>高级生命周期限制</td></tr>
<tr><td><code>type&lt;ident=type&gt;</code></td><td>泛型,其一个或多个相关类型必须被指定为特定类型(如 <code>Iterator&lt;Item=T&gt;</code></td></tr>
</tbody></table>
</div>
<p>表 B-5 展示了出现在使用 trait bounds 约束泛型参数上下文中的符号。</p>
<p><span class="caption">表 B-5: Trait Bound 约束</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>解释</th></tr></thead><tbody>
<tr><td><code>T: U</code></td><td>泛型参数 <code>T</code> 约束于实现了 <code>U</code> 的类型</td></tr>
<tr><td><code>T: 'a</code></td><td>泛型 <code>T</code> 的生命周期必须长于 <code>'a</code>(意味着该类型不能传递包含生命周期短于 <code>'a</code> 的任何引用)</td></tr>
<tr><td><code>T: 'static</code></td><td>泛型 T 不包含除 'static 之外的借用引用</td></tr>
<tr><td><code>'b: 'a</code></td><td>泛型 <code>'b</code> 生命周期必须长于泛型 <code>'a</code></td></tr>
<tr><td><code>T: ?Sized</code></td><td>使用一个不定大小的泛型类型</td></tr>
<tr><td><code>'a + trait</code>, <code>trait + trait</code></td><td>复合类型限制</td></tr>
</tbody></table>
</div>
<p>表 B-6 展示了在调用或定义宏以及在其上指定属性时的上下文中出现的符号。</p>
<p><span class="caption">表 B-6: 宏与属性</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>解释</th></tr></thead><tbody>
<tr><td><code>#[meta]</code></td><td>外部属性</td></tr>
<tr><td><code>#![meta]</code></td><td>内部属性</td></tr>
<tr><td><code>$ident</code></td><td>宏替换</td></tr>
<tr><td><code>$ident:kind</code></td><td>宏捕获</td></tr>
<tr><td><code>$(…)…</code></td><td>宏重复</td></tr>
<tr><td><code>ident!(...)</code>, <code>ident!{...}</code>, <code>ident![...]</code></td><td>宏调用</td></tr>
</tbody></table>
</div>
<p>表 B-7 展示了写注释的符号。</p>
<p><span class="caption">表 B-7: 注释</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>注释</th></tr></thead><tbody>
<tr><td><code>//</code></td><td>行注释</td></tr>
<tr><td><code>//!</code></td><td>内部行文档注释</td></tr>
<tr><td><code>///</code></td><td>外部行文档注释</td></tr>
<tr><td><code>/*...*/</code></td><td>块注释</td></tr>
<tr><td><code>/*!...*/</code></td><td>内部块文档注释</td></tr>
<tr><td><code>/**...*/</code></td><td>外部块文档注释</td></tr>
</tbody></table>
</div>
<p>表 B-8 展示了出现在使用元组时上下文中的符号。</p>
<p><span class="caption">表 B-8: 元组</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>解释</th></tr></thead><tbody>
<tr><td><code>()</code></td><td>空元组(亦称单元),即是字面值也是类型</td></tr>
<tr><td><code>(expr)</code></td><td>括号表达式</td></tr>
<tr><td><code>(expr,)</code></td><td>单一元素元组表达式</td></tr>
<tr><td><code>(type,)</code></td><td>单一元素元组类型</td></tr>
<tr><td><code>(expr, ...)</code></td><td>元组表达式</td></tr>
<tr><td><code>(type, ...)</code></td><td>元组类型</td></tr>
<tr><td><code>expr(expr, ...)</code></td><td>函数调用表达式;也用于初始化元组结构体 <code>struct</code> 以及元组枚举 <code>enum</code> 变体</td></tr>
<tr><td><code>expr.0</code>, <code>expr.1</code>, etc.</td><td>元组索引</td></tr>
</tbody></table>
</div>
<p>表 B-9 展示了使用大括号的上下文。</p>
<p><span class="caption">表 B-9: 大括号</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>解释</th></tr></thead><tbody>
<tr><td><code>{...}</code></td><td>块表达式</td></tr>
<tr><td><code>Type {...}</code></td><td><code>struct</code> 字面值</td></tr>
</tbody></table>
</div>
<p>表 B-10 展示了使用方括号的上下文。</p>
<p><span class="caption">表 B-10: 方括号</span></p>
<div class="table-wrapper"><table><thead><tr><th>符号</th><th>解释</th></tr></thead><tbody>
<tr><td><code>[...]</code></td><td>数组</td></tr>
<tr><td><code>[expr; len]</code></td><td>复制了 <code>len</code><code>expr</code>的数组</td></tr>
<tr><td><code>[type; len]</code></td><td>包含 <code>len</code><code>type</code> 类型的数组</td></tr>
<tr><td><code>expr[expr]</code></td><td>集合索引。重载(<code>Index</code>, <code>IndexMut</code></td></tr>
<tr><td><code>expr[..]</code>, <code>expr[a..]</code>, <code>expr[..b]</code>, <code>expr[a..b]</code></td><td>集合索引,使用 <code>Range</code><code>RangeFrom</code><code>RangeTo</code><code>RangeFull</code> 作为索引来代替集合 slice</td></tr>
</tbody></table>
</div><div style="break-before: page; page-break-before: always;"></div><h2 id="附录-c可派生的-trait"><a class="header" href="#附录-c可派生的-trait">附录 C可派生的 trait</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/appendix-03-derivable-traits.md">appendix-03-derivable-traits.md</a>
<br />
commit c07dddac692848ade6c2112c8e15a7087fbbec45</p>
</blockquote>
<p>在本书的各个部分中,我们讨论了可应用于结构体和枚举定义的 <code>derive</code> 属性。<code>derive</code> 属性会在使用 <code>derive</code> 语法标记的类型上生成对应 trait 的默认实现的代码。</p>
<p>在本附录中提供了标准库中所有可以使用 <code>derive</code> 的 trait 的参考。这些部分涉及到:</p>
<ul>
<li>该 trait 将会派生什么样的操作符和方法</li>
<li><code>derive</code> 提供什么样的 trait 实现</li>
<li>由什么来实现类型的 trait</li>
<li>是否允许实现该 trait 的条件</li>
<li>需要 trait 操作的例子</li>
</ul>
<p>如果你希望不同于 <code>derive</code> 属性所提供的行为,请查阅 <a href="https://doc.rust-lang.org/std/index.html">标准库文档</a> 中每个 trait 的细节以了解如何手动实现它们。</p>
<p>这里列出的 trait 是仅有的在标准库中定义且能通过 <code>derive</code> 在类型上实现。标准库中定义的其它 trait 不能通过 <code>derive</code> 在类型上实现。这些 trait 不存在有意义的默认行为,所以由你负责以合理的方式实现它们。</p>
<p>一个无法被派生的 trait 的例子是为终端用户处理格式化的 <code>Display</code> 。你应该时常考虑使用合适的方法来为终端用户显示一个类型。终端用户应该看到类型的什么部分他们会找出相关部分吗对他们来说最相关的数据格式是什么样的Rust 编译器没有这样的洞察力,因此无法为你提供合适的默认行为。</p>
<p>本附录所提供的可派生 trait 列表并不全面:库可以为其自己的 trait 实现 <code>derive</code>,可以使用 <code>derive</code> 的 trait 列表事实上是无限的。实现 <code>derive</code> 涉及到过程宏的应用,这在第二十章的 <a href="ch20-06-macros.html#%E5%AE%8F">“宏”</a> 有介绍。</p>
<h3 id="用于程序员输出的-debug"><a class="header" href="#用于程序员输出的-debug">用于程序员输出的 <code>Debug</code></a></h3>
<p><code>Debug</code> trait 用于开启格式化字符串中的调试格式,其通过在 <code>{}</code> 占位符中增加 <code>:?</code> 表明。</p>
<p><code>Debug</code> trait 允许以调试目的来打印一个类型的实例,所以使用该类型的程序员可以在程序执行的特定时间点观察其实例。</p>
<p>例如,在使用 <code>assert_eq!</code> 宏时,<code>Debug</code> trait 是必须的。如果等式断言失败,这个宏就把给定实例的值作为参数打印出来,如此程序员可以看到两个实例为什么不相等。</p>
<h3 id="等值比较的-partialeq-和-eq"><a class="header" href="#等值比较的-partialeq-和-eq">等值比较的 <code>PartialEq</code><code>Eq</code></a></h3>
<p><code>PartialEq</code> trait 可以比较一个类型的实例以检查是否相等,并开启了 <code>==</code><code>!=</code> 运算符的功能。</p>
<p>派生的 <code>PartialEq</code> 实现了 <code>eq</code> 方法。当 <code>PartialEq</code> 在结构体上派生时,只有<em>所有</em> 的字段都相等时两个实例才相等,同时只要有任何字段不相等则两个实例就不相等。当在枚举上派生时,每一个成员都和其自身相等,且和其他成员都不相等。</p>
<p>例如,当使用 <code>assert_eq!</code> 宏时,需要比较一个类型的两个实例是否相等,则 <code>PartialEq</code> trait 是必须的。</p>
<p><code>Eq</code> trait 没有方法。其作用是表明每一个被标记类型的值等于其自身。<code>Eq</code> trait 只能应用于那些实现了 <code>PartialEq</code> 的类型,但并非所有实现了 <code>PartialEq</code> 的类型都可以实现 <code>Eq</code>。浮点类型就是一个例子:浮点数的实现表明两个非数字(<code>NaN</code>not-a-number值是互不相等的。</p>
<p>例如,对于一个 <code>HashMap&lt;K, V&gt;</code> 中的 key 来说, <code>Eq</code> 是必须的,这样 <code>HashMap&lt;K, V&gt;</code> 就可以知道两个 key 是否一样了。</p>
<h3 id="次序比较的-partialord-和-ord"><a class="header" href="#次序比较的-partialord-和-ord">次序比较的 <code>PartialOrd</code><code>Ord</code></a></h3>
<p><code>PartialOrd</code> trait 可以基于排序的目的而比较一个类型的实例。实现了 <code>PartialOrd</code> 的类型可以使用 <code>&lt;</code><code>&gt;</code><code>&lt;=</code><code>&gt;=</code> 操作符。但只能在同时实现了 <code>PartialEq</code> 的类型上使用 <code>PartialOrd</code></p>
<p>派生 <code>PartialOrd</code> 实现了 <code>partial_cmp</code> 方法,其返回一个 <code>Option&lt;Ordering&gt;</code> ,但当给定值无法产生顺序时将返回 <code>None</code>。尽管大多数类型的值都可以比较,但一个无法产生顺序的例子是:浮点类型的非数字值。当在浮点数上调用 <code>partial_cmp</code> 时,<code>NaN</code> 的浮点数将返回 <code>None</code></p>
<p>当在结构体上派生时,<code>PartialOrd</code> 按照结构体定义中字段出现的顺序,依次比较每个字段的值,以此来比较两个实例。当在枚举上派生时,认为在枚举定义中声明较早的枚举变体小于其后的变体。</p>
<p>例如,对于来自于 <code>rand</code> crate 中的 <code>gen_range</code> 方法来说,当在一个范围表达式指定的范围内生成一个随机值时,<code>PartialOrd</code> trait 是必须的。</p>
<p><code>Ord</code> trait 也让你明白在一个带注解类型上的任意两个值存在有效顺序。<code>Ord</code> trait 实现了 <code>cmp</code> 方法,它返回一个 <code>Ordering</code> 而不是 <code>Option&lt;Ordering&gt;</code>,因为总存在一个合法的顺序。只可以在实现了 <code>PartialOrd</code><code>Eq</code><code>Eq</code> 依赖 <code>PartialEq</code>)的类型上使用 <code>Ord</code> trait。当在结构体或枚举上派生时 <code>cmp</code> 和以 <code>PartialOrd</code> 派生实现的 <code>partial_cmp</code> 表现一致。</p>
<p>例如,当在 <code>BTreeSet&lt;T&gt;</code>(一种基于有序值存储数据的数据结构)上存值时,<code>Ord</code> 是必须的。</p>
<h3 id="复制值的-clone-和-copy"><a class="header" href="#复制值的-clone-和-copy">复制值的 <code>Clone</code><code>Copy</code></a></h3>
<p><code>Clone</code> trait 可以明确地创建一个值的深拷贝deep copy复制过程可能包含任意代码的执行以及堆上数据的复制。查阅第四章 <a href="ch04-01-what-is-ownership.html#%E5%8F%98%E9%87%8F%E4%B8%8E%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%9A%84%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%85%8B%E9%9A%86">“变量与数据交互的方式(二):克隆”</a> 以获取有关 <code>Clone</code> 的更多信息。</p>
<p>派生 <code>Clone</code> 实现了 <code>clone</code> 方法,其为整个的类型实现时,在类型的每一部分上调用了 <code>clone</code> 方法。这意味着类型中所有字段或值也必须实现了 <code>Clone</code>,这样才能够派生 <code>Clone</code></p>
<p>例如当在一个切片slice上调用 <code>to_vec</code> 方法时,<code>Clone</code> 是必须的。切片并不拥有其包含的实例,但是从 <code>to_vec</code> 中返回的 vector 需要拥有其实例,因此,<code>to_vec</code> 在每个元素上调用 <code>clone</code>。因此,存储在切片中的类型必须实现 <code>Clone</code></p>
<p><code>Copy</code> trait 允许你通过只拷贝存储在栈上的位来复制值而不需要额外的代码。查阅第四章 <a href="ch04-01-what-is-ownership.html#%E5%8F%AA%E5%9C%A8%E6%A0%88%E4%B8%8A%E7%9A%84%E6%95%B0%E6%8D%AE%E6%8B%B7%E8%B4%9D">“只在栈上的数据:拷贝”</a> 的部分来获取有关 <code>Copy</code> 的更多信息。</p>
<p><code>Copy</code> trait 并未定义任何方法来阻止编程人员重写这些方法或违反不需要执行额外代码的假设。尽管如此所有的编程人员可以假设复制copy一个值非常快。</p>
<p>可以在类型内部全部实现 <code>Copy</code> trait 的任意类型上派生 <code>Copy</code>。一个实现了 <code>Copy</code> 的类型必须也实现了 <code>Clone</code>,因为一个实现了 <code>Copy</code> 的类型也简单地实现了 <code>Clone</code>,其执行和 <code>Copy</code> 相同的任务。</p>
<p><code>Copy</code> trait 很少使用;实现 <code>Copy</code> 的类型是可以优化的,这意味着你无需调用 <code>clone</code>,这让代码更简洁。</p>
<p>任何使用 <code>Copy</code> 的代码都可以通过 <code>Clone</code> 实现,但代码可能会稍慢,或者不得不在代码中的许多位置上使用 <code>clone</code></p>
<h3 id="固定大小的值到值映射的-hash"><a class="header" href="#固定大小的值到值映射的-hash">固定大小的值到值映射的 <code>Hash</code></a></h3>
<p><code>Hash</code> trait 可以实例化一个任意大小的类型并且能够用哈希hash函数将该实例映射到一个固定大小的值上。派生 <code>Hash</code> 实现了 <code>hash</code> 方法。<code>hash</code> 方法的派生实现结合了在类型的每部分调用 <code>hash</code> 的结果,这意味着所有的字段或值也必须实现了 <code>Hash</code>,这样才能够派生 <code>Hash</code></p>
<p>例如,在 <code>HashMap&lt;K, V&gt;</code> 上存储数据,存放 key 的时候,<code>Hash</code> 是必须的。</p>
<h3 id="默认值的-default"><a class="header" href="#默认值的-default">默认值的 <code>Default</code></a></h3>
<p><code>Default</code> trait 使你创建一个类型的默认值。派生 <code>Default</code> 实现了 <code>default</code> 函数。<code>default</code> 函数的派生实现调用了类型每部分的 <code>default</code> 函数,这意味着类型中所有的字段或值也必须实现了 <code>Default</code>,这样才能够派生 <code>Default</code></p>
<p><code>Default::default</code> 函数通常结合结构体更新语法一起使用,这在第五章的 <a href="ch05-01-defining-structs.html#%E4%BD%BF%E7%94%A8%E7%BB%93%E6%9E%84%E4%BD%93%E6%9B%B4%E6%96%B0%E8%AF%AD%E6%B3%95%E4%BB%8E%E5%85%B6%E4%BB%96%E5%AE%9E%E4%BE%8B%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BE%8B">“使用结构体更新语法从其他实例中创建实例”</a> 部分有讨论。可以自定义一个结构体的一小部分字段而剩余字段则使用 <code>..Default::default()</code> 设置为默认值。</p>
<p>例如,当你在 <code>Option&lt;T&gt;</code> 实例上使用 <code>unwrap_or_default</code> 方法时,<code>Default</code> trait 是必须的。如果 <code>Option&lt;T&gt;</code><code>None</code>的话,<code>unwrap_or_default</code> 方法将返回存储在 <code>Option&lt;T&gt;</code><code>T</code> 类型的 <code>Default::default</code> 的结果。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="附录-d实用开发工具"><a class="header" href="#附录-d实用开发工具">附录 D实用开发工具</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/appendix-04-useful-development-tools.md">appendix-04-useful-development-tools.md</a>
<br />
commit 5057f157cd0b35bc7d0dc0af6ef622fa4c480996</p>
</blockquote>
<p>本附录,我们将讨论 Rust 项目提供的用于开发 Rust 代码的工具。</p>
<h3 id="通过-rustfmt-自动格式化"><a class="header" href="#通过-rustfmt-自动格式化">通过 <code>rustfmt</code> 自动格式化</a></h3>
<p><code>rustfmt</code> 工具根据社区代码风格格式化代码。很多项目使用 <code>rustfmt</code> 来避免编写 Rust 风格的争论:所有人都用这个工具格式化代码!</p>
<p>安装 <code>rustfmt</code></p>
<pre><code class="language-console">$ rustup component add rustfmt
</code></pre>
<p>这会提供 <code>rustfmt</code><code>cargo-fmt</code>,类似于 Rust 同时安装 <code>rustc</code><code>cargo</code>。为了格式化整个 Cargo 项目:</p>
<pre><code class="language-console">$ cargo fmt
</code></pre>
<p>运行此命令会格式化当前 crate 中所有的 Rust 代码。这应该只会改变代码风格,而不是代码语义。请查看 <a href="https://github.com/rust-lang/rustfmt">该文档</a> 了解 <code>rustfmt</code> 的更多信息。</p>
<h3 id="通过-rustfix-修复代码"><a class="header" href="#通过-rustfix-修复代码">通过 <code>rustfix</code> 修复代码</a></h3>
<p>如果你编写过 Rust 代码,那么你可能见过那些有很明显修复方式的编译器警告。例如,考虑如下代码:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn do_something() {}
fn main() {
for i in 0..100 {
do_something();
}
}</code></pre></pre>
<p>这里调用了 <code>do_something</code> 函数 100 次,不过从未在 <code>for</code> 循环体中使用变量 <code>i</code>。Rust 会警告说:</p>
<pre><code class="language-console">$ cargo build
Compiling myprogram v0.1.0 (file:///projects/myprogram)
warning: unused variable: `i`
--&gt; src/main.rs:4:9
|
4 | for i in 0..100 {
| ^ help: consider using `_i` instead
|
= note: #[warn(unused_variables)] on by default
Finished dev [unoptimized + debuginfo] target(s) in 0.50s
</code></pre>
<p>警告中建议使用 <code>_i</code> 名称:下划线表明该变量有意不使用。我们可以通过 <code>cargo fix</code> 命令使用 <code>rustfix</code> 工具来自动采用该建议:</p>
<pre><code class="language-console">$ cargo fix
Checking myprogram v0.1.0 (file:///projects/myprogram)
Fixing src/main.rs (1 fix)
Finished dev [unoptimized + debuginfo] target(s) in 0.59s
</code></pre>
<p>如果再次查看 <em>src/main.rs</em>,会发现 <code>cargo fix</code> 修改了代码:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn do_something() {}
fn main() {
for _i in 0..100 {
do_something();
}
}</code></pre></pre>
<p>现在 <code>for</code> 循环变量变为 <code>_i</code>,警告也不再出现。</p>
<p><code>cargo fix</code> 命令可以用于在不同 Rust 版本间迁移代码。版本在附录 E 中介绍。</p>
<h3 id="通过-clippy-提供更多-lint-功能"><a class="header" href="#通过-clippy-提供更多-lint-功能">通过 <code>clippy</code> 提供更多 lint 功能</a></h3>
<p><code>clippy</code> 工具是一系列 lint 的集合,用于捕捉常见错误和改进 Rust 代码。</p>
<p>安装 <code>clippy</code></p>
<pre><code class="language-console">$ rustup component add clippy
</code></pre>
<p>对任何 Cargo 项目运行 clippy 的 lint</p>
<pre><code class="language-console">$ cargo clippy
</code></pre>
<p>例如,如果程序使用了如 pi 这样数学常数的近似值,如下:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = 3.1415;
let r = 8.0;
println!("the area of the circle is {}", x * r * r);
}</code></pre></pre>
<p>在此项目上运行 <code>cargo clippy</code> 会导致这个错误:</p>
<pre><code class="language-text">error: approximate value of `f{32, 64}::consts::PI` found
--&gt; src/main.rs:2:13
|
2 | let x = 3.1415;
| ^^^^^^
|
= note: `#[deny(clippy::approx_constant)]` on by default
= help: consider using the constant directly
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant
</code></pre>
<p>这告诉我们 Rust 定义了更为精确的常量,而如果使用了这些常量程序将更加准确。如下代码就不会导致 <code>clippy</code> 产生任何错误或警告:</p>
<p><span class="filename">文件名src/main.rs</span></p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let x = std::f64::consts::PI;
let r = 8.0;
println!("the area of the circle is {}", x * r * r);
}</code></pre></pre>
<p>请查看 <a href="https://github.com/rust-lang/rust-clippy">其文档</a> 来了解 <code>clippy</code> 的更多信息。</p>
<h3 id="使用-rust-analyzer-的-ide-集成"><a class="header" href="#使用-rust-analyzer-的-ide-集成">使用 <code>rust-analyzer</code> 的 IDE 集成</a></h3>
<p>为了帮助 IDE 集成Rust 社区建议使用 <a href="https://rust-analyzer.github.io"><code>rust-analyzer</code></a>。这个工具是一组以编译器为中心的实用程序,它实现了 <a href="http://langserver.org/">Language Server Protocol</a>(一个 IDE 与编程语言之间的通信规范)。<code>rust-analyzer</code> 可以用于不同的客户端,比如 <a href="https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer">Visual Studio Code 的 Rust analyzer 插件</a></p>
<p>访问 <code>rust-analyzer</code> 项目的 <a href="https://rust-analyzer.github.io">主页</a> 来了解如何安装它,然后为你的 IDE 安装 language server 支持。如此你的 IDE 便会获得如自动补全、跳转到定义和 inline error 之类的功能。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="附录-e版本"><a class="header" href="#附录-e版本">附录 E版本</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/appendix-05-editions.md">appendix-05-editions.md</a>
<br />
commit 8cf0496bb8e56b683ea3f015871c8631684decf4</p>
</blockquote>
<p>早在第一章,我们见过 <code>cargo new</code><em>Cargo.toml</em> 中增加了一些有关 <code>edition</code> 的元数据。本附录将解释其意义!</p>
<p>Rust 语言和编译器有一个为期 6 周的发布循环。这意味着用户会稳定得到新功能的更新。其他编程语言发布大更新但不甚频繁Rust 选择更为频繁的发布小更新。一段时间之后,所有这些小更新会日积月累。不过随着小更新逐次的发布,或许很难回过头来感叹:“哇,从 Rust 1.10 到 Rust 1.31Rust 的变化真大!”</p>
<p>每两到三年Rust 团队会生成一个新的 Rust <strong>版本</strong><em>edition</em>)。每一个版本会结合已经落地的功能,并提供一个清晰的带有完整更新文档和工具的功能包。新版本会作为常规的 6 周发布过程的一部分发布。</p>
<p>这为不同的人群提供了不同的功能:</p>
<ul>
<li>对于活跃的 Rust 用户,其将增量的修改与易于理解的功能包相结合。</li>
<li>对于非用户,它表明发布了一些重大进展,这意味着 Rust 可能变得值得一试。</li>
<li>对于 Rust 自身开发者,其提供了项目整体的集合点。</li>
</ul>
<p>在本文档编写时Rust 有三个可用版本Rust 2015、Rust 2018 和 Rust 2021。本书基于 Rust 2021 edition 风格编写。</p>
<p><em>Cargo.toml</em> 中的 <code>edition</code> 字段表明代码应该使用哪个版本编译。如果该字段不存在,其默认为 <code>2015</code> 以提供后向兼容性。</p>
<p>每个项目都可以选择不同于默认的 2015 edition 的版本。这样,版本可能会包含不兼容的修改,比如新增关键字可能会与代码中的标识符冲突并导致错误。不过除非选择兼容这些修改,(旧)代码仍将能够编译,即便升级了 Rust 编译器的版本。</p>
<p>所有 Rust 编译器都支持任何之前存在的编译器版本,并可以链接任何支持版本的 crate。编译器修改只影响最初的解析代码的过程。因此如果你使用 Rust 2015 而某个依赖使用 Rust 2018你的项目仍旧能够编译并使用该依赖。反之若项目使用 Rust 2018 而依赖使用 Rust 2015 亦可工作。</p>
<p>有一点需要明确:大部分功能在所有版本中都能使用。开发者使用任何 Rust 版本将能继续接收最新稳定版的改进。然而在一些情况,主要是增加了新关键字的时候,则可能出现了只能用于新版本的功能。只需切换版本即可利用新版本的功能。</p>
<p>请查看 <a href="https://rust-lang-nursery.github.io/edition-guide/">Edition Guide</a> 了解更多细节,这是一个完全介绍版本的书籍,包括如何通过 <code>cargo fix</code> 自动将代码迁移到新版本。</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="附录-f本书译本"><a class="header" href="#附录-f本书译本">附录 F本书译本</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/appendix-06-translation.md">appendix-06-translation.md</a>
<br />
commit 4c8d13c52c51f1c62a80b52d7fbd7cc0b63ada43</p>
</blockquote>
<p>一些非英语语言的资源。多数仍在翻译中;查阅 <a href="https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations">翻译标签</a> 来帮助翻译,或者添加译本链接!</p>
<ul>
<li><a href="https://github.com/rust-br/rust-book-pt-br">Português</a> (BR)</li>
<li><a href="https://github.com/nunojesus/rust-book-pt-pt">Português</a> (PT)</li>
<li><a href="https://github.com/KaiserY/trpl-zh-cn">简体中文</a></li>
<li><a href="https://github.com/rust-tw/book-tw">正體中文</a></li>
<li><a href="https://github.com/pavloslav/rust-book-uk-ua">Українська</a></li>
<li><a href="https://github.com/thecodix/book">Español</a>, <a href="https://github.com/ManRR/rust-book-es">alternate</a></li>
<li><a href="https://github.com/EmanueleGurini/book_it">Italiano</a></li>
<li><a href="https://github.com/rust-lang-ru/book">Русский</a></li>
<li><a href="https://github.com/rinthel/rust-lang-book-ko">한국어</a></li>
<li><a href="https://github.com/rust-lang-ja/book-ja">日本語</a></li>
<li><a href="https://github.com/Jimskapt/rust-book-fr">Français</a></li>
<li><a href="https://github.com/paytchoo/book-pl">Polski</a></li>
<li><a href="https://github.com/agentzero1/book">Cebuano</a></li>
<li><a href="https://github.com/josephace135/book">Tagalog</a></li>
<li><a href="https://github.com/psychoslave/Rust-libro">Esperanto</a></li>
<li><a href="https://github.com/TChatzigiannakis/rust-book-greek">ελληνική</a></li>
<li><a href="https://github.com/sebras/book">Svenska</a></li>
<li><a href="https://github.com/pomokhtari/rust-book-fa">Farsi</a></li>
<li><a href="https://github.com/rust-lang-de/rustbook-de">Deutsch</a></li>
<li><a href="https://github.com/venkatarun95/rust-book-hindi">हिंदी</a></li>
<li><a href="https://github.com/rust-lang-th/book-th">ไทย</a></li>
<li><a href="https://github.com/DanKHansen/book-dk">Danske</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h2 id="附录-grust-是如何开发的与-nightly-rust"><a class="header" href="#附录-grust-是如何开发的与-nightly-rust">附录 GRust 是如何开发的与 “Nightly Rust”</a></h2>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/main/src/appendix-07-nightly-rust.md">appendix-07-nightly-rust.md</a>
<br />
commit d44317c3122b44fb713aba66cc295dee3453b24b</p>
</blockquote>
<p>本附录介绍 Rust 是如何开发的以及这如何影响作为 Rust 开发者的你。</p>
<h3 id="无停滞稳定"><a class="header" href="#无停滞稳定">无停滞稳定</a></h3>
<p>作为一个语言Rust <strong>十分</strong> 注重代码的稳定性。我们希望 Rust 成为你代码坚实的基础,假如持续地有东西在变,这个希望就实现不了。但与此同时,如果不能实验新功能的话,在发布之前我们又无法发现其中重大的缺陷,而一旦发布便再也没有修改的机会了。</p>
<p>对于这个问题我们的解决方案被称为 “无停滞稳定”“stability without stagnation”其指导性原则是无需担心升级到最新的稳定版 Rust。每次升级应该是无痛的并应带来新功能更少的 bug 和更快的编译速度。</p>
<h3 id="choo-choo-发布通道和发布时刻表riding-the-trains"><a class="header" href="#choo-choo-发布通道和发布时刻表riding-the-trains">Choo, Choo! 发布通道和发布时刻表Riding the Trains</a></h3>
<p>Rust 开发运行于一个 <strong>发布时刻表</strong><em>train schedule</em>)之上。也就是说,所有的开发工作都位于 Rust 仓库的 <code>master</code> 分支。发布采用 software release train 模型,其被用于思科 IOS 等其它软件项目。Rust 有三个 <strong>发布通道</strong><em>release channel</em></p>
<ul>
<li>Nightly</li>
<li>Beta</li>
<li>Stable稳定版</li>
</ul>
<p>大部分 Rust 开发者主要采用稳定版通道,不过希望实验新功能的开发者可能会使用 nightly 或 beta 版。</p>
<p>如下是一个开发和发布过程如何运转的例子:假设 Rust 团队正在进行 Rust 1.5 的发布工作。该版本发布于 2015 年 12 月不过这里只是为了提供一个真实的版本。Rust 新增了一项功能:一个 <code>master</code> 分支的新提交。每天晚上,会产生一个新的 nightly 版本。每天都是发布版本的日子,而这些发布由发布基础设施自动完成。所以随着时间推移,发布轨迹看起来像这样,版本一天一发:</p>
<pre><code class="language-text">nightly: * - - * - - *
</code></pre>
<p>每 6 周时间是准备发布新版本的时候了Rust 仓库的 <code>beta</code> 分支会从用于 nightly 的 <code>master</code> 分支产生。现在,有了两个发布版本:</p>
<pre><code class="language-text">nightly: * - - * - - *
|
beta: *
</code></pre>
<p>大部分 Rust 用户不会主要使用 beta 版本,不过在 CI 系统中对 beta 版本进行测试能够帮助 Rust 发现可能的回归缺陷regression。同时每天仍产生 nightly 发布:</p>
<pre><code class="language-text">nightly: * - - * - - * - - * - - *
|
beta: *
</code></pre>
<p>比如我们发现了一个回归缺陷。好消息是在这些缺陷流入稳定发布之前还有一些时间来测试 beta 版本fix 被合并到 <code>master</code>,为此 nightly 版本得到了修复,接着这些 fix 将 backport 到 <code>beta</code> 分支,一个新的 beta 发布就产生了:</p>
<pre><code class="language-text">nightly: * - - * - - * - - * - - * - - *
|
beta: * - - - - - - - - *
</code></pre>
<p>第一个 beta 版的 6 周后,是发布稳定版的时候了!<code>stable</code> 分支从 <code>beta</code> 分支生成:</p>
<pre><code class="language-text">nightly: * - - * - - * - - * - - * - - * - * - *
|
beta: * - - - - - - - - *
|
stable: *
</code></pre>
<p>好的Rust 1.5 发布了!然而,我们忘了些东西:因为又过了 6 周,我们还需发布 <strong>新版</strong> Rust 的 beta 版Rust 1.6。所以从 <code>beta</code> 生成 <code>stable</code> 分支后,新版的 <code>beta</code> 分支也再次从 <code>nightly</code> 生成:</p>
<pre><code class="language-text">nightly: * - - * - - * - - * - - * - - * - * - *
| |
beta: * - - - - - - - - * *
|
stable: *
</code></pre>
<p>这被称为 “train model”因为每 6 周,一个版本 “离开车站”“leaves the station”不过从 beta 通道到达稳定通道还有一段旅程。</p>
<p>Rust 每 6 周发布一个版本,如时钟般准确。如果你知道了某个 Rust 版本的发布时间就可以知道下个版本的时间6 周后。每 6 周发布版本的一个好的方面是下一班车会来得更快。如果特定版本碰巧缺失某个功能也无需担心:另一个版本很快就会到来!这有助于减少因临近发版时间而偷偷释出未经完善的功能的压力。</p>
<p>多亏了这个过程,你总是可以切换到下一版本的 Rust 并验证是否可以轻易的升级:如果 beta 版不能如期工作,你可以向 Rust 团队报告并在发布稳定版之前得到修复beta 版造成的破坏是非常少见的,不过 <code>rustc</code> 也不过是一个软件,可能会存在 bug。</p>
<h3 id="不稳定功能"><a class="header" href="#不稳定功能">不稳定功能</a></h3>
<p>这个发布模型中另一个值得注意的地方不稳定功能unstable features。Rust 使用一个被称为 “功能标记”“feature flags”的技术来确定给定版本的某个功能是否启用。如果新功能正在积极地开发中其提交到了 <code>master</code>,因此会出现在 nightly 版中,不过会位于一个 <strong>功能标记</strong> 之后。作为用户,如果你希望尝试这个正在开发的功能,则可以在源码中使用合适的标记来开启,不过必须使用 nightly 版。</p>
<p>如果使用的是 beta 或稳定版 Rust则不能使用任何功能标记。这是在新功能被宣布为永久稳定之前获得实用价值的关键。这既满足了希望使用最尖端技术的同学那些坚持稳定版的同学也知道其代码不会被破坏。这就是无停滞稳定。</p>
<p>本书只包含稳定的功能,因为还在开发中的功能仍可能改变,当其进入稳定版时肯定会与编写本书的时候有所不同。你可以在网上获取 nightly 版的文档。</p>
<h3 id="rustup-和-rust-nightly-的职责"><a class="header" href="#rustup-和-rust-nightly-的职责">Rustup 和 Rust Nightly 的职责</a></h3>
<p>Rustup 使得改变不同发布通道的 Rust 更为简单,其在全局或分项目的层次工作。其默认会安装稳定版 Rust。例如为了安装 nightly</p>
<pre><code class="language-console">$ rustup toolchain install nightly
</code></pre>
<p>你会发现 <code>rustup</code> 也安装了所有的 <strong>工具链</strong><em>toolchains</em>Rust 和其相关组件)。如下是一位作者的 Windows 计算机上的例子:</p>
<pre><code class="language-powershell">&gt; rustup toolchain list
stable-x86_64-pc-windows-msvc (default)
beta-x86_64-pc-windows-msvc
nightly-x86_64-pc-windows-msvc
</code></pre>
<p>如你所见,默认是稳定版。大部分 Rust 用户在大部分时间使用稳定版。你可能也会这么做,不过如果你关心最新的功能,可以为特定项目使用 nightly 版。为此,可以在项目目录使用 <code>rustup override</code> 来设置当前目录 <code>rustup</code> 使用 nightly 工具链:</p>
<pre><code class="language-console">$ cd ~/projects/needs-nightly
$ rustup override set nightly
</code></pre>
<p>现在,每次在 <em>~/projects/needs-nightly</em> 调用 <code>rustc</code><code>cargo</code><code>rustup</code> 会确保使用 nightly 版 Rust。在你有很多 Rust 项目时大有裨益!</p>
<h3 id="rfc-过程和团队"><a class="header" href="#rfc-过程和团队">RFC 过程和团队</a></h3>
<p>那么你如何了解这些新功能呢Rust 开发模式遵循一个 <strong>Request For Comments (RFC) 过程</strong>。如果你希望改进 Rust可以编写一个提议也就是 RFC。</p>
<p>任何人都可以编写 RFC 来改进 Rust同时这些 RFC 会被 Rust 团队评审和讨论,他们由很多不同分工的子团队组成。这里是 <a href="https://www.rust-lang.org/governance">Rust 官网上</a> 所有团队的总列表,其包含了项目中每个领域的团队:语言设计、编译器实现、基础设施、文档等。各个团队会阅读相应的提议和评论,编写回复,并最终达成接受或回绝功能的一致。</p>
<p>如果功能被接受了,在 Rust 仓库会打开一个 issue人们就可以实现它。实现功能的人当然可能不是最初提议功能的人当实现完成后其会合并到 <code>master</code> 分支并位于一个功能开关feature gate之后正如 <a href="appendix-07-nightly-rust.html#%E4%B8%8D%E7%A8%B3%E5%AE%9A%E5%8A%9F%E8%83%BD">“不稳定功能”</a> 部分所讨论的。</p>
<p>在稍后的某个时间,一旦使用 nightly 版的 Rust 团队能够尝试这个功能了,团队成员会讨论这个功能,它如何在 nightly 中工作,并决定是否应该进入稳定版。如果决定继续推进,功能开关会移除,然后这个功能就被认为是稳定的了!乘着“发布的列车”,最终在新的稳定版 Rust 中出现。</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
</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>
<script>
window.addEventListener('load', function() {
window.setTimeout(window.print, 100);
});
</script>
</div>
</body>
</html>