The Rust Programming Language
Rust 编程语言
by Steve Klabnik and Carol Nichols, with contributions from the Rust Community
作者:Steve Klabnik 和 Carol Nichols,来自 Rust 社区的贡献
This version of the text assumes you’re using Rust 1.78.0 (released 2024-05-02)
or later. See the “Installation” section of Chapter 1
to install or update Rust.
此版本的文本假设您使用 Rust 1.78.0(2024 年 5 月 2 日发布)或更高版本。请参阅第 1 章的“安装”部分,忽略安装或更新 Rust。
The HTML format is available online at
https://doc.rust-lang.org/stable/book/
and offline with installations of Rust made with rustup
; run rustup doc --book
to open.
HTML 格式可以在https://doc.rust-lang.org/stable/book/上在线获取,也可以通过rustup
安装 Rust 来离线获取;运行rustup doc --book
以打开。
Several community translations are also available.
还提供多种社区翻译。
This text is available in paperback and ebook format from No Starch
Press.
No Starch Press 提供本文的平装本和电子书格式。
🚨 Want a more interactive learning experience? Try out a different version of the Rust Book, featuring: quizzes, highlighting, visualizations, and more: https://rust-book.cs.brown.edu
🚨 想要更具互动性的学习体验吗?尝试 Rust Book 的不同版本,其特色包括:测验、突出显示、可视化等等: https://rust-book.cs.brown.edu
Foreword 前言
It wasn’t always so clear, but the Rust programming language is fundamentally
about empowerment: no matter what kind of code you are writing now, Rust
empowers you to reach farther, to program with confidence in a wider variety of
domains than you did before.
情况并不总是那么清楚,但 Rust 编程语言从根本上讲是关于赋权:无论您现在编写什么样的代码,Rust 都能让您走得更远,比以前更有信心地在更广泛的领域进行编程。
Take, for example, “systems-level” work that deals with low-level details of
memory management, data representation, and concurrency. Traditionally, this
realm of programming is seen as arcane, accessible only to a select few who
have devoted the necessary years learning to avoid its infamous pitfalls. And
even those who practice it do so with caution, lest their code be open to
exploits, crashes, or corruption.
以处理内存管理、数据表示和并发性等低级细节的“系统级”工作为例。传统上,这个编程领域被认为是神秘的,只有少数经过多年学习以避免其臭名昭著的陷阱的人才能接触到。即使那些实践它的人也会谨慎行事,以免他们的代码容易被利用、崩溃或损坏。
Rust breaks down these barriers by eliminating the old pitfalls and providing a
friendly, polished set of tools to help you along the way. Programmers who need
to “dip down” into lower-level control can do so with Rust, without taking on
the customary risk of crashes or security holes, and without having to learn
the fine points of a fickle toolchain. Better yet, the language is designed to
guide you naturally towards reliable code that is efficient in terms of speed
and memory usage.
Rust 通过消除旧的陷阱并提供一套友好、完善的工具来帮助您一路走来,从而打破了这些障碍。需要“深入”到较低级别控制的程序员可以使用 Rust 来实现,而无需承担常见的崩溃或安全漏洞风险,也无需学习变化无常的工具链的优点。更好的是,该语言旨在引导您自然地获得在速度和内存使用方面高效的可靠代码。
Programmers who are already working with low-level code can use Rust to raise
their ambitions. For example, introducing parallelism in Rust is a relatively
low-risk operation: the compiler will catch the classical mistakes for you. And
you can tackle more aggressive optimizations in your code with the confidence
that you won’t accidentally introduce crashes or vulnerabilities.
已经在使用低级代码的程序员可以使用 Rust 来实现他们的目标。例如,在 Rust 中引入并行性是一个相对低风险的操作:编译器会为你捕获经典错误。您可以在代码中进行更积极的优化,并确信不会意外引入崩溃或漏洞。
But Rust isn’t limited to low-level systems programming. It’s expressive and
ergonomic enough to make CLI apps, web servers, and many other kinds of code
quite pleasant to write — you’ll find simple examples of both later in the
book. Working with Rust allows you to build skills that transfer from one
domain to another; you can learn Rust by writing a web app, then apply those
same skills to target your Raspberry Pi.
但 Rust 并不局限于低级系统编程。它的表现力和人体工程学足以使 CLI 应用程序、Web 服务器和许多其他类型的代码编写起来非常愉快 - 您将在本书后面找到这两者的简单示例。使用 Rust 可以让你培养从一个领域转移到另一个领域的技能;您可以通过编写 Web 应用程序来学习 Rust,然后将这些相同的技能应用于您的 Raspberry Pi。
This book fully embraces the potential of Rust to empower its users. It’s a
friendly and approachable text intended to help you level up not just your
knowledge of Rust, but also your reach and confidence as a programmer in
general. So dive in, get ready to learn—and welcome to the Rust community!
本书充分展现了 Rust 为其用户提供支持的潜力。这是一本友好且平易近人的文本,旨在帮助您不仅提高 Rust 知识,而且还提高您作为程序员的影响力和信心。因此,投入其中,准备好学习——欢迎来到 Rust 社区!
— Nicholas Matsakis and Aaron Turon
— 尼古拉斯·马萨基斯和亚伦·特隆
Introduction 介绍
Note: This edition of the book is the same as The Rust Programming
Language available in print and ebook format from No Starch
Press.
注意:本书的这个版本与No Starch Press提供的印刷版和电子书格式的《Rust 编程语言》相同。
Welcome to The Rust Programming Language, an introductory book about Rust.
The Rust programming language helps you write faster, more reliable software.
High-level ergonomics and low-level control are often at odds in programming
language design; Rust challenges that conflict. Through balancing powerful
technical capacity and a great developer experience, Rust gives you the option
to control low-level details (such as memory usage) without all the hassle
traditionally associated with such control.
欢迎阅读《Rust 编程语言》 ,这是一本关于 Rust 的介绍性书籍。 Rust 编程语言可帮助您编写更快、更可靠的软件。在编程语言设计中,高级人体工程学和低级控制常常是不一致的; Rust 挑战了这种冲突。通过平衡强大的技术能力和出色的开发人员体验,Rust 为您提供了控制低级细节(例如内存使用)的选项,而无需传统上与此类控制相关的所有麻烦。
Who Rust Is For Rust 适合谁
Rust is ideal for many people for a variety of reasons. Let’s look at a few of
the most important groups.
由于多种原因,Rust 对许多人来说是理想的选择。让我们看看几个最重要的群体。
Teams of Developers 开发团队
Rust is proving to be a productive tool for collaborating among large teams of
developers with varying levels of systems programming knowledge. Low-level code
is prone to various subtle bugs, which in most other languages can be caught
only through extensive testing and careful code review by experienced
developers. In Rust, the compiler plays a gatekeeper role by refusing to
compile code with these elusive bugs, including concurrency bugs. By working
alongside the compiler, the team can spend their time focusing on the program’s
logic rather than chasing down bugs.
Rust 被证明是一种高效的工具,可用于在具有不同系统编程知识水平的大型开发团队之间进行协作。低级代码很容易出现各种细微的错误,而在大多数其他语言中,这些错误只能通过经验丰富的开发人员进行广泛的测试和仔细的代码审查来发现。在 Rust 中,编译器扮演着看门人的角色,拒绝编译带有这些难以捉摸的错误(包括并发错误)的代码。通过与编译器一起工作,团队可以将时间集中在程序的逻辑上,而不是追查错误。
Rust also brings contemporary developer tools to the systems programming world:
Rust 还为系统编程世界带来了当代的开发工具:
- Cargo, the included dependency manager and build tool, makes adding,
compiling, and managing dependencies painless and consistent across the Rust
ecosystem.
Cargo 是随附的依赖项管理器和构建工具,使添加、编译和管理依赖项变得轻松且在整个 Rust 生态系统中保持一致。 - The Rustfmt formatting tool ensures a consistent coding style across
developers.
Rustfmt 格式化工具可确保开发人员之间保持一致的编码风格。 - The rust-analyzer powers Integrated Development Environment (IDE)
integration for code completion and inline error messages.
rust-analyzer 支持集成开发环境 (IDE) 集成,以实现代码完成和内联错误消息。
By using these and other tools in the Rust ecosystem, developers can be
productive while writing systems-level code.
通过使用 Rust 生态系统中的这些工具和其他工具,开发人员可以在编写系统级代码时提高工作效率。
Students 学生
Rust is for students and those who are interested in learning about systems
concepts. Using Rust, many people have learned about topics like operating
systems development. The community is very welcoming and happy to answer
student questions. Through efforts such as this book, the Rust teams want to
make systems concepts more accessible to more people, especially those new to
programming.
Rust 适合学生和那些有兴趣学习系统概念的人。使用 Rust,许多人了解了操作系统开发等主题。社区非常欢迎并乐意回答学生的问题。通过本书等努力,Rust 团队希望让更多人,尤其是那些刚接触编程的人更容易理解系统概念。
Companies 公司
Hundreds of companies, large and small, use Rust in production for a variety of
tasks, including command line tools, web services, DevOps tooling, embedded
devices, audio and video analysis and transcoding, cryptocurrencies,
bioinformatics, search engines, Internet of Things applications, machine
learning, and even major parts of the Firefox web browser.
数百家大大小小的公司在生产中使用 Rust 来执行各种任务,包括命令行工具、Web 服务、DevOps 工具、嵌入式设备、音频和视频分析和转码、加密货币、生物信息学、搜索引擎、物联网应用程序、机器学习,甚至是 Firefox 网络浏览器的主要部分。
Open Source Developers 开源开发人员
Rust is for people who want to build the Rust programming language, community,
developer tools, and libraries. We’d love to have you contribute to the Rust
language.
Rust 适合那些想要构建 Rust 编程语言、社区、开发工具和库的人。我们很高兴您为 Rust 语言做出贡献。
People Who Value Speed and Stability
重视速度和稳定性的人
Rust is for people who crave speed and stability in a language. By speed, we
mean both how quickly Rust code can run and the speed at which Rust lets you
write programs. The Rust compiler’s checks ensure stability through feature
additions and refactoring. This is in contrast to the brittle legacy code in
languages without these checks, which developers are often afraid to modify. By
striving for zero-cost abstractions, higher-level features that compile to
lower-level code as fast as code written manually, Rust endeavors to make safe
code be fast code as well.
Rust 适合那些渴望语言速度和稳定性的人。所谓速度,我们指的是 Rust 代码运行的速度以及 Rust 允许您编写程序的速度。 Rust 编译器的检查通过添加功能和重构来确保稳定性。这与没有这些检查的语言中脆弱的遗留代码形成鲜明对比,开发人员通常不敢修改这些代码。通过努力实现零成本抽象、与手动编写代码一样快地编译为较低级别代码的高级功能,Rust 致力于使安全代码也成为快速代码。
The Rust language hopes to support many other users as well; those mentioned
here are merely some of the biggest stakeholders. Overall, Rust’s greatest
ambition is to eliminate the trade-offs that programmers have accepted for
decades by providing safety and productivity, speed and ergonomics. Give
Rust a try and see if its choices work for you.
Rust 语言也希望支持许多其他用户;这里提到的只是一些最大的利益相关者。总的来说,Rust 最大的野心是通过提供安全性和生产力、速度和人体工程学来消除程序员几十年来所接受的权衡。尝试一下 Rust,看看它的选择是否适合您。
Who This Book Is For
这本书适合谁
This book assumes that you’ve written code in another programming language but
doesn’t make any assumptions about which one. We’ve tried to make the material
broadly accessible to those from a wide variety of programming backgrounds. We
don’t spend a lot of time talking about what programming is or how to think
about it. If you’re entirely new to programming, you would be better served by
reading a book that specifically provides an introduction to programming.
本书假设您已经用另一种编程语言编写了代码,但没有对是哪一种语言做出任何假设。我们努力让具有各种编程背景的人们能够广泛地访问这些材料。我们不会花很多时间讨论什么是编程或如何思考它。如果您对编程完全陌生,那么阅读一本专门介绍编程的书会更好。
How to Use This Book
如何使用本书
In general, this book assumes that you’re reading it in sequence from front to
back. Later chapters build on concepts in earlier chapters, and earlier
chapters might not delve into details on a particular topic but will revisit
the topic in a later chapter.
一般来说,本书假设您按从前到后的顺序阅读。后面的章节建立在前面章节中的概念的基础上,前面的章节可能不会深入研究特定主题的细节,但会在后面的章节中重新讨论该主题。
You’ll find two kinds of chapters in this book: concept chapters and project
chapters. In concept chapters, you’ll learn about an aspect of Rust. In project
chapters, we’ll build small programs together, applying what you’ve learned so
far. Chapters 2, 12, and 20 are project chapters; the rest are concept chapters.
本书中有两种章节:概念章节和项目章节。在概念章节中,您将了解 Rust 的一个方面。在项目章节中,我们将应用您迄今为止所学到的知识来共同构建小程序。第2章、第12章和第20章是项目章节;其余的是概念章节。
Chapter 1 explains how to install Rust, how to write a “Hello, world!” program,
and how to use Cargo, Rust’s package manager and build tool. Chapter 2 is a
hands-on introduction to writing a program in Rust, having you build up a
number guessing game. Here we cover concepts at a high level, and later
chapters will provide additional detail. If you want to get your hands dirty
right away, Chapter 2 is the place for that. Chapter 3 covers Rust features
that are similar to those of other programming languages, and in Chapter 4
you’ll learn about Rust’s ownership system. If you’re a particularly meticulous
learner who prefers to learn every detail before moving on to the next, you
might want to skip Chapter 2 and go straight to Chapter 3, returning to Chapter
2 when you’d like to work on a project applying the details you’ve learned.
第 1 章解释了如何安装 Rust,如何编写“Hello, world!”程序,以及如何使用 Cargo、Rust 的包管理器和构建工具。第 2 章是关于用 Rust 编写程序的实践介绍,让您构建一个猜数字游戏。在这里,我们概括地介绍了概念,后面的章节将提供更多细节。如果您想立即动手,请阅读第 2 章。第 3 章介绍了与其他编程语言类似的 Rust 功能,在第 4 章中,您将了解 Rust 的所有权系统。如果您是一个特别细心的学习者,喜欢在继续下一章之前学习每个细节,您可能想跳过第 2 章并直接进入第 3 章,当您想要从事应用程序的项目时返回第 2 章你所学到的细节。
Chapter 5 discusses structs and methods, and Chapter 6 covers enums, match
expressions, and the if let
control flow construct. You’ll use structs and
enums to make custom types in Rust.
第 5 章讨论结构和方法,第 6 章介绍枚举、 match
表达式和if let
控制流构造。您将使用结构和枚举在 Rust 中创建自定义类型。
In Chapter 7, you’ll learn about Rust’s module system and about privacy rules
for organizing your code and its public Application Programming Interface
(API). Chapter 8 discusses some common collection data structures that the
standard library provides, such as vectors, strings, and hash maps. Chapter 9
explores Rust’s error-handling philosophy and techniques.
在第 7 章中,您将了解 Rust 的模块系统以及组织代码及其公共应用程序编程接口(API)的隐私规则。第8章讨论标准库提供的一些常见的集合数据结构,例如向量、字符串和散列映射。第 9 章探讨 Rust 的错误处理理念和技术。
Chapter 10 digs into generics, traits, and lifetimes, which give you the power
to define code that applies to multiple types. Chapter 11 is all about testing,
which even with Rust’s safety guarantees is necessary to ensure your program’s
logic is correct. In Chapter 12, we’ll build our own implementation of a subset
of functionality from the grep
command line tool that searches for text
within files. For this, we’ll use many of the concepts we discussed in the
previous chapters.
第 10 章深入探讨了泛型、特征和生命周期,它们使您能够定义适用于多种类型的代码。第 11 章是关于测试的,即使有 Rust 的安全保证,测试也是确保程序逻辑正确所必需的。在第 12 章中,我们将构建我们自己的grep
命令行工具功能子集的实现,该工具在文件中搜索文本。为此,我们将使用前面章节中讨论的许多概念。
Chapter 13 explores closures and iterators: features of Rust that come from
functional programming languages. In Chapter 14, we’ll examine Cargo in more
depth and talk about best practices for sharing your libraries with others.
Chapter 15 discusses smart pointers that the standard library provides and the
traits that enable their functionality.
第 13 章探讨了闭包和迭代器:来自函数式编程语言的 Rust 特性。在第 14 章中,我们将更深入地研究 Cargo 并讨论与其他人共享库的最佳实践。第 15 章讨论标准库提供的智能指针以及实现其功能的特征。
In Chapter 16, we’ll walk through different models of concurrent programming
and talk about how Rust helps you to program in multiple threads fearlessly.
Chapter 17 looks at how Rust idioms compare to object-oriented programming
principles you might be familiar with.
在第 16 章中,我们将介绍并发编程的不同模型,并讨论 Rust 如何帮助您无所畏惧地在多线程中进行编程。第 17 章着眼于 Rust 习惯用法与您可能熟悉的面向对象编程原理的比较。
Chapter 18 is a reference on patterns and pattern matching, which are powerful
ways of expressing ideas throughout Rust programs. Chapter 19 contains a
smorgasbord of advanced topics of interest, including unsafe Rust, macros, and
more about lifetimes, traits, types, functions, and closures.
第 18 章是关于模式和模式匹配的参考,它们是在 Rust 程序中表达想法的强大方式。第 19 章包含了一系列令人感兴趣的高级主题,包括不安全的 Rust、宏以及更多关于生命周期、特征、类型、函数和闭包的内容。
In Chapter 20, we’ll complete a project in which we’ll implement a low-level
multithreaded web server!
在第 20 章中,我们将完成一个项目,在该项目中我们将实现一个低级多线程 Web 服务器!
Finally, some appendices contain useful information about the language in a
more reference-like format. Appendix A covers Rust’s keywords, Appendix B
covers Rust’s operators and symbols, Appendix C covers derivable traits
provided by the standard library, Appendix D covers some useful development
tools, and Appendix E explains Rust editions. In Appendix F, you can find
translations of the book, and in Appendix G we’ll cover how Rust is made and
what nightly Rust is.
最后,一些附录以更像参考的格式包含有关该语言的有用信息。附录 A 涵盖 Rust 的关键字,附录 B 涵盖 Rust 的运算符和符号,附录 C 涵盖标准库提供的可派生特征,附录 D 涵盖一些有用的开发工具,附录 E 解释 Rust 版本。在附录 F 中,您可以找到本书的翻译,在附录 G 中,我们将介绍 Rust 的制作方法以及夜间 Rust 是什么。
There is no wrong way to read this book: if you want to skip ahead, go for it!
You might have to jump back to earlier chapters if you experience any
confusion. But do whatever works for you.
阅读这本书没有错误的方法:如果你想跳过,就直接跳过去吧!如果您遇到任何困惑,您可能必须跳回到前面的章节。但做任何对你有用的事情。
An important part of the process of learning Rust is learning how to read the
error messages the compiler displays: these will guide you toward working code.
As such, we’ll provide many examples that don’t compile along with the error
message the compiler will show you in each situation. Know that if you enter
and run a random example, it may not compile! Make sure you read the
surrounding text to see whether the example you’re trying to run is meant to
error. Ferris will also help you distinguish code that isn’t meant to work:
学习 Rust 过程的一个重要部分是学习如何阅读编译器显示的错误消息:这些将引导您编写工作代码。因此,我们将提供许多无法编译的示例以及编译器在每种情况下向您显示的错误消息。请注意,如果您输入并运行随机示例,它可能无法编译!请务必阅读周围的文本,看看您尝试运行的示例是否会出错。 Ferris 还将帮助您区分不起作用的代码:
Ferris 费里斯 | Meaning 意义 |
---|---|
This code does not compile! 这段代码无法编译! | |
This code panics! 这段代码会引起恐慌! | |
This code does not produce the desired behavior. 此代码不会产生所需的行为。 |
In most situations, we’ll lead you to the correct version of any code that
doesn’t compile.
在大多数情况下,我们会引导您找到任何无法编译的代码的正确版本。
Source Code 源代码
The source files from which this book is generated can be found on
GitHub.
生成本书的源文件可以在GitHub上找到。
Getting Started 入门
Let’s start your Rust journey! There’s a lot to learn, but every journey starts
somewhere. In this chapter, we’ll discuss:
让我们开始您的 Rust 之旅吧!有很多东西需要学习,但每一次旅程都从某个地方开始。在本章中,我们将讨论:
- Installing Rust on Linux, macOS, and Windows
在 Linux、macOS 和 Windows 上安装 Rust - Writing a program that prints
Hello, world!
编写一个打印Hello, world!
的程序 - Using
cargo
, Rust’s package manager and build system
使用cargo
、Rust 的包管理器和构建系统
Installation 安装
The first step is to install Rust. We’ll download Rust through rustup
, a
command line tool for managing Rust versions and associated tools. You’ll need
an internet connection for the download.
第一步是安装 Rust。我们将通过rustup
下载 Rust,这是一个用于管理 Rust 版本和相关工具的命令行工具。您需要连接互联网才能下载。
Note: If you prefer not to use rustup
for some reason, please see the
Other Rust Installation Methods page for more options.
注意:如果您出于某种原因不想使用rustup
,请参阅其他 Rust 安装方法页面以获取更多选项。
The following steps install the latest stable version of the Rust compiler.
Rust’s stability guarantees ensure that all the examples in the book that
compile will continue to compile with newer Rust versions. The output might
differ slightly between versions because Rust often improves error messages and
warnings. In other words, any newer, stable version of Rust you install using
these steps should work as expected with the content of this book.
以下步骤安装最新稳定版本的 Rust 编译器。 Rust 的稳定性保证确保书中所有编译的示例都将继续使用较新的 Rust 版本进行编译。版本之间的输出可能略有不同,因为 Rust 通常会改进错误消息和警告。换句话说,使用这些步骤安装的任何较新、稳定的 Rust 版本都应该按照本书的内容按预期工作。
Command Line Notation 命令行表示法
In this chapter and throughout the book, we’ll show some commands used in the
terminal. Lines that you should enter in a terminal all start with $
. You
don’t need to type the $
character; it’s the command line prompt shown to
indicate the start of each command. Lines that don’t start with $
typically
show the output of the previous command. Additionally, PowerShell-specific
examples will use >
rather than $
.
在本章和整本书中,我们将展示终端中使用的一些命令。您应该在终端中输入的行均以$
开头。您不需要键入$
字符;它是显示的命令行提示符,指示每个命令的开始。不以$
开头的行通常显示上一个命令的输出。此外,特定于 PowerShell 的示例将使用>
而不是$
。
Installing rustup
on Linux or macOS
在 Linux 或 macOS 上安装rustup
If you’re using Linux or macOS, open a terminal and enter the following command:
如果您使用的是 Linux 或 macOS,请打开终端并输入以下命令:
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
The command downloads a script and starts the installation of the rustup
tool, which installs the latest stable version of Rust. You might be prompted
for your password. If the install is successful, the following line will appear:
该命令下载脚本并开始安装rustup
工具,该工具将安装 Rust 的最新稳定版本。系统可能会提示您输入密码。如果安装成功,会出现下面一行:
Rust is installed now. Great!
You will also need a linker, which is a program that Rust uses to join its
compiled outputs into one file. It is likely you already have one. If you get
linker errors, you should install a C compiler, which will typically include a
linker. A C compiler is also useful because some common Rust packages depend on
C code and will need a C compiler.
您还需要一个链接器,这是 Rust 用来将其编译输出连接到一个文件中的程序。您很可能已经拥有一个。如果出现链接器错误,则应安装 C 编译器,该编译器通常包含链接器。 AC 编译器也很有用,因为一些常见的 Rust 包依赖于 C 代码,并且需要 C 编译器。
On macOS, you can get a C compiler by running:
在 macOS 上,您可以通过运行以下命令来获取 C 编译器:
$ xcode-select --install
Linux users should generally install GCC or Clang, according to their
distribution’s documentation. For example, if you use Ubuntu, you can install
the build-essential
package.
Linux 用户通常应该根据其发行版的文档安装 GCC 或 Clang。例如,如果您使用 Ubuntu,则可以安装build-essential
包。
Installing rustup
on Windows
在 Windows 上安装rustup
On Windows, go to https://www.rust-lang.org/tools/install and follow
the instructions for installing Rust. At some point in the installation, you’ll
be prompted to install Visual Studio. This provides a linker and the native
libraries needed to compile programs. If you need more help with this step, see
https://rust-lang.github.io/rustup/installation/windows-msvc.html
在 Windows 上,请访问https://www.rust-lang.org/tools/install并按照安装 Rust 的说明进行操作。在安装过程中的某个时刻,系统会提示您安装 Visual Studio。这提供了编译程序所需的链接器和本机库。如果您需要有关此步骤的更多帮助,请参阅https://rust-lang.github.io/rustup/installation/windows-msvc.html
The rest of this book uses commands that work in both cmd.exe and PowerShell.
If there are specific differences, we’ll explain which to use.
本书的其余部分使用可在cmd.exe和 PowerShell 中运行的命令。如果存在具体差异,我们将解释使用哪个。
Troubleshooting 故障排除
To check whether you have Rust installed correctly, open a shell and enter this
line:
要检查 Rust 是否正确安装,请打开 shell 并输入以下行:
$ rustc --version
You should see the version number, commit hash, and commit date for the latest
stable version that has been released, in the following format:
您应该看到已发布的最新稳定版本的版本号、提交哈希值和提交日期,格式如下:
rustc x.y.z (abcabcabc yyyy-mm-dd)
If you see this information, you have installed Rust successfully! If you don’t
see this information, check that Rust is in your %PATH%
system variable as
follows.
如果你看到这个信息,说明你已经安装Rust成功了!如果您没有看到此信息,请检查 Rust 是否在您的%PATH%
系统变量中,如下所示。
In Windows CMD, use: 在 Windows CMD 中,使用:
> echo %PATH%
In PowerShell, use: 在 PowerShell 中,使用:
> echo $env:Path
In Linux and macOS, use:
在 Linux 和 macOS 中,使用:
$ echo $PATH
If that’s all correct and Rust still isn’t working, there are a number of
places you can get help. Find out how to get in touch with other Rustaceans (a
silly nickname we call ourselves) on the community page.
如果一切正确,但 Rust 仍然无法工作,您可以从很多地方获得帮助。在社区页面上了解如何与其他 Rustaceans(我们给自己起的一个愚蠢的昵称)取得联系。
Updating and Uninstalling
更新和卸载
Once Rust is installed via rustup
, updating to a newly released version is
easy. From your shell, run the following update script:
通过rustup
安装 Rust 后,更新到新发布的版本就很容易了。从 shell 中运行以下更新脚本:
$ rustup update
To uninstall Rust and rustup
, run the following uninstall script from your
shell:
要卸载 Rust 和rustup
,请从 shell 运行以下卸载脚本:
$ rustup self uninstall
Local Documentation 本地文档
The installation of Rust also includes a local copy of the documentation so
that you can read it offline. Run rustup doc
to open the local documentation
in your browser.
Rust 的安装还包括文档的本地副本,以便您可以离线阅读。运行rustup doc
以在浏览器中打开本地文档。
Any time a type or function is provided by the standard library and you’re not
sure what it does or how to use it, use the application programming interface
(API) documentation to find out!
每当标准库提供类型或函数并且您不确定它的作用或如何使用它时,请使用应用程序编程接口 (API) 文档来查找!
Hello, World! 你好世界!
Now that you’ve installed Rust, it’s time to write your first Rust program.
It’s traditional when learning a new language to write a little program that
prints the text Hello, world!
to the screen, so we’ll do the same here!
现在您已经安装了 Rust,是时候编写您的第一个 Rust 程序了。学习一门新语言时,传统做法是编写一个小程序来打印文本Hello, world!
到屏幕上,所以我们在这里也做同样的事情!
Note: This book assumes basic familiarity with the command line. Rust makes
no specific demands about your editing or tooling or where your code lives, so
if you prefer to use an integrated development environment (IDE) instead of
the command line, feel free to use your favorite IDE. Many IDEs now have some
degree of Rust support; check the IDE’s documentation for details. The Rust
team has been focusing on enabling great IDE support via rust-analyzer
. See
Appendix D for more details.
注意:本书假设您对命令行有基本的熟悉。 Rust 对您的编辑、工具或代码所在位置没有具体要求,因此,如果您更喜欢使用集成开发环境 (IDE) 而不是命令行,请随意使用您最喜欢的 IDE。现在许多 IDE 都具有一定程度的 Rust 支持;有关详细信息,请查看 IDE 的文档。 Rust 团队一直致力于通过rust-analyzer
提供强大的 IDE 支持。有关详细信息,请参阅附录 D忽略。
Creating a Project Directory
创建项目目录
You’ll start by making a directory to store your Rust code. It doesn’t matter
to Rust where your code lives, but for the exercises and projects in this book,
we suggest making a projects directory in your home directory and keeping all
your projects there.
您将首先创建一个目录来存储 Rust 代码。对于 Rust 来说,你的代码所在的位置并不重要,但对于本书中的练习和项目,我们建议在你的主目录中创建一个项目目录,并将所有项目保存在那里。
Open a terminal and enter the following commands to make a projects directory
and a directory for the “Hello, world!” project within the projects directory.
打开终端并输入以下命令来创建项目目录和“Hello, world!”目录项目位于项目目录中。
For Linux, macOS, and PowerShell on Windows, enter this:
对于 Linux、macOS 和 Windows 上的 PowerShell,请输入:
$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
For Windows CMD, enter this:
对于 Windows CMD,请输入:
> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir hello_world
> cd hello_world
Writing and Running a Rust Program
编写并运行 Rust 程序
Next, make a new source file and call it main.rs. Rust files always end with
the .rs extension. If you’re using more than one word in your filename, the
convention is to use an underscore to separate them. For example, use
hello_world.rs rather than helloworld.rs.
接下来,创建一个新的源文件并将其命名为main.rs 。 Rust 文件始终以.rs扩展名结尾。如果您的文件名中使用了多个单词,则惯例是使用下划线分隔它们。例如,使用hello_world.rs而不是helloworld.rs 。
Now open the main.rs file you just created and enter the code in Listing 1-1.
现在打开刚刚创建的main.rs文件并输入清单 1-1 中的代码。
Save the file and go back to your terminal window in the
~/projects/hello_world directory. On Linux or macOS, enter the following
commands to compile and run the file:
保存文件并返回到~/projects/hello_world目录中的终端窗口。在 Linux 或 macOS 上,输入以下命令来编译并运行该文件:
$ rustc main.rs
$ ./main
Hello, world!
On Windows, enter the command .\main.exe
instead of ./main
:
在 Windows 上,输入命令.\main.exe
而不是./main
:
> rustc main.rs
> .\main.exe
Hello, world!
Regardless of your operating system, the string Hello, world!
should print to
the terminal. If you don’t see this output, refer back to the
“Troubleshooting” part of the Installation
section for ways to get help.
无论您使用什么操作系统,字符串Hello, world!
应该打印到终端。如果您没有看到此输出,请参阅安装部分的“故障排除”忽略部分,了解获取帮助的方法。
If Hello, world!
did print, congratulations! You’ve officially written a Rust
program. That makes you a Rust programmer—welcome!
如果Hello, world!
打印出来了,恭喜!您已经正式编写了一个 Rust 程序。这使您成为一名 Rust 程序员——欢迎!
Anatomy of a Rust Program
Rust 程序剖析
Let’s review this “Hello, world!” program in detail. Here’s the first piece of
the puzzle:
让我们回顾一下这首《你好,世界!》详细的计划。这是拼图的第一块:
fn main() {
}
These lines define a function named main
. The main
function is special: it
is always the first code that runs in every executable Rust program. Here, the
first line declares a function named main
that has no parameters and returns
nothing. If there were parameters, they would go inside the parentheses ()
.
这些行定义了一个名为main
函数。 main
函数很特殊:它始终是每个可执行 Rust 程序中运行的第一个代码。这里,第一行声明了一个名为main
函数,它没有参数,也不返回任何内容。如果有参数,它们将放在括号()
内。
The function body is wrapped in {}
. Rust requires curly brackets around all
function bodies. It’s good style to place the opening curly bracket on the same
line as the function declaration, adding one space in between.
函数体被包裹在{}
中。 Rust 要求所有函数体都用大括号括起来。将左大括号与函数声明放在同一行,并在中间添加一个空格是一种很好的风格。
Note: If you want to stick to a standard style across Rust projects, you can
use an automatic formatter tool called rustfmt
to format your code in a
particular style (more on rustfmt
in
Appendix D). The Rust team has included this tool
with the standard Rust distribution, as rustc
is, so it should already be
installed on your computer!
注意:如果您想在 Rust 项目中坚持使用标准样式,您可以使用名为rustfmt
的自动格式化工具以特定样式格式化您的代码(附录 D中有关rustfmt
更多信息忽略)。 Rust 团队已将该工具包含在标准 Rust 发行版中,就像rustc
一样,因此它应该已经安装在您的计算机上!
The body of the main
function holds the following code:main
函数的主体包含以下代码:
This line does all the work in this little program: it prints text to the
screen. There are four important details to notice here.
这一行完成了这个小程序中的所有工作:它将文本打印到屏幕上。这里有四个重要细节需要注意。
First, Rust style is to indent with four spaces, not a tab.
首先,Rust 风格是用四个空格缩进,而不是制表符。
Second, println!
calls a Rust macro. If it had called a function instead, it
would be entered as println
(without the !
). We’ll discuss Rust macros in
more detail in Chapter 19. For now, you just need to know that using a !
means that you’re calling a macro instead of a normal function and that macros
don’t always follow the same rules as functions.
第二, println!
调用 Rust 宏。如果它调用了一个函数,那么它将被输入为println
(不带!
)。我们将在第 19 章中更详细地讨论 Rust 宏。现在,您只需要知道使用!
意味着您正在调用宏而不是普通函数,并且宏并不总是遵循与函数相同的规则。
Third, you see the "Hello, world!"
string. We pass this string as an argument
to println!
, and the string is printed to the screen.
第三,您会看到"Hello, world!"
细绳。我们将此字符串作为参数传递给println!
,并且字符串被打印到屏幕上。
Fourth, we end the line with a semicolon (;
), which indicates that this
expression is over and the next one is ready to begin. Most lines of Rust code
end with a semicolon.
第四,我们以分号( ;
)结束该行,这表明该表达式已结束,下一个表达式已准备好开始。大多数 Rust 代码行都以分号结尾。
Compiling and Running Are Separate Steps
编译和运行是分开的步骤
You’ve just run a newly created program, so let’s examine each step in the
process.
您刚刚运行了一个新创建的程序,所以让我们检查一下该过程中的每个步骤。
Before running a Rust program, you must compile it using the Rust compiler by
entering the rustc
command and passing it the name of your source file, like
this:
在运行 Rust 程序之前,您必须使用 Rust 编译器来编译它,方法是输入rustc
命令并向其传递源文件的名称,如下所示:
$ rustc main.rs
If you have a C or C++ background, you’ll notice that this is similar to gcc
or clang
. After compiling successfully, Rust outputs a binary executable.
如果您有 C 或 C++ 背景,您会注意到这与gcc
或clang
类似。编译成功后,Rust 输出一个二进制可执行文件。
On Linux, macOS, and PowerShell on Windows, you can see the executable by
entering the ls
command in your shell:
在 Linux、macOS 和 Windows 上的 PowerShell 上,您可以通过在 shell 中输入ls
命令来查看可执行文件:
$ ls
main main.rs
On Linux and macOS, you’ll see two files. With PowerShell on Windows, you’ll
see the same three files that you would see using CMD. With CMD on Windows, you
would enter the following:
在 Linux 和 macOS 上,您将看到两个文件。使用 Windows 上的 PowerShell,您将看到与使用 CMD 看到的相同的三个文件。使用 Windows 上的 CMD,您将输入以下内容:
> dir /B %= the /B option says to only show the file names =%
main.exe
main.pdb
main.rs
This shows the source code file with the .rs extension, the executable file
(main.exe on Windows, but main on all other platforms), and, when using
Windows, a file containing debugging information with the .pdb extension.
From here, you run the main or main.exe file, like this:
这显示了扩展名为.rs的源代码文件、可执行文件(Windows 上为main.exe ,但在所有其他平台上为 main ),以及使用 Windows 时包含扩展名为.pdb 的调试信息的文件。从这里,您运行main或main.exe文件,如下所示:
$ ./main # or .\main.exe on Windows
If your main.rs is your “Hello, world!” program, this line prints Hello, world!
to your terminal.
如果你的main.rs是你的“Hello, world!”程序中,这一行打印Hello, world!
到您的终端。
If you’re more familiar with a dynamic language, such as Ruby, Python, or
JavaScript, you might not be used to compiling and running a program as
separate steps. Rust is an ahead-of-time compiled language, meaning you can
compile a program and give the executable to someone else, and they can run it
even without having Rust installed. If you give someone a .rb, .py, or
.js file, they need to have a Ruby, Python, or JavaScript implementation
installed (respectively). But in those languages, you only need one command to
compile and run your program. Everything is a trade-off in language design.
如果您更熟悉动态语言,例如 Ruby、Python 或 JavaScript,您可能不习惯将程序编译和运行作为单独的步骤。 Rust 是一种提前编译的语言,这意味着您可以编译程序并将可执行文件提供给其他人,即使没有安装 Rust,他们也可以运行它。如果您向某人提供.rb 、 .py或.js文件,他们需要(分别)安装 Ruby、Python 或 JavaScript 实现。但在这些语言中,您只需要一个命令来编译和运行您的程序。一切都是语言设计的权衡。
Just compiling with rustc
is fine for simple programs, but as your project
grows, you’ll want to manage all the options and make it easy to share your
code. Next, we’ll introduce you to the Cargo tool, which will help you write
real-world Rust programs.
对于简单的程序来说,使用rustc
进行编译就足够了,但随着项目的增长,您将需要管理所有选项并轻松共享代码。接下来,我们将向您介绍 Cargo 工具,它将帮助您编写真实的 Rust 程序。
Hello, Cargo! 你好,货物!
Cargo is Rust’s build system and package manager. Most Rustaceans use this tool
to manage their Rust projects because Cargo handles a lot of tasks for you,
such as building your code, downloading the libraries your code depends on, and
building those libraries. (We call the libraries that your code needs
dependencies.)
Cargo 是 Rust 的构建系统和包管理器。大多数 Rustaceans 使用这个工具来管理他们的 Rust 项目,因为 Cargo 会为您处理很多任务,例如构建代码、下载代码所依赖的库以及构建这些库。 (我们将您的代码需要的库称为“依赖项” 。)
The simplest Rust programs, like the one we’ve written so far, don’t have any
dependencies. If we had built the “Hello, world!” project with Cargo, it would
only use the part of Cargo that handles building your code. As you write more
complex Rust programs, you’ll add dependencies, and if you start a project
using Cargo, adding dependencies will be much easier to do.
最简单的 Rust 程序,就像我们迄今为止编写的程序一样,没有任何依赖项。如果我们建造了“你好,世界!”使用 Cargo 进行项目时,它只会使用 Cargo 中处理构建代码的部分。当你编写更复杂的 Rust 程序时,你将添加依赖项,如果你使用 Cargo 启动一个项目,添加依赖项会更容易。
Because the vast majority of Rust projects use Cargo, the rest of this book
assumes that you’re using Cargo too. Cargo comes installed with Rust if you
used the official installers discussed in the
“Installation” section. If you installed Rust
through some other means, check whether Cargo is installed by entering the
following in your terminal:
由于绝大多数 Rust 项目都使用 Cargo,因此本书的其余部分假设您也使用 Cargo。如果您使用“安装”忽略部分中讨论的官方安装程序,Cargo 会随 Rust 一起安装。如果您通过其他方式安装了 Rust,请在终端中输入以下内容来检查 Cargo 是否已安装:
$ cargo --version
If you see a version number, you have it! If you see an error, such as command not found
, look at the documentation for your method of installation to
determine how to install Cargo separately.
如果您看到版本号,则说明您已拥有它!如果您看到错误,例如command not found
,请查看您的安装方法的文档,以确定如何单独安装 Cargo。
Creating a Project with Cargo
使用 Cargo 创建项目
Let’s create a new project using Cargo and look at how it differs from our
original “Hello, world!” project. Navigate back to your projects directory
(or wherever you decided to store your code). Then, on any operating system,
run the following:
让我们使用 Cargo 创建一个新项目,看看它与我们原来的“Hello, world!”有何不同。项目。导航回您的项目目录(或您决定存储代码的任何位置)。然后,在任何操作系统上运行以下命令:
$ cargo new hello_cargo
$ cd hello_cargo
The first command creates a new directory and project called hello_cargo.
We’ve named our project hello_cargo, and Cargo creates its files in a
directory of the same name.
第一个命令创建一个名为hello_cargo的新目录和项目。我们将项目命名为hello_cargo ,Cargo 在同名目录中创建其文件。
Go into the hello_cargo directory and list the files. You’ll see that Cargo
has generated two files and one directory for us: a Cargo.toml file and a
src directory with a main.rs file inside.
进入hello_cargo目录并列出文件。你会看到 Cargo 为我们生成了两个文件和一个目录:一个Cargo.toml文件和一个src目录,里面有一个main.rs文件。
It has also initialized a new Git repository along with a .gitignore file.
Git files won’t be generated if you run cargo new
within an existing Git
repository; you can override this behavior by using cargo new --vcs=git
.
它还初始化了一个新的 Git 存储库以及一个.gitignore文件。如果您在现有的 Git 存储库中运行cargo new
,则不会生成 Git 文件;您可以使用cargo new --vcs=git
覆盖此行为。
Note: Git is a common version control system. You can change cargo new
to
use a different version control system or no version control system by using
the --vcs
flag. Run cargo new --help
to see the available options.
注:Git 是一个常见的版本控制系统。您可以使用--vcs
标志将cargo new
更改为使用不同的版本控制系统或不使用版本控制系统。运行cargo new --help
以查看可用选项。
Open Cargo.toml in your text editor of choice. It should look similar to the
code in Listing 1-2.
在您选择的文本编辑器中打开Cargo.toml 。它应该类似于清单 1-2 中的代码。
This file is in the TOML (Tom’s Obvious, Minimal
Language) format, which is Cargo’s configuration format.
该文件采用TOMLignore ( Tom's Obvious,Minimal Language )格式,这是 Cargo 的配置格式。
The first line, [package]
, is a section heading that indicates that the
following statements are configuring a package. As we add more information to
this file, we’ll add other sections.
第一行[package]
是一个节标题,指示以下语句正在配置包。当我们向该文件添加更多信息时,我们将添加其他部分。
The next three lines set the configuration information Cargo needs to compile
your program: the name, the version, and the edition of Rust to use. We’ll talk
about the edition
key in Appendix E.
接下来的三行设置 Cargo 编译程序所需的配置信息:名称、版本和要使用的 Rust 版本。我们将在附录 Eignore中讨论edition
密钥。
The last line, [dependencies]
, is the start of a section for you to list any
of your project’s dependencies. In Rust, packages of code are referred to as
crates. We won’t need any other crates for this project, but we will in the
first project in Chapter 2, so we’ll use this dependencies section then.
最后一行[dependencies]
是一个部分的开始,用于列出项目的任何依赖项。在 Rust 中,代码包被称为crates 。该项目不需要任何其他 crate,但我们将在第 2 章的第一个项目中使用,因此我们将使用此依赖项部分。
Now open src/main.rs and take a look:
现在打开src/main.rs看看:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
println!("Hello, world!");
}
Cargo has generated a “Hello, world!” program for you, just like the one we
wrote in Listing 1-1! So far, the differences between our project and the
project Cargo generated are that Cargo placed the code in the src directory
and we have a Cargo.toml configuration file in the top directory.
Cargo 生成了“Hello, world!”为您准备的程序,就像我们在清单 1-1 中编写的程序一样!到目前为止,我们的项目和 Cargo 生成的项目之间的区别在于 Cargo 将代码放在src目录中,并且我们在顶层目录中有一个Cargo.toml配置文件。
Cargo expects your source files to live inside the src directory. The
top-level project directory is just for README files, license information,
configuration files, and anything else not related to your code. Using Cargo
helps you organize your projects. There’s a place for everything, and
everything is in its place.
Cargo 希望您的源文件位于src目录中。顶级项目目录仅用于 README 文件、许可证信息、配置文件以及与代码无关的任何其他内容。使用 Cargo 可以帮助您组织项目。一切都有一个地方,一切都在它的位置上。
If you started a project that doesn’t use Cargo, as we did with the “Hello,
world!” project, you can convert it to a project that does use Cargo. Move the
project code into the src directory and create an appropriate Cargo.toml
file.
如果您启动了一个不使用 Cargo 的项目,就像我们对“Hello, world!”所做的那样项目,您可以将其转换为使用 Cargo 的项目。将项目代码移至src目录并创建适当的Cargo.toml文件。
Building and Running a Cargo Project
构建和运行货运项目
Now let’s look at what’s different when we build and run the “Hello, world!”
program with Cargo! From your hello_cargo directory, build your project by
entering the following command:
现在让我们看看构建和运行“Hello, world!”时有什么不同。与 Cargo 一起计划!在hello_cargo目录中,输入以下命令来构建项目:
$ cargo build
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
This command creates an executable file in target/debug/hello_cargo (or
target\debug\hello_cargo.exe on Windows) rather than in your current
directory. Because the default build is a debug build, Cargo puts the binary in
a directory named debug. You can run the executable with this command:
此命令在target/debug/hello_cargo (或 Windows 上的target\debug\hello_cargo.exe )而不是在当前目录中创建可执行文件。由于默认构建是调试构建,因此 Cargo 将二进制文件放在名为debug的目录中。您可以使用以下命令运行可执行文件:
$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
Hello, world!
If all goes well, Hello, world!
should print to the terminal. Running cargo build
for the first time also causes Cargo to create a new file at the top
level: Cargo.lock. This file keeps track of the exact versions of
dependencies in your project. This project doesn’t have dependencies, so the
file is a bit sparse. You won’t ever need to change this file manually; Cargo
manages its contents for you.
如果一切顺利的话, Hello, world!
应该打印到终端。第一次运行cargo build
还会导致 Cargo 在顶层创建一个新文件: Cargo.lock 。该文件跟踪项目中依赖项的确切版本。该项目没有依赖项,因此文件有点稀疏。您无需手动更改此文件; Cargo 为您管理其内容。
We just built a project with cargo build
and ran it with
./target/debug/hello_cargo
, but we can also use cargo run
to compile the
code and then run the resultant executable all in one command:
我们刚刚使用cargo build
构建了一个项目,并使用./target/debug/hello_cargo
运行它,但我们也可以使用cargo run
来编译代码,然后在一个命令中运行生成的可执行文件:
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/hello_cargo`
Hello, world!
Using cargo run
is more convenient than having to remember to run cargo build
and then use the whole path to the binary, so most developers use cargo run
.
使用cargo run
比必须记住运行cargo build
然后使用二进制文件的整个路径更方便,因此大多数开发人员使用cargo run
。
Notice that this time we didn’t see output indicating that Cargo was compiling
hello_cargo
. Cargo figured out that the files hadn’t changed, so it didn’t
rebuild but just ran the binary. If you had modified your source code, Cargo
would have rebuilt the project before running it, and you would have seen this
output:
请注意,这次我们没有看到表明 Cargo 正在编译hello_cargo
的输出。 Cargo 发现文件没有改变,所以它没有重建,只是运行二进制文件。如果您修改了源代码,Cargo 将在运行之前重新构建项目,并且您将看到以下输出:
$ 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!
Cargo also provides a command called cargo check
. This command quickly checks
your code to make sure it compiles but doesn’t produce an executable:
Cargo还提供了一个名为cargo check
命令。此命令快速检查您的代码以确保它可以编译但不会生成可执行文件:
$ cargo check
Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
Why would you not want an executable? Often, cargo check
is much faster than
cargo build
because it skips the step of producing an executable. If you’re
continually checking your work while writing the code, using cargo check
will
speed up the process of letting you know if your project is still compiling! As
such, many Rustaceans run cargo check
periodically as they write their
program to make sure it compiles. Then they run cargo build
when they’re
ready to use the executable.
为什么你不想要一个可执行文件?通常, cargo check
比cargo build
快得多,因为它跳过了生成可执行文件的步骤。如果您在编写代码时不断检查您的工作,那么使用cargo check
将加快让您知道项目是否仍在编译的过程!因此,许多 Rustaceans 在编写程序时定期运行cargo check
以确保其编译。然后,当他们准备好使用可执行文件时,他们会运行cargo build
。
Let’s recap what we’ve learned so far about Cargo:
让我们回顾一下到目前为止我们所学到的有关 Cargo 的知识:
- We can create a project using
cargo new
.
我们可以使用cargo new
创建一个项目。 - We can build a project using
cargo build
.
我们可以使用cargo build
构建一个项目。 - We can build and run a project in one step using
cargo run
.
我们可以使用cargo run
一步构建并运行一个项目。 - We can build a project without producing a binary to check for errors using
cargo check
.
我们可以在不生成二进制文件的情况下构建项目,以使用cargo check
检查错误。 - Instead of saving the result of the build in the same directory as our code,
Cargo stores it in the target/debug directory.
Cargo 没有将构建结果保存在与我们的代码相同的目录中,而是将其存储在target/debug目录中。
An additional advantage of using Cargo is that the commands are the same no
matter which operating system you’re working on. So, at this point, we’ll no
longer provide specific instructions for Linux and macOS versus Windows.
使用 Cargo 的另一个优点是,无论您使用哪种操作系统,命令都是相同的。因此,目前我们将不再提供针对 Linux 和 macOS 与 Windows 的具体说明。
Building for Release 构建发布
When your project is finally ready for release, you can use cargo build --release
to compile it with optimizations. This command will create an
executable in target/release instead of target/debug. The optimizations
make your Rust code run faster, but turning them on lengthens the time it takes
for your program to compile. This is why there are two different profiles: one
for development, when you want to rebuild quickly and often, and another for
building the final program you’ll give to a user that won’t be rebuilt
repeatedly and that will run as fast as possible. If you’re benchmarking your
code’s running time, be sure to run cargo build --release
and benchmark with
the executable in target/release.
当您的项目最终准备好发布时,您可以使用cargo build --release
对其进行优化编译。此命令将在target/release而不是target/debug中创建可执行文件。这些优化使您的 Rust 代码运行得更快,但打开它们会延长程序编译所需的时间。这就是为什么有两种不同的配置文件:一种用于开发,当您想要快速且频繁地重建时,另一种用于构建最终程序,您将提供给用户,该程序不会重复重建并且运行速度与可能的。如果您要对代码的运行时间进行基准测试,请务必运行cargo build --release
并使用target/release中的可执行文件进行基准测试。
Cargo as Convention 货物作为惯例
With simple projects, Cargo doesn’t provide a lot of value over just using
rustc
, but it will prove its worth as your programs become more intricate.
Once programs grow to multiple files or need a dependency, it’s much easier to
let Cargo coordinate the build.
对于简单的项目,Cargo 并不能提供比仅使用rustc
更大的价值,但随着你的程序变得更加复杂,它会证明它的价值。一旦程序增长到多个文件或需要依赖项,让 Cargo 协调构建就会容易得多。
Even though the hello_cargo
project is simple, it now uses much of the real
tooling you’ll use in the rest of your Rust career. In fact, to work on any
existing projects, you can use the following commands to check out the code
using Git, change to that project’s directory, and build:
尽管hello_cargo
项目很简单,但它现在使用了您在 Rust 职业生涯的其余部分中将使用的许多真实工具。事实上,要处理任何现有项目,您可以使用以下命令通过 Git 检查代码,更改到该项目的目录,然后构建:
$ git clone example.org/someproject
$ cd someproject
$ cargo build
For more information about Cargo, check out its documentation.
有关 Cargo 的更多信息,请查看其文档。
Summary 概括
You’re already off to a great start on your Rust journey! In this chapter,
you’ve learned how to:
您的 Rust 之旅已经有了一个良好的开端!在本章中,您学习了如何:
- Install the latest stable version of Rust using
rustup
使用rustup
安装最新稳定版本的 Rust - Update to a newer Rust version
更新到较新的 Rust 版本 - Open locally installed documentation
打开本地安装的文档 - Write and run a “Hello, world!” program using
rustc
directly
编写并运行“Hello, world!”直接使用rustc
进行编程 - Create and run a new project using the conventions of Cargo
使用 Cargo 约定创建并运行一个新项目
This is a great time to build a more substantial program to get used to reading
and writing Rust code. So, in Chapter 2, we’ll build a guessing game program.
If you would rather start by learning how common programming concepts work in
Rust, see Chapter 3 and then return to Chapter 2.
现在是构建一个更充实的程序以习惯阅读和编写 Rust 代码的好时机。因此,在第 2 章中,我们将构建一个猜谜游戏程序。如果您想从学习 Rust 中常见编程概念的工作原理开始,请参阅第 3 章,然后返回第 2 章。
Programming a Guessing Game
编写一个猜谜游戏
Let’s jump into Rust by working through a hands-on project together! This
chapter introduces you to a few common Rust concepts by showing you how to use
them in a real program. You’ll learn about let
, match
, methods, associated
functions, external crates, and more! In the following chapters, we’ll explore
these ideas in more detail. In this chapter, you’ll just practice the
fundamentals.
让我们一起完成一个实践项目来进入 Rust!本章通过向您展示如何在实际程序中使用它们来向您介绍一些常见的 Rust 概念。您将了解let
、 match
、方法、关联函数、外部包等等!在接下来的章节中,我们将更详细地探讨这些想法。在本章中,您将只练习基础知识。
We’ll implement a classic beginner programming problem: a guessing game. Here’s
how it works: the program will generate a random integer between 1 and 100. It
will then prompt the player to enter a guess. After a guess is entered, the
program will indicate whether the guess is too low or too high. If the guess is
correct, the game will print a congratulatory message and exit.
我们将实现一个经典的初学者编程问题:猜谜游戏。它的工作原理如下:程序将生成一个 1 到 100 之间的随机整数。然后它会提示玩家输入猜测值。输入猜测后,程序将指示猜测是否太低或太高。如果猜测正确,游戏将打印一条祝贺消息并退出。
Setting Up a New Project
设置新项目
To set up a new project, go to the projects directory that you created in
Chapter 1 and make a new project using Cargo, like so:
要设置新项目,请转到您在第 1 章中创建的项目目录并使用 Cargo 创建一个新项目,如下所示:
$ cargo new guessing_game
$ cd guessing_game
The first command, cargo new
, takes the name of the project (guessing_game
)
as the first argument. The second command changes to the new project’s
directory.
第一个命令cargo new
将项目名称 ( guessing_game
) 作为第一个参数。第二个命令更改为新项目的目录。
Look at the generated Cargo.toml file:
查看生成的Cargo.toml文件:
Filename: Cargo.toml 文件名:Cargo.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]
As you saw in Chapter 1, cargo new
generates a “Hello, world!” program for
you. Check out the src/main.rs file:
正如您在第 1 章中看到的, cargo new
生成一个“Hello, world!”为您准备的节目。查看src/main.rs文件:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
println!("Hello, world!");
}
Now let’s compile this “Hello, world!” program and run it in the same step
using the cargo run
command:
现在让我们编译这个“Hello, world!”程序并使用cargo run
命令在同一步骤中运行它:
$ 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!
The run
command comes in handy when you need to rapidly iterate on a project,
as we’ll do in this game, quickly testing each iteration before moving on to
the next one.
当您需要快速迭代项目时, run
命令会派上用场,正如我们将在本游戏中所做的那样,在继续下一个迭代之前快速测试每个迭代。
Reopen the src/main.rs file. You’ll be writing all the code in this file.
重新打开src/main.rs文件。您将在此文件中编写所有代码。
Processing a Guess 处理猜测
The first part of the guessing game program will ask for user input, process
that input, and check that the input is in the expected form. To start, we’ll
allow the player to input a guess. Enter the code in Listing 2-1 into
src/main.rs.
猜谜游戏程序的第一部分将要求用户输入,处理该输入,并检查输入是否为预期形式。首先,我们将允许玩家输入猜测。将清单 2-1 中的代码输入到src/main.rs中。
Filename: src/main.rs 文件名:src/main.rs
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
This code contains a lot of information, so let’s go over it line by line. To
obtain user input and then print the result as output, we need to bring the
io
input/output library into scope. The io
library comes from the standard
library, known as std
:
这段代码包含了很多信息,所以让我们逐行看一下。为了获取用户输入然后将结果打印为输出,我们需要将io
输入/输出库纳入范围。 io
库来自标准库,称为std
:
By default, Rust has a set of items defined in the standard library that it
brings into the scope of every program. This set is called the prelude, and
you can see everything in it in the standard library documentation.
默认情况下,Rust 在标准库中定义了一组项目,并将其引入每个程序的范围内。该集合称为前奏,您可以在标准库文档中看到其中的所有内容。
If a type you want to use isn’t in the prelude, you have to bring that type
into scope explicitly with a use
statement. Using the std::io
library
provides you with a number of useful features, including the ability to accept
user input.
如果您要使用的类型不在前奏中,则必须使用use
语句显式将该类型引入作用域。使用std::io
库为您提供了许多有用的功能,包括接受用户输入的能力。
As you saw in Chapter 1, the main
function is the entry point into the
program:
正如您在第 1 章中看到的, main
函数是程序的入口点:
The fn
syntax declares a new function; the parentheses, ()
, indicate there
are no parameters; and the curly bracket, {
, starts the body of the function.fn
语法声明一个新函数;括号()
表示没有参数;大括号{
开始函数体。
As you also learned in Chapter 1, println!
is a macro that prints a string to
the screen:
正如您在第 1 章中了解到的, println!
是一个将字符串打印到屏幕上的宏:
This code is printing a prompt stating what the game is and requesting input
from the user.
此代码打印一条提示,说明游戏是什么并请求用户输入。
Storing Values with Variables
用变量存储值
Next, we’ll create a variable to store the user input, like this:
接下来,我们将创建一个变量来存储用户输入,如下所示:
Now the program is getting interesting! There’s a lot going on in this little
line. We use the let
statement to create the variable. Here’s another example:
现在节目变得有趣了!这短短的一行里发生了很多事情。我们使用let
语句来创建变量。这是另一个例子:
let apples = 5;
This line creates a new variable named apples
and binds it to the value 5. In
Rust, variables are immutable by default, meaning once we give the variable a
value, the value won’t change. We’ll be discussing this concept in detail in
the “Variables and Mutability”
section in Chapter 3. To make a variable mutable, we add mut
before the
variable name:
这一行创建了一个名为apples
新变量,并将其绑定到值 5。在 Rust 中,默认情况下变量是不可变的,这意味着一旦我们给变量赋予了值,该值就不会改变。我们将在第 3 章的“变量和可变性”忽略部分详细讨论这个概念。为了使变量可变,我们在变量名前添加mut
:
let apples = 5; // immutable
let mut bananas = 5; // mutable
Note: The //
syntax starts a comment that continues until the end of the
line. Rust ignores everything in comments. We’ll discuss comments in more
detail in Chapter 3.
注意: //
语法开始一个注释,一直持续到该行末尾。 Rust 会忽略注释中的所有内容。我们将在第 3 章中更详细地讨论注释。
Returning to the guessing game program, you now know that let mut guess
will
introduce a mutable variable named guess
. The equal sign (=
) tells Rust we
want to bind something to the variable now. On the right of the equal sign is
the value that guess
is bound to, which is the result of calling
String::new
, a function that returns a new instance of a String
.
String
is a string type provided by the standard
library that is a growable, UTF-8 encoded bit of text.
回到猜谜游戏程序,您现在知道let mut guess
将引入一个名为guess
的可变变量。等号 ( =
) 告诉 Rust 我们现在想要将某些内容绑定到变量。等号右侧是guess
所绑定的值,它是调用String::new
结果,该函数返回String
的新实例。 String
忽略是标准库提供的字符串类型,它是可增长的 UTF-8 编码文本位。
The ::
syntax in the ::new
line indicates that new
is an associated
function of the String
type. An associated function is a function that’s
implemented on a type, in this case String
. This new
function creates a
new, empty string. You’ll find a new
function on many types because it’s a
common name for a function that makes a new value of some kind.::
::new
语法表明new
是String
类型的关联函数。关联函数是在类型(本例中为String
上实现的函数。这个new
函数创建一个新的空字符串。您会在许多类型上找到new
函数,因为它是产生某种新值的函数的通用名称。
In full, the let mut guess = String::new();
line has created a mutable
variable that is currently bound to a new, empty instance of a String
. Whew!
完整来说, let mut guess = String::new();
line 创建了一个可变变量,该变量当前绑定到String
的新空实例。哇!
Receiving User Input 接收用户输入
Recall that we included the input/output functionality from the standard
library with use std::io;
on the first line of the program. Now we’ll call
the stdin
function from the io
module, which will allow us to handle user
input:
回想一下,我们通过use std::io;
包含了标准库中的输入/输出功能。在程序的第一行。现在我们将从io
模块调用stdin
函数,这将允许我们处理用户输入:
If we hadn’t imported the io
library with use std::io;
at the beginning of
the program, we could still use the function by writing this function call as
std::io::stdin
. The stdin
function returns an instance of
std::io::Stdin
, which is a type that represents a
handle to the standard input for your terminal.
如果我们没有use std::io;
导入io
库在程序开始时,我们仍然可以通过将此函数调用编写为std::io::stdin
来使用该函数。 stdin
函数返回std::io::Stdin
的实例,它是表示终端标准输入句柄的类型。
Next, the line .read_line(&mut guess)
calls the read_line
method on the standard input handle to get input from the user.
We’re also passing &mut guess
as the argument to read_line
to tell it what
string to store the user input in. The full job of read_line
is to take
whatever the user types into standard input and append that into a string
(without overwriting its contents), so we therefore pass that string as an
argument. The string argument needs to be mutable so the method can change the
string’s content.
接下来,行.read_line(&mut guess)
调用标准输入句柄上的read_line
方法以获取用户的输入。我们还将&mut guess
作为参数传递给read_line
,告诉它将用户输入存储在哪个字符串中。 read_line
的完整工作是将用户输入到标准输入中的所有内容并将其附加到字符串中(而不覆盖其内容) ),因此我们将该字符串作为参数传递。字符串参数需要是可变的,以便该方法可以更改字符串的内容。
The &
indicates that this argument is a reference, which gives you a way to
let multiple parts of your code access one piece of data without needing to
copy that data into memory multiple times. References are a complex feature,
and one of Rust’s major advantages is how safe and easy it is to use
references. You don’t need to know a lot of those details to finish this
program. For now, all you need to know is that, like variables, references are
immutable by default. Hence, you need to write &mut guess
rather than
&guess
to make it mutable. (Chapter 4 will explain references more
thoroughly.)&
表示该参数是一个引用,它为您提供了一种让代码的多个部分访问一条数据的方法,而无需多次将该数据复制到内存中。引用是一项复杂的功能,Rust 的主要优点之一是使用引用的安全性和易用性。您不需要了解很多细节即可完成此程序。现在,您需要知道的是,与变量一样,默认情况下引用是不可变的。因此,您需要编写&mut guess
而不是&guess
来使其可变。 (第 4 章将更彻底地解释参考文献。)
Handling Potential Failure with Result
处理潜在的失败和Result
We’re still working on this line of code. We’re now discussing a third line of
text, but note that it’s still part of a single logical line of code. The next
part is this method:
我们仍在研究这行代码。我们现在正在讨论第三行文本,但请注意,它仍然是单个逻辑代码行的一部分。下一部分是这个方法:
We could have written this code as:
我们可以将这段代码写成:
io::stdin().read_line(&mut guess).expect("Failed to read line");
However, one long line is difficult to read, so it’s best to divide it. It’s
often wise to introduce a newline and other whitespace to help break up long
lines when you call a method with the .method_name()
syntax. Now let’s
discuss what this line does.
然而,一长行很难阅读,所以最好将其分开。当您使用.method_name()
语法调用方法时,引入换行符和其他空格来帮助分解长行通常是明智的做法。现在我们来讨论一下这条线的作用。
As mentioned earlier, read_line
puts whatever the user enters into the string
we pass to it, but it also returns a Result
value. Result
is an enumeration, often called an enum,
which is a type that can be in one of multiple possible states. We call each
possible state a variant.
如前所述, read_line
将用户输入的任何内容放入我们传递给它的字符串中,但它也返回一个Result
值。 Result
忽略是枚举忽略,通常称为枚举,它是一种可以处于多种可能状态之一的类型。我们将每种可能的状态称为变体。
Chapter 6 will cover enums in more detail. The purpose
of these Result
types is to encode error-handling information.
第 6 章ignore 将更详细地介绍枚举。这些Result
类型的目的是对错误处理信息进行编码。
Result
’s variants are Ok
and Err
. The Ok
variant indicates the
operation was successful, and inside Ok
is the successfully generated value.
The Err
variant means the operation failed, and Err
contains information
about how or why the operation failed.Result
的变体是Ok
和Err
。 Ok
变量表示操作成功, Ok
里面是成功生成的值。 Err
变体表示操作失败, Err
包含有关操作如何或为何失败的信息。
Values of the Result
type, like values of any type, have methods defined on
them. An instance of Result
has an expect
method
that you can call. If this instance of Result
is an Err
value, expect
will cause the program to crash and display the message that you passed as an
argument to expect
. If the read_line
method returns an Err
, it would
likely be the result of an error coming from the underlying operating system.
If this instance of Result
is an Ok
value, expect
will take the return
value that Ok
is holding and return just that value to you so you can use it.
In this case, that value is the number of bytes in the user’s input.
与任何类型的值一样, Result
类型的值也定义了方法。 Result
的实例有一个您可以调用的expect
方法ignore。如果Result
的此实例是Err
值, expect
将导致程序崩溃并显示您作为参数传递给expect
的消息。如果read_line
方法返回Err
,则可能是来自底层操作系统的错误的结果。如果Result
的这个实例是Ok
值, expect
将获取Ok
所保存的返回值并将该值返回给您,以便您可以使用它。在本例中,该值是用户输入中的字节数。
If you don’t call expect
, the program will compile, but you’ll get a warning:
如果您不调用expect
,程序将编译,但您会收到警告:
$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
warning: unused `Result` that must be used
--> src/main.rs:10:5
|
10 | io::stdin().read_line(&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(&mut guess);
| +++++++
warning: `guessing_game` (bin "guessing_game") generated 1 warning
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.59s
Rust warns that you haven’t used the Result
value returned from read_line
,
indicating that the program hasn’t handled a possible error.
Rust 警告您尚未使用从read_line
返回的Result
值,这表明程序尚未处理可能的错误。
The right way to suppress the warning is to actually write error-handling code,
but in our case we just want to crash this program when a problem occurs, so we
can use expect
. You’ll learn about recovering from errors in Chapter
9.
抑制警告的正确方法是实际编写错误处理代码,但在我们的例子中,我们只想在出现问题时使该程序崩溃,因此我们可以使用expect
。您将在第 9 章中了解如何从错误中恢复 忽略 。
Printing Values with println!
Placeholders
使用println!
打印值占位符
Aside from the closing curly bracket, there’s only one more line to discuss in
the code so far:
除了右大括号之外,到目前为止,代码中只剩下一行需要讨论:
This line prints the string that now contains the user’s input. The {}
set of
curly brackets is a placeholder: think of {}
as little crab pincers that hold
a value in place. When printing the value of a variable, the variable name can
go inside the curly brackets. When printing the result of evaluating an
expression, place empty curly brackets in the format string, then follow the
format string with a comma-separated list of expressions to print in each empty
curly bracket placeholder in the same order. Printing a variable and the result
of an expression in one call to println!
would look like this:
此行打印现在包含用户输入的字符串。大括号{}
组是一个占位符:将{}
想象成固定值的小螃蟹钳子。打印变量值时,变量名称可以放在大括号内。打印表达式求值结果时,将空大括号放在格式字符串中,然后在格式字符串后跟上以逗号分隔的表达式列表,以相同的顺序在每个空大括号占位符中打印。在一次调用println!
看起来像这样:
This code would print x = 5 and y + 2 = 12
.
此代码将打印x = 5 and y + 2 = 12
。
Testing the First Part 测试第一部分
Let’s test the first part of the guessing game. Run it using cargo run
:
让我们测试一下猜谜游戏的第一部分。使用cargo run
运行它:
$ 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
At this point, the first part of the game is done: we’re getting input from the
keyboard and then printing it.
此时,游戏的第一部分已经完成:我们从键盘获取输入,然后打印它。
Generating a Secret Number
生成一个秘密号码
Next, we need to generate a secret number that the user will try to guess. The
secret number should be different every time so the game is fun to play more
than once. We’ll use a random number between 1 and 100 so the game isn’t too
difficult. Rust doesn’t yet include random number functionality in its standard
library. However, the Rust team does provide a rand
crate with
said functionality.
接下来,我们需要生成一个用户将尝试猜测的秘密数字。每次的秘密数字应该不同,这样玩多次游戏就会很有趣。我们将使用 1 到 100 之间的随机数,这样游戏就不会太困难。 Rust 的标准库中尚未包含随机数功能。然而,Rust 团队确实提供了具有上述功能的rand
箱。
Using a Crate to Get More Functionality
使用 crate 获得更多功能
Remember that a crate is a collection of Rust source code files. The project
we’ve been building is a binary crate, which is an executable. The rand
crate is a library crate, which contains code that is intended to be used in
other programs and can’t be executed on its own.
请记住,板条箱是 Rust 源代码文件的集合。我们一直在构建的项目是一个二进制 crate ,它是一个可执行文件。 rand
crate 是一个库 crate ,其中包含旨在在其他程序中使用且不能单独执行的代码。
Cargo’s coordination of external crates is where Cargo really shines. Before we
can write code that uses rand
, we need to modify the Cargo.toml file to
include the rand
crate as a dependency. Open that file now and add the
following line to the bottom, beneath the [dependencies]
section header that
Cargo created for you. Be sure to specify rand
exactly as we have here, with
this version number, or the code examples in this tutorial may not work:
Cargo 与外部板条箱的协调是 Cargo 真正的亮点。在编写使用rand
的代码之前,我们需要修改Cargo.toml文件以包含rand
箱作为依赖项。现在打开该文件,并将以下行添加到底部,即 Cargo 为您创建的[dependencies]
部分标题下方。请务必使用此版本号完全按照我们此处的方式指定rand
,否则本教程中的代码示例可能无法工作:
Filename: Cargo.toml 文件名:Cargo.toml
[dependencies]
rand = "0.8.5"
In the Cargo.toml file, everything that follows a header is part of that
section that continues until another section starts. In [dependencies]
you
tell Cargo which external crates your project depends on and which versions of
those crates you require. In this case, we specify the rand
crate with the
semantic version specifier 0.8.5
. Cargo understands Semantic
Versioning (sometimes called SemVer), which is a
standard for writing version numbers. The specifier 0.8.5
is actually
shorthand for ^0.8.5
, which means any version that is at least 0.8.5 but
below 0.9.0.
在Cargo.toml文件中,标头后面的所有内容都是该部分的一部分,一直持续到另一个部分开始。在[dependencies]
中,您告诉 Cargo 您的项目依赖哪些外部 crate,以及您需要这些 crate 的哪些版本。在本例中,我们使用语义版本说明符0.8.5
指定rand
箱。 Cargo 理解语义版本控制忽略(有时称为SemVer ),这是编写版本号的标准。说明符0.8.5
实际上是^0.8.5
的简写,这意味着至少 0.8.5 但低于 0.9.0 的任何版本。
Cargo considers these versions to have public APIs compatible with version
0.8.5, and this specification ensures you’ll get the latest patch release that
will still compile with the code in this chapter. Any version 0.9.0 or greater
is not guaranteed to have the same API as what the following examples use.
Cargo 认为这些版本具有与 0.8.5 版本兼容的公共 API,并且此规范确保您将获得最新的补丁版本,该版本仍将使用本章中的代码进行编译。不保证任何 0.9.0 或更高版本具有与以下示例使用的 API 相同的 API。
Now, without changing any of the code, let’s build the project, as shown in
Listing 2-2.
现在,在不更改任何代码的情况下,让我们构建项目,如清单 2-2 所示。
$ 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
You may see different version numbers (but they will all be compatible with the
code, thanks to SemVer!) and different lines (depending on the operating
system), and the lines may be in a different order.
您可能会看到不同的版本号(但由于 SemVer,它们都与代码兼容!)和不同的行(取决于操作系统),并且这些行的顺序可能不同。
When we include an external dependency, Cargo fetches the latest versions of
everything that dependency needs from the registry, which is a copy of data
from Crates.io. Crates.io is where people in the Rust ecosystem
post their open source Rust projects for others to use.
当我们包含外部依赖项时,Cargo 会从注册表中获取该依赖项所需的所有内容的最新版本,该注册表是来自Crates.io的数据副本。 Crates.io 是 Rust 生态系统中的人们发布开源 Rust 项目供其他人使用的地方。
After updating the registry, Cargo checks the [dependencies]
section and
downloads any crates listed that aren’t already downloaded. In this case,
although we only listed rand
as a dependency, Cargo also grabbed other crates
that rand
depends on to work. After downloading the crates, Rust compiles
them and then compiles the project with the dependencies available.
更新注册表后,Cargo 检查[dependencies]
部分并下载列出的所有尚未下载的包。在本例中,虽然我们只将rand
列为依赖项,但 Cargo 还抓取了rand
工作所依赖的其他 crate。下载包后,Rust 会编译它们,然后使用可用的依赖项编译项目。
If you immediately run cargo build
again without making any changes, you
won’t get any output aside from the Finished
line. Cargo knows it has already
downloaded and compiled the dependencies, and you haven’t changed anything
about them in your Cargo.toml file. Cargo also knows that you haven’t changed
anything about your code, so it doesn’t recompile that either. With nothing to
do, it simply exits.
如果您立即再次运行cargo build
而不进行任何更改,则除了Finished
行之外,您将不会获得任何输出。 Cargo 知道它已经下载并编译了依赖项,并且您没有在Cargo.toml文件中更改它们的任何内容。 Cargo 还知道您没有更改代码的任何内容,因此它也不会重新编译。无事可做,它就简单地退出了。
If you open the src/main.rs file, make a trivial change, and then save it and
build again, you’ll only see two lines of output:
如果您打开src/main.rs文件,进行一些简单的更改,然后保存并再次构建,您将只会看到两行输出:
$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
These lines show that Cargo only updates the build with your tiny change to the
src/main.rs file. Your dependencies haven’t changed, so Cargo knows it can
reuse what it has already downloaded and compiled for those.
这些行表明 Cargo 仅通过对src/main.rs文件进行微小更改来更新构建。您的依赖项没有改变,因此 Cargo 知道它可以重用已经下载并编译的内容。
Ensuring Reproducible Builds with the Cargo.lock File
使用Cargo.lock文件确保可重复构建
Cargo has a mechanism that ensures you can rebuild the same artifact every time
you or anyone else builds your code: Cargo will use only the versions of the
dependencies you specified until you indicate otherwise. For example, say that
next week version 0.8.6 of the rand
crate comes out, and that version
contains an important bug fix, but it also contains a regression that will
break your code. To handle this, Rust creates the Cargo.lock file the first
time you run cargo build
, so we now have this in the guessing_game
directory.
Cargo 具有一种机制,可确保您或其他任何人每次构建代码时都可以重建相同的工件:Cargo 将仅使用您指定的依赖项版本,直到您另有指示。例如,假设下周rand
crate 的 0.8.6 版本将发布,该版本包含一个重要的错误修复,但它也包含一个会破坏您的代码的回归。为了处理这个问题,Rust 在您第一次运行cargo build
时创建了Cargo.lock文件,因此我们现在将其放置在guessing_game目录中。
When you build a project for the first time, Cargo figures out all the versions
of the dependencies that fit the criteria and then writes them to the
Cargo.lock file. When you build your project in the future, Cargo will see
that the Cargo.lock file exists and will use the versions specified there
rather than doing all the work of figuring out versions again. This lets you
have a reproducible build automatically. In other words, your project will
remain at 0.8.5 until you explicitly upgrade, thanks to the Cargo.lock file.
Because the Cargo.lock file is important for reproducible builds, it’s often
checked into source control with the rest of the code in your project.
当您第一次构建项目时,Cargo 会找出符合条件的所有依赖项版本,然后将它们写入Cargo.lock文件。当您将来构建项目时,Cargo 将看到Cargo.lock文件存在,并将使用其中指定的版本,而不是再次执行确定版本的所有工作。这可以让您自动获得可重复的构建。换句话说,在您明确升级之前,您的项目将保持在 0.8.5,这要归功于Cargo.lock文件。由于Cargo.lock文件对于可重现的构建非常重要,因此它通常会与项目中的其余代码一起检入源代码管理。
Updating a Crate to Get a New Version
更新 crate 以获取新版本
When you do want to update a crate, Cargo provides the command update
,
which will ignore the Cargo.lock file and figure out all the latest versions
that fit your specifications in Cargo.toml. Cargo will then write those
versions to the Cargo.lock file. In this case, Cargo will only look for
versions greater than 0.8.5 and less than 0.9.0. If the rand
crate has
released the two new versions 0.8.6 and 0.9.0, you would see the following if
you ran cargo update
:
当您确实想要更新 crate 时,Cargo 提供了命令update
,该命令将忽略Cargo.lock文件并找出符合您在Cargo.toml中的规范的所有最新版本。然后 Cargo 会将这些版本写入Cargo.lock文件。在这种情况下,Cargo 将仅查找大于 0.8.5 且小于 0.9.0 的版本。如果rand
crate 已经发布了两个新版本 0.8.6 和 0.9.0,那么如果您运行cargo update
您将看到以下内容:
$ cargo update
Updating crates.io index
Updating rand v0.8.5 -> v0.8.6
Cargo ignores the 0.9.0 release. At this point, you would also notice a change
in your Cargo.lock file noting that the version of the rand
crate you are
now using is 0.8.6. To use rand
version 0.9.0 or any version in the 0.9.x
series, you’d have to update the Cargo.toml file to look like this instead:
Cargo 忽略 0.9.0 版本。此时,您还会注意到Cargo.lock文件中的更改,指出您现在使用的rand
箱的版本是 0.8.6。使用rand
版本 0.9.0 或 0.9 中的任何版本。 x系列,您必须更新Cargo.toml文件,使其看起来像这样:
[dependencies]
rand = "0.9.0"
The next time you run cargo build
, Cargo will update the registry of crates
available and reevaluate your rand
requirements according to the new version
you have specified.
下次您运行cargo build
时,Cargo 将更新可用 crate 的注册表,并根据您指定的新版本重新评估您的rand
要求。
There’s a lot more to say about Cargo and its
ecosystem, which we’ll discuss in Chapter 14, but
for now, that’s all you need to know. Cargo makes it very easy to reuse
libraries, so Rustaceans are able to write smaller projects that are assembled
from a number of packages.
关于Cargoignore及其生态系统ignore还有很多要说的,我们将在第14章中讨论,但现在,这就是你需要知道的全部。 Cargo 使得重用库变得非常容易,因此 Rustaceans 能够编写由多个包组装而成的较小项目。
Generating a Random Number
生成随机数
Let’s start using rand
to generate a number to guess. The next step is to
update src/main.rs, as shown in Listing 2-3.
让我们开始使用rand
生成一个数字来猜测。下一步是更新src/main.rs ,如清单 2-3 所示。
Filename: src/main.rs 文件名:src/main.rs
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(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
First we add the line use rand::Rng;
. The Rng
trait defines methods that
random number generators implement, and this trait must be in scope for us to
use those methods. Chapter 10 will cover traits in detail.
首先我们添加行use rand::Rng;
。 Rng
特征定义了随机数生成器实现的方法,并且该特征必须在我们使用这些方法的范围内。第 10 章将详细介绍特征。
Next, we’re adding two lines in the middle. In the first line, we call the
rand::thread_rng
function that gives us the particular random number
generator we’re going to use: one that is local to the current thread of
execution and is seeded by the operating system. Then we call the gen_range
method on the random number generator. This method is defined by the Rng
trait that we brought into scope with the use rand::Rng;
statement. The
gen_range
method takes a range expression as an argument and generates a
random number in the range. The kind of range expression we’re using here takes
the form start..=end
and is inclusive on the lower and upper bounds, so we
need to specify 1..=100
to request a number between 1 and 100.
接下来,我们在中间添加两行。在第一行中,我们调用rand::thread_rng
函数,该函数为我们提供将要使用的特定随机数生成器:一个位于当前执行线程本地并由操作系统播种的随机数生成器。然后我们调用随机数生成器上的gen_range
方法。该方法由我们通过use rand::Rng;
引入范围的Rng
特征定义。陈述。 gen_range
方法采用范围表达式作为参数,并在该范围内生成一个随机数。我们在这里使用的范围表达式采用start..=end
形式,并且包含下限和上限,因此我们需要指定1..=100
来请求 1 到 100 之间的数字。
Note: You won’t just know which traits to use and which methods and functions
to call from a crate, so each crate has documentation with instructions for
using it. Another neat feature of Cargo is that running the cargo doc --open
command will build documentation provided by all your dependencies
locally and open it in your browser. If you’re interested in other
functionality in the rand
crate, for example, run cargo doc --open
and
click rand
in the sidebar on the left.
注意:您不仅知道要使用哪些特征以及要从包中调用哪些方法和函数,因此每个包都有包含使用说明的文档。 Cargo 的另一个巧妙功能是,运行cargo doc --open
命令将在本地构建所有依赖项提供的文档,并在浏览器中打开它。例如,如果您对rand
箱中的其他功能感兴趣,请运行cargo doc --open
并单击左侧边栏中的rand
。
The second new line prints the secret number. This is useful while we’re
developing the program to be able to test it, but we’ll delete it from the
final version. It’s not much of a game if the program prints the answer as soon
as it starts!
第二个新行打印秘密号码。这在我们开发程序以对其进行测试时很有用,但我们将从最终版本中删除它。如果程序一开始就打印出答案,那就不算什么游戏了!
Try running the program a few times:
尝试运行该程序几次:
$ 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
You should get different random numbers, and they should all be numbers between
1 and 100. Great job!
您应该得到不同的随机数,并且它们都应该是 1 到 100 之间的数字。干得好!
Comparing the Guess to the Secret Number
将猜测与秘密数字进行比较
Now that we have user input and a random number, we can compare them. That step
is shown in Listing 2-4. Note that this code won’t compile just yet, as we will
explain.
现在我们有了用户输入和随机数,我们可以比较它们。该步骤如清单 2-4 所示。请注意,正如我们将解释的那样,该代码还无法编译。
Filename: src/main.rs 文件名:src/main.rs
First we add another use
statement, bringing a type called
std::cmp::Ordering
into scope from the standard library. The Ordering
type
is another enum and has the variants Less
, Greater
, and Equal
. These are
the three outcomes that are possible when you compare two values.
首先,我们添加另一个use
语句,将一个名为std::cmp::Ordering
类型从标准库引入范围。 Ordering
类型是另一个枚举,具有Less
、 Greater
和Equal
变体。这是比较两个值时可能出现的三种结果。
Then we add five new lines at the bottom that use the Ordering
type. The
cmp
method compares two values and can be called on anything that can be
compared. It takes a reference to whatever you want to compare with: here it’s
comparing guess
to secret_number
. Then it returns a variant of the
Ordering
enum we brought into scope with the use
statement. We use a
match
expression to decide what to do next based on
which variant of Ordering
was returned from the call to cmp
with the values
in guess
and secret_number
.
然后我们在底部添加五个使用Ordering
类型的新行。 cmp
方法比较两个值,并且可以在任何可以比较的对象上调用。它需要引用您想要比较的任何内容:这里是将guess
与secret_number
进行比较。然后它返回我们通过use
语句引入范围的Ordering
枚举的变体。我们使用match
忽略表达式来根据从调用cmp
返回的Ordering
变体(具有guess
和secret_number
中的值)来决定下一步要做什么。
A match
expression is made up of arms. An arm consists of a pattern to
match against, and the code that should be run if the value given to match
fits that arm’s pattern. Rust takes the value given to match
and looks
through each arm’s pattern in turn. Patterns and the match
construct are
powerful Rust features: they let you express a variety of situations your code
might encounter and they make sure you handle them all. These features will be
covered in detail in Chapter 6 and Chapter 18, respectively.match
表达式由手臂组成。手臂由要匹配的模式以及在给定的match
值适合该手臂的模式时应运行的代码组成。 Rust 获取给定的值进行match
,并依次查看每个手臂的模式。模式和match
构造是强大的 Rust 功能:它们让您表达代码可能遇到的各种情况,并确保您能够处理所有情况。这些功能将分别在第 6 章和第 18 章中详细介绍。
Let’s walk through an example with the match
expression we use here. Say that
the user has guessed 50 and the randomly generated secret number this time is
38.
让我们看一下这里使用的match
表达式的示例。假设用户猜中了 50,这次随机生成的秘密数字是 38。
When the code compares 50 to 38, the cmp
method will return
Ordering::Greater
because 50 is greater than 38. The match
expression gets
the Ordering::Greater
value and starts checking each arm’s pattern. It looks
at the first arm’s pattern, Ordering::Less
, and sees that the value
Ordering::Greater
does not match Ordering::Less
, so it ignores the code in
that arm and moves to the next arm. The next arm’s pattern is
Ordering::Greater
, which does match Ordering::Greater
! The associated
code in that arm will execute and print Too big!
to the screen. The match
expression ends after the first successful match, so it won’t look at the last
arm in this scenario.
当代码比较 50 和 38 时, cmp
方法将返回Ordering::Greater
,因为 50 大于 38。 match
表达式获取Ordering::Greater
值并开始检查每个臂的模式。它查看第一个臂的模式Ordering::Less
,并发现值Ordering::Greater
与Ordering::Less
不匹配,因此它忽略该臂中的代码并移至下一个臂。下一个手臂的模式是Ordering::Greater
,它与Ordering::Greater
匹配!该手臂中的相关代码将执行并打印Too big!
到屏幕上。 match
表达式在第一次成功匹配后结束,因此在这种情况下它不会查看最后一个分支。
However, the code in Listing 2-4 won’t compile yet. Let’s try it:
但是,清单 2-4 中的代码还无法编译。我们来尝试一下:
$ cargo build
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
--> src/main.rs:22:21
|
22 | match guess.cmp(&secret_number) {
| --- ^^^^^^^^^^^^^^ expected `&String`, found `&{integer}`
| |
| arguments to this method are incorrect
|
= note: expected reference `&String`
found reference `&{integer}`
note: method defined here
--> /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/core/src/cmp.rs:836: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
The core of the error states that there are mismatched types. Rust has a
strong, static type system. However, it also has type inference. When we wrote
let mut guess = String::new()
, Rust was able to infer that guess
should be
a String
and didn’t make us write the type. The secret_number
, on the other
hand, is a number type. A few of Rust’s number types can have a value between 1
and 100: i32
, a 32-bit number; u32
, an unsigned 32-bit number; i64
, a
64-bit number; as well as others. Unless otherwise specified, Rust defaults to
an i32
, which is the type of secret_number
unless you add type information
elsewhere that would cause Rust to infer a different numerical type. The reason
for the error is that Rust cannot compare a string and a number type.
错误的核心是类型不匹配。 Rust 拥有强大的静态类型系统。然而,它也有类型推断。当我们编写let mut guess = String::new()
时,Rust 能够推断guess
应该是一个String
并且不会让我们编写类型。另一方面, secret_number
是一种数字类型。 Rust 的一些数字类型的值可以在 1 到 100 之间: i32
,一个 32 位数字; u32
,无符号 32 位数字; i64
,64 位数字;以及其他人。除非另有说明,Rust 默认为i32
,这是secret_number
的类型,除非您在其他地方添加类型信息,这会导致 Rust 推断出不同的数字类型。错误的原因是 Rust 无法比较字符串和数字类型。
Ultimately, we want to convert the String
the program reads as input into a
number type so we can compare it numerically to the secret number. We do so by
adding this line to the main
function body:
最终,我们希望将程序作为输入读取的String
转换为数字类型,以便我们可以将其与秘密数字进行数字比较。我们通过将此行添加到main
函数体来实现:
Filename: src/main.rs 文件名:src/main.rs
The line is: 该行是:
let guess: u32 = guess.trim().parse().expect("Please type a number!");
We create a variable named guess
. But wait, doesn’t the program already have
a variable named guess
? It does, but helpfully Rust allows us to shadow the
previous value of guess
with a new one. Shadowing lets us reuse the guess
variable name rather than forcing us to create two unique variables, such as
guess_str
and guess
, for example. We’ll cover this in more detail in
Chapter 3, but for now, know that this feature is
often used when you want to convert a value from one type to another type.
我们创建一个名为guess
变量。但是等等,程序不是已经有一个名为guess
变量了吗?确实如此,但 Rust 允许我们用新的猜测值来掩盖之前的guess
值,这很有帮助。阴影允许我们重用guess
变量名称,而不是强迫我们创建两个唯一的变量,例如guess_str
和guess
。我们将在第 3 章中更详细地介绍这一点。ignore,但是现在,当您想要将值从一种类型转换为另一种类型时,通常会使用此功能。
We bind this new variable to the expression guess.trim().parse()
. The guess
in the expression refers to the original guess
variable that contained the
input as a string. The trim
method on a String
instance will eliminate any
whitespace at the beginning and end, which we must do to be able to compare the
string to the u32
, which can only contain numerical data. The user must press
enter to satisfy read_line
and input their guess, which adds a
newline character to the string. For example, if the user types 5 and
presses enter, guess
looks like this: 5\n
. The \n
represents
“newline.” (On Windows, pressing enter results in a carriage return
and a newline, \r\n
.) The trim
method eliminates \n
or \r\n
, resulting
in just 5
.
我们将这个新变量绑定到表达式guess.trim().parse()
。表达式中的guess
是指包含字符串输入的原始guess
变量。 String
实例上的trim
方法将消除开头和结尾的任何空格,我们必须这样做才能将字符串与u32
进行比较,u32 只能包含数字数据。用户必须按 enter 满足read_line
并输入他们的猜测,这会向字符串添加换行符。例如,如果用户输入 5 并按 enter , guess
看起来像这样: 5\n
。 \n
代表“换行符”。 (在 Windows 上,按 enter 结果是一个回车符和一个换行符\r\n
。) trim
方法消除了\n
或\r\n
,结果只是5
。
The parse
method on strings converts a string to
another type. Here, we use it to convert from a string to a number. We need to
tell Rust the exact number type we want by using let guess: u32
. The colon
(:
) after guess
tells Rust we’ll annotate the variable’s type. Rust has a
few built-in number types; the u32
seen here is an unsigned, 32-bit integer.
It’s a good default choice for a small positive number. You’ll learn about
other number types in Chapter 3.
字符串的parse
方法ignore 将字符串转换为另一种类型。在这里,我们使用它从字符串转换为数字。我们需要使用let guess: u32
告诉 Rust 我们想要的确切数字类型。 guess
后的冒号 ( :
告诉 Rust 我们将注释变量的类型。 Rust 有一些内置的数字类型;这里看到的u32
是一个无符号的 32 位整数。对于较小的正数,这是一个很好的默认选择。您将在第 3 章中了解其他数字类型。
Additionally, the u32
annotation in this example program and the comparison
with secret_number
means Rust will infer that secret_number
should be a
u32
as well. So now the comparison will be between two values of the same
type!
此外,此示例程序中的u32
注释以及与secret_number
的比较意味着 Rust 将推断secret_number
也应该是u32
。所以现在比较将在相同类型的两个值之间进行!
The parse
method will only work on characters that can logically be converted
into numbers and so can easily cause errors. If, for example, the string
contained A👍%
, there would be no way to convert that to a number. Because it
might fail, the parse
method returns a Result
type, much as the read_line
method does (discussed earlier in “Handling Potential Failure with
Result
”). We’ll treat
this Result
the same way by using the expect
method again. If parse
returns an Err
Result
variant because it couldn’t create a number from the
string, the expect
call will crash the game and print the message we give it.
If parse
can successfully convert the string to a number, it will return the
Ok
variant of Result
, and expect
will return the number that we want from
the Ok
value.parse
方法仅适用于逻辑上可以转换为数字的字符,因此很容易导致错误。例如,如果字符串包含A👍%
,则无法将其转换为数字。因为它可能会失败,所以parse
方法返回Result
类型,就像read_line
方法所做的那样(前面在“使用结果处理潜在Result
”忽略中讨论过)。我们将再次使用expect
方法以相同的方式处理此Result
。如果parse
因为无法从字符串创建数字而返回Err
Result
变体,则expect
调用将使游戏崩溃并打印我们提供的消息。如果parse
可以成功地将字符串转换为数字,它将返回Result
的Ok
变体,并且expect
将从Ok
值中返回我们想要的数字。
Let’s run the program now:
现在让我们运行该程序:
$ 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!
Nice! Even though spaces were added before the guess, the program still figured
out that the user guessed 76. Run the program a few times to verify the
different behavior with different kinds of input: guess the number correctly,
guess a number that is too high, and guess a number that is too low.
好的!即使在猜测之前添加了空格,程序仍然发现用户猜测了 76。运行程序几次以验证不同类型输入的不同行为:猜对数字,猜数字太高,并猜测一个太低的数字。
We have most of the game working now, but the user can make only one guess.
Let’s change that by adding a loop!
现在游戏的大部分功能都可以运行,但用户只能做出一种猜测。让我们通过添加一个循环来改变它!
Allowing Multiple Guesses with Looping
允许通过循环进行多次猜测
The loop
keyword creates an infinite loop. We’ll add a loop to give users
more chances at guessing the number:loop
关键字创建无限循环。我们将添加一个循环,让用户有更多机会猜测数字:
Filename: src/main.rs 文件名:src/main.rs
As you can see, we’ve moved everything from the guess input prompt onward into
a loop. Be sure to indent the lines inside the loop another four spaces each
and run the program again. The program will now ask for another guess forever,
which actually introduces a new problem. It doesn’t seem like the user can quit!
正如您所看到的,我们已将猜测输入提示中的所有内容移至循环中。确保将循环内的行每行缩进四个空格,然后再次运行程序。程序现在将永远要求另一个猜测,这实际上引入了一个新问题。看来用户不能退出啊!
The user could always interrupt the program by using the keyboard shortcut
ctrl-c. But there’s another way to escape this insatiable
monster, as mentioned in the parse
discussion in “Comparing the Guess to the
Secret Number”: if
the user enters a non-number answer, the program will crash. We can take
advantage of that to allow the user to quit, as shown here:
用户始终可以使用键盘快捷键中断程序 ctrl - c 。但还有另一种方法可以逃避这个贪得无厌的怪物,正如“比较猜测与秘密数字”中的parse
讨论中提到的忽略:如果用户输入非数字答案,程序将崩溃。我们可以利用这一点来允许用户退出,如下所示:
$ 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
Typing quit
will quit the game, but as you’ll notice, so will entering any
other non-number input. This is suboptimal, to say the least; we want the game
to also stop when the correct number is guessed.
输入quit
将退出游戏,但您会注意到,输入任何其他非数字输入也会退出游戏。至少可以说,这是次优的;我们希望当猜到正确的数字时游戏也停止。
Quitting After a Correct Guess
猜测正确后退出
Let’s program the game to quit when the user wins by adding a break
statement:
让我们通过添加一个break
语句来编程游戏以在用户获胜时退出:
Filename: src/main.rs 文件名:src/main.rs
Adding the break
line after You win!
makes the program exit the loop when
the user guesses the secret number correctly. Exiting the loop also means
exiting the program, because the loop is the last part of main
.You win!
后添加break
!当用户正确猜出秘密数字时,使程序退出循环。退出循环也意味着退出程序,因为循环是main
的最后一部分。
Handling Invalid Input 处理无效输入
To further refine the game’s behavior, rather than crashing the program when
the user inputs a non-number, let’s make the game ignore a non-number so the
user can continue guessing. We can do that by altering the line where guess
is converted from a String
to a u32
, as shown in Listing 2-5.
为了进一步完善游戏的行为,让游戏忽略非数字以便用户可以继续猜测,而不是在用户输入非数字时使程序崩溃。我们可以通过更改将guess
从String
转换为u32
行来实现这一点,如清单 2-5 所示。
Filename: src/main.rs 文件名:src/main.rs
We switch from an expect
call to a match
expression to move from crashing
on an error to handling the error. Remember that parse
returns a Result
type and Result
is an enum that has the variants Ok
and Err
. We’re using
a match
expression here, as we did with the Ordering
result of the cmp
method.
我们从expect
调用切换到match
表达式,以从因错误而崩溃转变为处理错误。请记住, parse
返回Result
类型,并且Result
是一个具有变体Ok
和Err
枚举。我们在这里使用match
表达式,就像我们对cmp
方法的Ordering
结果所做的那样。
If parse
is able to successfully turn the string into a number, it will
return an Ok
value that contains the resultant number. That Ok
value will
match the first arm’s pattern, and the match
expression will just return the
num
value that parse
produced and put inside the Ok
value. That number
will end up right where we want it in the new guess
variable we’re creating.
如果parse
能够成功将字符串转换为数字,它将返回包含结果数字的Ok
值。该Ok
值将与第一个臂的模式匹配,并且match
表达式将仅返回parse
生成的num
值并将其放入Ok
值中。该数字最终将位于我们正在创建的新guess
变量中所需的位置。
If parse
is not able to turn the string into a number, it will return an
Err
value that contains more information about the error. The Err
value
does not match the Ok(num)
pattern in the first match
arm, but it does
match the Err(_)
pattern in the second arm. The underscore, _
, is a
catchall value; in this example, we’re saying we want to match all Err
values, no matter what information they have inside them. So the program will
execute the second arm’s code, continue
, which tells the program to go to the
next iteration of the loop
and ask for another guess. So, effectively, the
program ignores all errors that parse
might encounter!
如果parse
无法将字符串转换为数字,它将返回一个Err
值,其中包含有关错误的更多信息。 Err
值与第一个match
臂中的Ok(num)
模式不匹配,但与第二个匹配臂中的Err(_)
模式匹配。下划线_
是一个包罗万象的值;在这个例子中,我们说我们想要匹配所有Err
值,无论它们里面有什么信息。因此,程序将执行第二个分支的代码continue
,它告诉程序进入loop
的下一次迭代并要求进行另一次猜测。因此,实际上,程序会忽略parse
可能遇到的所有错误!
Now everything in the program should work as expected. Let’s try it:
现在程序中的所有内容都应该按预期工作。我们来尝试一下:
$ 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!
Awesome! With one tiny final tweak, we will finish the guessing game. Recall
that the program is still printing the secret number. That worked well for
testing, but it ruins the game. Let’s delete the println!
that outputs the
secret number. Listing 2-6 shows the final code.
惊人的!通过最后的一点小小的调整,我们将完成这个猜谜游戏。回想一下,程序仍在打印秘密数字。这对于测试来说效果很好,但它却破坏了游戏。让我们删除println!
输出秘密数字。清单 2-6 显示了最终的代码。
Filename: src/main.rs 文件名:src/main.rs
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(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
At this point, you’ve successfully built the guessing game. Congratulations!
至此,您已经成功构建了猜谜游戏。恭喜!
Summary 概括
This project was a hands-on way to introduce you to many new Rust concepts:
let
, match
, functions, the use of external crates, and more. In the next
few chapters, you’ll learn about these concepts in more detail. Chapter 3
covers concepts that most programming languages have, such as variables, data
types, and functions, and shows how to use them in Rust. Chapter 4 explores
ownership, a feature that makes Rust different from other languages. Chapter 5
discusses structs and method syntax, and Chapter 6 explains how enums work.
这个项目是向您介绍许多新的 Rust 概念的实践方式: let
、 match
、函数、外部板条箱的使用等等。在接下来的几章中,您将更详细地了解这些概念。第 3 章涵盖了大多数编程语言所具有的概念,例如变量、数据类型和函数,并展示了如何在 Rust 中使用它们。第 4 章探讨了所有权,这是 Rust 与其他语言不同的一个特性。第 5 章讨论结构体和方法语法,第 6 章解释枚举的工作原理。
Common Programming Concepts
常见的编程概念
This chapter covers concepts that appear in almost every programming language
and how they work in Rust. Many programming languages have much in common at
their core. None of the concepts presented in this chapter are unique to Rust,
but we’ll discuss them in the context of Rust and explain the conventions
around using these concepts.
本章涵盖了几乎所有编程语言中出现的概念以及它们在 Rust 中的工作原理。许多编程语言的核心都有很多共同点。本章中提出的概念都不是 Rust 所独有的,但我们将在 Rust 的背景下讨论它们,并解释使用这些概念的约定。
Specifically, you’ll learn about variables, basic types, functions, comments,
and control flow. These foundations will be in every Rust program, and learning
them early will give you a strong core to start from.
具体来说,您将了解变量、基本类型、函数、注释和控制流。这些基础知识将存在于每个 Rust 程序中,尽早学习它们将为您提供强大的核心。
Keywords 关键词
The Rust language has a set of keywords that are reserved for use by the
language only, much as in other languages. Keep in mind that you cannot use
these words as names of variables or functions. Most of the keywords have
special meanings, and you’ll be using them to do various tasks in your Rust
programs; a few have no current functionality associated with them but have
been reserved for functionality that might be added to Rust in the future. You
can find a list of the keywords in Appendix A.
Rust 语言有一组保留仅供该语言使用的关键字,就像其他语言一样。请记住,您不能使用这些单词作为变量或函数的名称。大多数关键字都有特殊含义,您将使用它们在 Rust 程序中执行各种任务;一些当前没有与之相关的功能,但已为将来可能添加到 Rust 的功能保留。您可以在附录 Aignore中找到关键字列表。
Variables and Mutability 变量和可变性
As mentioned in the “Storing Values with
Variables” section, by default,
variables are immutable. This is one of many nudges Rust gives you to write
your code in a way that takes advantage of the safety and easy concurrency that
Rust offers. However, you still have the option to make your variables mutable.
Let’s explore how and why Rust encourages you to favor immutability and why
sometimes you might want to opt out.
正如“用变量存储值”忽略部分中提到的,默认情况下,变量是不可变的。这是 Rust 为您提供的众多推动力之一,让您能够利用 Rust 提供的安全性和简单的并发性来编写代码。但是,您仍然可以选择使变量可变。让我们探讨 Rust 如何以及为什么鼓励您支持不变性,以及为什么有时您可能想要选择退出。
When a variable is immutable, once a value is bound to a name, you can’t change
that value. To illustrate this, generate a new project called variables in
your projects directory by using cargo new variables
.
当变量是不可变的时,一旦将值绑定到名称,就无法更改该值。为了说明这一点,请使用cargo new variables
在项目目录中生成一个名为Variables的新项目。
Then, in your new variables directory, open src/main.rs and replace its
code with the following code, which won’t compile just yet:
然后,在新的变量目录中,打开src/main.rs并将其代码替换为以下代码,该代码目前还无法编译:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
Save and run the program using cargo run
. You should receive an error message
regarding an immutability error, as shown in this output:
使用cargo run
保存并运行程序。您应该收到一条有关不变性错误的错误消息,如以下输出所示:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| -
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
3 | println!("The value of x is: {x}");
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` (bin "variables") due to 1 previous error
This example shows how the compiler helps you find errors in your programs.
Compiler errors can be frustrating, but really they only mean your program
isn’t safely doing what you want it to do yet; they do not mean that you’re
not a good programmer! Experienced Rustaceans still get compiler errors.
此示例显示编译器如何帮助您查找程序中的错误。编译器错误可能会令人沮丧,但实际上它们仅意味着您的程序尚未安全地执行您希望它执行的操作;它们并不意味着您不是一个好的程序员!经验丰富的 Rustaceans 仍然会遇到编译器错误。
You received the error message cannot assign twice to immutable variable `x`
because you tried to assign a second value to the immutable x
variable.
您收到错误消息cannot assign twice to immutable variable `x`
因为您尝试为不可变x
变量分配第二个值。
It’s important that we get compile-time errors when we attempt to change a
value that’s designated as immutable because this very situation can lead to
bugs. If one part of our code operates on the assumption that a value will
never change and another part of our code changes that value, it’s possible
that the first part of the code won’t do what it was designed to do. The cause
of this kind of bug can be difficult to track down after the fact, especially
when the second piece of code changes the value only sometimes. The Rust
compiler guarantees that when you state that a value won’t change, it really
won’t change, so you don’t have to keep track of it yourself. Your code is thus
easier to reason through.
当我们尝试更改指定为不可变的值时,我们会遇到编译时错误,这一点很重要,因为这种情况可能会导致错误。如果我们的代码的一部分在假设值永远不会改变的情况下运行,而代码的另一部分更改了该值,则代码的第一部分可能不会执行其设计目的。事后很难追查这种错误的原因,尤其是当第二段代码有时只更改值时。 Rust 编译器保证当你声明一个值不会改变时,它确实不会改变,所以你不必自己跟踪它。因此,您的代码更容易推理。
But mutability can be very useful, and can make code more convenient to write.
Although variables are immutable by default, you can make them mutable by
adding mut
in front of the variable name as you did in Chapter
2. Adding mut
also conveys
intent to future readers of the code by indicating that other parts of the code
will be changing this variable’s value.
但可变性可能非常有用,并且可以使代码更方便编写。尽管默认情况下变量是不可变的,但您可以通过在变量名前面添加mut
来使它们可变,就像在第 2 章中所做的ignore 一样。添加mut
还通过指示代码的其他部分将更改此变量的值来向代码的未来读者传达意图。
For example, let’s change src/main.rs to the following:
例如,我们将src/main.rs更改为以下内容:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
When we run the program now, we get this:
当我们现在运行该程序时,我们得到:
$ 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
We’re allowed to change the value bound to x
from 5
to 6
when mut
is
used. Ultimately, deciding whether to use mutability or not is up to you and
depends on what you think is clearest in that particular situation.
当使用mut
时,我们可以将绑定到x
的值从5
更改为6
。最终,决定是否使用可变性取决于您,并且取决于您认为在特定情况下最清楚的内容。
Constants 常数
Like immutable variables, constants are values that are bound to a name and
are not allowed to change, but there are a few differences between constants
and variables.
与不可变变量一样,常量是绑定到名称且不允许更改的值,但常量和变量之间存在一些差异。
First, you aren’t allowed to use mut
with constants. Constants aren’t just
immutable by default—they’re always immutable. You declare constants using the
const
keyword instead of the let
keyword, and the type of the value must
be annotated. We’ll cover types and type annotations in the next section,
“Data Types”, so don’t worry about the details
right now. Just know that you must always annotate the type.
首先,不允许将mut
与常量一起使用。常量不仅在默认情况下是不可变的,而且始终是不可变的。使用const
关键字而不是let
关键字声明常量,并且必须注释值的类型。我们将在下一节“数据类型”中介绍类型和类型注释,所以现在不用担心细节。只需知道您必须始终注释类型即可。
Constants can be declared in any scope, including the global scope, which makes
them useful for values that many parts of code need to know about.
常量可以在任何范围内声明,包括全局范围,这使得它们对于代码的许多部分需要了解的值非常有用。
The last difference is that constants may be set only to a constant expression,
not the result of a value that could only be computed at runtime.
最后一个区别是常量只能设置为常量表达式,而不是只能在运行时计算的值的结果。
Here’s an example of a constant declaration:
这是常量声明的示例:
The constant’s name is THREE_HOURS_IN_SECONDS
and its value is set to the
result of multiplying 60 (the number of seconds in a minute) by 60 (the number
of minutes in an hour) by 3 (the number of hours we want to count in this
program). Rust’s naming convention for constants is to use all uppercase with
underscores between words. The compiler is able to evaluate a limited set of
operations at compile time, which lets us choose to write out this value in a
way that’s easier to understand and verify, rather than setting this constant
to the value 10,800. See the Rust Reference’s section on constant
evaluation for more information on what operations can be used
when declaring constants.
该常量的名称为THREE_HOURS_IN_SECONDS
,其值设置为 60(一分钟的秒数)乘以 60(一小时的分钟数)乘以 3(我们要在此程序中计算的小时数) )。 Rust 的常量命名约定是全部大写,单词之间使用下划线。编译器能够在编译时评估一组有限的操作,这让我们可以选择以更容易理解和验证的方式写出该值,而不是将此常量设置为值 10,800。有关声明常量时可以使用哪些操作的更多信息,请参阅Rust 参考中有关常量求值的部分。
Constants are valid for the entire time a program runs, within the scope in
which they were declared. This property makes constants useful for values in
your application domain that multiple parts of the program might need to know
about, such as the maximum number of points any player of a game is allowed to
earn, or the speed of light.
常量在程序运行的整个时间内(在声明它们的范围内)有效。此属性使常量对于程序的多个部分可能需要了解的应用程序域中的值非常有用,例如允许游戏玩家获得的最大分数或光速。
Naming hardcoded values used throughout your program as constants is useful in
conveying the meaning of that value to future maintainers of the code. It also
helps to have only one place in your code you would need to change if the
hardcoded value needed to be updated in the future.
将整个程序中使用的硬编码值命名为常量有助于将该值的含义传达给未来的代码维护者。如果将来需要更新硬编码值,那么在代码中只需要更改一个位置也很有帮助。
Shadowing 影子
As you saw in the guessing game tutorial in Chapter
2, you can declare a
new variable with the same name as a previous variable. Rustaceans say that the
first variable is shadowed by the second, which means that the second
variable is what the compiler will see when you use the name of the variable.
In effect, the second variable overshadows the first, taking any uses of the
variable name to itself until either it itself is shadowed or the scope ends.
We can shadow a variable by using the same variable’s name and repeating the
use of the let
keyword as follows:
正如您在第 2 章中的猜谜游戏教程中看到的ignore,您可以声明一个与先前变量同名的新变量。 Rustaceans 说第一个变量被第二个变量遮蔽,这意味着当您使用变量名称时编译器将看到第二个变量。实际上,第二个变量掩盖了第一个变量,将变量名称的任何使用都归为自身,直到它本身被掩盖或作用域结束。我们可以通过使用相同的变量名称并重复使用let
关键字来隐藏变量,如下所示:
Filename: src/main.rs 文件名:src/main.rs
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}");
}
This program first binds x
to a value of 5
. Then it creates a new variable
x
by repeating let x =
, taking the original value and adding 1
so the
value of x
is then 6
. Then, within an inner scope created with the curly
brackets, the third let
statement also shadows x
and creates a new
variable, multiplying the previous value by 2
to give x
a value of 12
.
When that scope is over, the inner shadowing ends and x
returns to being 6
.
When we run this program, it will output the following:
该程序首先将x
绑定到值5
。然后,它通过重复let x =
来创建一个新变量x
,取原始值并加1
,因此x
的值为6
。然后,在使用大括号创建的内部作用域内,第三个let
语句也隐藏x
并创建一个新变量,将先前的值乘以2
以使x
的值为12
。当该范围结束时,内部阴影结束并且x
返回到6
。当我们运行这个程序时,它会输出以下内容:
$ 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
Shadowing is different from marking a variable as mut
because we’ll get a
compile-time error if we accidentally try to reassign to this variable without
using the let
keyword. By using let
, we can perform a few transformations
on a value but have the variable be immutable after those transformations have
been completed.
隐藏与将变量标记为mut
不同,因为如果我们不小心尝试在不使用let
关键字的情况下重新分配给该变量,我们将收到编译时错误。通过使用let
,我们可以对一个值执行一些转换,但在这些转换完成后变量是不可变的。
The other difference between mut
and shadowing is that because we’re
effectively creating a new variable when we use the let
keyword again, we can
change the type of the value but reuse the same name. For example, say our
program asks a user to show how many spaces they want between some text by
inputting space characters, and then we want to store that input as a number:mut
和 Shadowing 之间的另一个区别是,因为当我们再次使用let
关键字时,我们实际上是在创建一个新变量,所以我们可以更改值的类型,但重复使用相同的名称。例如,假设我们的程序要求用户通过输入空格字符来显示他们想要在某些文本之间有多少个空格,然后我们希望将该输入存储为数字:
The first spaces
variable is a string type and the second spaces
variable
is a number type. Shadowing thus spares us from having to come up with
different names, such as spaces_str
and spaces_num
; instead, we can reuse
the simpler spaces
name. However, if we try to use mut
for this, as shown
here, we’ll get a compile-time error:
第一个spaces
变量是字符串类型,第二个spaces
变量是数字类型。因此,阴影使我们不必想出不同的名称,例如spaces_str
和spaces_num
;相反,我们可以重复使用更简单的spaces
名称。但是,如果我们尝试使用mut
来实现此目的,如下所示,我们将收到编译时错误:
The error says we’re not allowed to mutate a variable’s type:
该错误表明我们不允许改变变量的类型:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0308]: mismatched types
--> src/main.rs:3:14
|
2 | let mut spaces = " ";
| ----- expected due to this value
3 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected `&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
Now that we’ve explored how variables work, let’s look at more data types they
can have.
现在我们已经探讨了变量的工作原理,让我们看看它们可以拥有的更多数据类型。
Data Types 数据类型
Every value in Rust is of a certain data type, which tells Rust what kind of
data is being specified so it knows how to work with that data. We’ll look at
two data type subsets: scalar and compound.
Rust 中的每个值都有特定的数据类型,它告诉 Rust 正在指定哪种数据,以便它知道如何处理该数据。我们将研究两种数据类型子集:标量和复合。
Keep in mind that Rust is a statically typed language, which means that it
must know the types of all variables at compile time. The compiler can usually
infer what type we want to use based on the value and how we use it. In cases
when many types are possible, such as when we converted a String
to a numeric
type using parse
in the “Comparing the Guess to the Secret
Number” section in
Chapter 2, we must add a type annotation, like this:
请记住,Rust 是一种静态类型语言,这意味着它必须在编译时知道所有变量的类型。编译器通常可以根据值以及我们如何使用它来推断我们想要使用什么类型。如果可能有多种类型,例如当我们在第 2 章的“比较猜测与秘密数字”忽略部分中使用parse
将String
转换为数字类型时,我们必须添加类型注释,如下所示:
If we don’t add the : u32
type annotation shown in the preceding code, Rust
will display the following error, which means the compiler needs more
information from us to know which type we want to use:
如果我们不添加前面代码中所示的: u32
类型注释,Rust 将显示以下错误,这意味着编译器需要我们提供更多信息才能知道我们要使用哪种类型:
$ cargo build
Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)
error[E0284]: type annotations needed
--> src/main.rs:2:9
|
2 | let guess = "42".parse().expect("Not a number!");
| ^^^^^ ----- type must be known at this point
|
= note: cannot satisfy `<_ as FromStr>::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
You’ll see different type annotations for other data types.
您将看到其他数据类型的不同类型注释。
Scalar Types 标量类型
A scalar type represents a single value. Rust has four primary scalar types:
integers, floating-point numbers, Booleans, and characters. You may recognize
these from other programming languages. Let’s jump into how they work in Rust.
标量类型表示单个值。 Rust 有四种主要标量类型:整数、浮点数、布尔值和字符。您可能会从其他编程语言中识别出这些。让我们来看看它们在 Rust 中是如何工作的。
Integer Types 整数类型
An integer is a number without a fractional component. We used one integer
type in Chapter 2, the u32
type. This type declaration indicates that the
value it’s associated with should be an unsigned integer (signed integer types
start with i
instead of u
) that takes up 32 bits of space. Table 3-1 shows
the built-in integer types in Rust. We can use any of these variants to declare
the type of an integer value.
整数是没有小数部分的数字。我们在第 2 章中使用了一种整数类型,即u32
类型。此类型声明指示与其关联的值应该是占用 32 位空间的无符号整数(有符号整数类型以i
而不是u
开头)。表 3-1 显示了 Rust 中的内置整数类型。我们可以使用任何这些变体来声明整数值的类型。
Length 长度 | Signed 签名 | Unsigned 未签名 |
---|---|---|
8-bit 8位 | i8 | u8 |
16-bit 16位 | i16 | u16 |
32-bit 32位 | i32 | u32 |
64-bit 64位 | i64 | u64 |
128-bit 128位 | i128 | u128 |
arch 拱 | isize | usize |
Each variant can be either signed or unsigned and has an explicit size.
Signed and unsigned refer to whether it’s possible for the number to be
negative—in other words, whether the number needs to have a sign with it
(signed) or whether it will only ever be positive and can therefore be
represented without a sign (unsigned). It’s like writing numbers on paper: when
the sign matters, a number is shown with a plus sign or a minus sign; however,
when it’s safe to assume the number is positive, it’s shown with no sign.
Signed numbers are stored using two’s complement representation.
每个变体可以是有符号的或无符号的,并且具有明确的大小。有符号和无符号是指数字是否可能为负数,换句话说,数字是否需要带有符号(有符号),或者它是否只能为正数,因此可以在没有符号的情况下表示(无符号) )。这就像在纸上写数字:当符号重要时,数字会显示加号或减号;当符号重要时,数字会显示为加号或减号;但是,当可以安全地假设该数字为正数时,它会不显示任何符号。有符号数使用二进制补码忽略表示法来存储。
Each signed variant can store numbers from -(2n - 1) to 2n -
1 - 1 inclusive, where n is the number of bits that variant uses. So an
i8
can store numbers from -(27) to 27 - 1, which equals
-128 to 127. Unsigned variants can store numbers from 0 to 2n - 1,
so a u8
can store numbers from 0 to 28 - 1, which equals 0 to 255.
每个有符号变体可以存储从 -(2 n - 1 ) 到 2 n - 1 - 1 (含)的数字,其中n是变体使用的位数。因此i8
可以存储从 -(2 7 ) 到 2 7 - 1 的数字,等于 -128 到 127。无符号变体可以存储从 0 到 2 n - 1 的数字,因此u8
可以存储从 0 到 2 8 - 的数字1,等于 0 到 255。
Additionally, the isize
and usize
types depend on the architecture of the
computer your program is running on, which is denoted in the table as “arch”:
64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit
architecture.
此外, isize
和usize
类型取决于程序运行所在计算机的体系结构,在表中表示为“arch”:如果使用 64 位体系结构,则为 64 位;如果使用 64 位体系结构,则为 32 位在 32 位架构上。
You can write integer literals in any of the forms shown in Table 3-2. Note
that number literals that can be multiple numeric types allow a type suffix,
such as 57u8
, to designate the type. Number literals can also use _
as a
visual separator to make the number easier to read, such as 1_000
, which will
have the same value as if you had specified 1000
.
您可以采用表 3-2 中所示的任何形式编写整数文字。请注意,可以是多个数字类型的数字文字允许使用类型后缀(例如57u8
)来指定类型。数字文字还可以使用_
作为视觉分隔符,以使数字更易于阅读,例如1_000
,它的值与您指定的1000
相同。
Number literals 数字字面量 | Example 例子 |
---|---|
Decimal 十进制 | 98_222 |
Hex 十六进制 | 0xff |
Octal 八进制 | 0o77 |
Binary 二进制 | 0b1111_0000 |
Byte (u8 only)字节(仅限 u8 ) | b'A' |
So how do you know which type of integer to use? If you’re unsure, Rust’s
defaults are generally good places to start: integer types default to i32
.
The primary situation in which you’d use isize
or usize
is when indexing
some sort of collection.
那么你如何知道要使用哪种类型的整数呢?如果您不确定,Rust 的默认值通常是一个不错的起点:整数类型默认为i32
。使用isize
或usize
的主要情况是对某种集合建立索引时。
Integer Overflow 整数溢出
Let’s say you have a variable of type u8
that can hold values between 0 and
255. If you try to change the variable to a value outside that range, such as
256, integer overflow will occur, which can result in one of two behaviors.
When you’re compiling in debug mode, Rust includes checks for integer overflow
that cause your program to panic at runtime if this behavior occurs. Rust
uses the term panicking when a program exits with an error; we’ll discuss
panics in more depth in the “Unrecoverable Errors with
panic!
” section in Chapter
9.
假设您有一个u8
类型的变量,它可以保存 0 到 255 之间的值。如果您尝试将该变量更改为该范围之外的值(例如 256),则会发生整数溢出,这可能会导致以下两种行为之一。当您在调试模式下进行编译时,Rust 会检查整数溢出,如果发生这种行为,则会导致程序在运行时出现恐慌。当程序因错误退出时,Rust 使用术语“恐慌” 。我们将在“不可恢复的恐慌错误panic!
中更深入地讨论恐慌。 ”忽略第 9 章中的部分。
When you’re compiling in release mode with the --release
flag, Rust does
not include checks for integer overflow that cause panics. Instead, if
overflow occurs, Rust performs two’s complement wrapping. In short, values
greater than the maximum value the type can hold “wrap around” to the minimum
of the values the type can hold. In the case of a u8
, the value 256 becomes
0, the value 257 becomes 1, and so on. The program won’t panic, but the
variable will have a value that probably isn’t what you were expecting it to
have. Relying on integer overflow’s wrapping behavior is considered an error.
当您使用--release
标志在发布模式下进行编译时,Rust不包括对导致恐慌的整数溢出的检查。相反,如果发生溢出,Rust 会执行补码换行。简而言之,大于该类型可以容纳的最大值的值“环绕”到该类型可以容纳的最小值。在u8
的情况下,值256变为0,值257变为1,依此类推。程序不会出现恐慌,但变量的值可能不是您期望的值。依赖整数溢出的包装行为被视为错误。
To explicitly handle the possibility of overflow, you can use these families
of methods provided by the standard library for primitive numeric types:
要显式处理溢出的可能性,您可以使用标准库为原始数字类型提供的以下一系列方法:
- Wrap in all modes with the
wrapping_*
methods, such aswrapping_add
.
使用wrapping_*
方法包装所有模式,例如wrapping_add
。 - Return the
None
value if there is overflow with thechecked_*
methods.
如果checked_*
方法存在溢出,则返回None
值。 - Return the value and a boolean indicating whether there was overflow with
the
overflowing_*
methods.
返回值和一个布尔值,指示overflowing_*
方法是否存在溢出。 - Saturate at the value’s minimum or maximum values with the
saturating_*
methods.
使用saturating_*
方法在值的最小值或最大值处饱和。
Floating-Point Types 浮点类型
Rust also has two primitive types for floating-point numbers, which are
numbers with decimal points. Rust’s floating-point types are f32
and f64
,
which are 32 bits and 64 bits in size, respectively. The default type is f64
because on modern CPUs, it’s roughly the same speed as f32
but is capable of
more precision. All floating-point types are signed.
Rust 还有两种浮点数的原始类型,即带小数点的数字。 Rust 的浮点类型是f32
和f64
,它们的大小分别是 32 位和 64 位。默认类型是f64
因为在现代 CPU 上,它的速度与f32
大致相同,但精度更高。所有浮点类型都有符号。
Here’s an example that shows floating-point numbers in action:
下面是一个显示浮点数实际操作的示例:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}
Floating-point numbers are represented according to the IEEE-754 standard. The
f32
type is a single-precision float, and f64
has double precision.
浮点数根据 IEEE-754 标准表示。 f32
类型是单精度浮点数, f64
是双精度。
Numeric Operations 数值运算
Rust supports the basic mathematical operations you’d expect for all the number
types: addition, subtraction, multiplication, division, and remainder. Integer
division truncates toward zero to the nearest integer. The following code shows
how you’d use each numeric operation in a let
statement:
Rust 支持您期望的所有数字类型的基本数学运算:加法、减法、乘法、除法和余数。整数除法将零截断为最接近的整数。以下代码显示了如何在let
语句中使用每个数字运算:
Filename: src/main.rs 文件名:src/main.rs
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; // Results in -1
// remainder
let remainder = 43 % 5;
}
Each expression in these statements uses a mathematical operator and evaluates
to a single value, which is then bound to a variable. Appendix
B contains a list of all operators that Rust
provides.
这些语句中的每个表达式都使用数学运算符并计算为单个值,然后将其绑定到变量。附录 B忽略包含 Rust 提供的所有运算符的列表。
The Boolean Type 布尔类型
As in most other programming languages, a Boolean type in Rust has two possible
values: true
and false
. Booleans are one byte in size. The Boolean type in
Rust is specified using bool
. For example:
与大多数其他编程语言一样,Rust 中的布尔类型有两个可能的值: true
和false
。布尔值的大小为一字节。 Rust 中的布尔类型是使用bool
指定的。例如:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let t = true;
let f: bool = false; // with explicit type annotation
}
The main way to use Boolean values is through conditionals, such as an if
expression. We’ll cover how if
expressions work in Rust in the “Control
Flow” section.
使用布尔值的主要方法是通过条件,例如if
表达式。我们将在“控制流”忽略部分介绍if
表达式在 Rust 中如何工作。
The Character Type 角色类型
Rust’s char
type is the language’s most primitive alphabetic type. Here are
some examples of declaring char
values:
Rust 的char
类型是该语言最原始的字母类型。以下是声明char
值的一些示例:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let c = 'z';
let z: char = 'ℤ'; // with explicit type annotation
let heart_eyed_cat = '😻';
}
Note that we specify char
literals with single quotes, as opposed to string
literals, which use double quotes. Rust’s char
type is four bytes in size and
represents a Unicode Scalar Value, which means it can represent a lot more than
just ASCII. Accented letters; Chinese, Japanese, and Korean characters; emoji;
and zero-width spaces are all valid char
values in Rust. Unicode Scalar
Values range from U+0000
to U+D7FF
and U+E000
to U+10FFFF
inclusive.
However, a “character” isn’t really a concept in Unicode, so your human
intuition for what a “character” is may not match up with what a char
is in
Rust. We’ll discuss this topic in detail in “Storing UTF-8 Encoded Text with
Strings” in Chapter 8.
请注意,我们使用单引号指定char
文字,而不是使用双引号的字符串文字。 Rust 的char
类型大小为 4 个字节,表示 Unicode 标量值,这意味着它可以表示的不仅仅是 ASCII。重音字母;中文、日文、韩文字符;表情符号;和零宽度空格都是 Rust 中的有效char
值。 Unicode 标量值范围从U+0000
到U+D7FF
以及U+E000
到U+10FFFF
(含)。然而,“字符”并不是 Unicode 中真正的概念,因此您对“字符”的人类直觉可能与 Rust 中的char
不相符。我们将在第 8 章的“用字符串存储 UTF-8 编码文本”中详细讨论这个主题。
Compound Types 复合类型
Compound types can group multiple values into one type. Rust has two
primitive compound types: tuples and arrays.
复合类型可以将多个值分组为一种类型。 Rust 有两种原始复合类型:元组和数组。
The Tuple Type 元组类型
A tuple is a general way of grouping together a number of values with a
variety of types into one compound type. Tuples have a fixed length: once
declared, they cannot grow or shrink in size.
元组是将具有多种类型的多个值组合在一起形成一个复合类型的通用方法。元组有固定的长度:一旦声明,它们的大小就不能增长或缩小。
We create a tuple by writing a comma-separated list of values inside
parentheses. Each position in the tuple has a type, and the types of the
different values in the tuple don’t have to be the same. We’ve added optional
type annotations in this example:
我们通过在括号内写入逗号分隔的值列表来创建一个元组。元组中的每个位置都有一个类型,并且元组中不同值的类型不必相同。我们在此示例中添加了可选的类型注释:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
The variable tup
binds to the entire tuple because a tuple is considered a
single compound element. To get the individual values out of a tuple, we can
use pattern matching to destructure a tuple value, like this:
变量tup
绑定到整个元组,因为元组被视为单个复合元素。为了从元组中获取单个值,我们可以使用模式匹配来解构元组值,如下所示:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {y}");
}
This program first creates a tuple and binds it to the variable tup
. It then
uses a pattern with let
to take tup
and turn it into three separate
variables, x
, y
, and z
. This is called destructuring because it breaks
the single tuple into three parts. Finally, the program prints the value of
y
, which is 6.4
.
该程序首先创建一个元组并将其绑定到变量tup
。然后,它使用带有let
模式来获取tup
并将其转换为三个单独的变量x
、 y
和z
。这称为解构,因为它将单个元组分解为三个部分。最后,程序打印y
的值,即6.4
。
We can also access a tuple element directly by using a period (.
) followed by
the index of the value we want to access. For example:
我们还可以通过使用句点 ( .
) 后跟要访问的值的索引来直接访问元组元素。例如:
Filename: src/main.rs 文件名:src/main.rs
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;
}
This program creates the tuple x
and then accesses each element of the tuple
using their respective indices. As with most programming languages, the first
index in a tuple is 0.
该程序创建元组x
,然后使用各自的索引访问元组的每个元素。与大多数编程语言一样,元组中的第一个索引是 0。
The tuple without any values has a special name, unit. This value and its
corresponding type are both written ()
and represent an empty value or an
empty return type. Expressions implicitly return the unit value if they don’t
return any other value.
没有任何值的元组有一个特殊的名称, unit 。这个值和它对应的类型都写成()
,表示一个空值或者一个空返回类型。如果表达式不返回任何其他值,则它们隐式返回单位值。
The Array Type 数组类型
Another way to have a collection of multiple values is with an array. Unlike
a tuple, every element of an array must have the same type. Unlike arrays in
some other languages, arrays in Rust have a fixed length.
拥有多个值的集合的另一种方法是使用数组。与元组不同,数组的每个元素必须具有相同的类型。与其他一些语言中的数组不同,Rust 中的数组具有固定长度。
We write the values in an array as a comma-separated list inside square
brackets:
我们将数组中的值写为方括号内的逗号分隔列表:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let a = [1, 2, 3, 4, 5];
}
Arrays are useful when you want your data allocated on the stack rather than
the heap (we will discuss the stack and the heap more in Chapter
4) or when you want to ensure you always have a
fixed number of elements. An array isn’t as flexible as the vector type,
though. A vector is a similar collection type provided by the standard
library that is allowed to grow or shrink in size. If you’re unsure whether
to use an array or a vector, chances are you should use a vector. Chapter
8 discusses vectors in more detail.
当您希望将数据分配在堆栈而不是堆上(我们将在第 4 章忽略中更多地讨论堆栈和堆)或者当您希望确保始终拥有固定数量的元素时,数组非常有用。不过,数组不如向量类型灵活。矢量是标准库提供的类似集合类型,允许大小增长或缩小。如果您不确定是使用数组还是向量,那么您很可能应该使用向量。第 8 章忽略更详细地讨论向量。
However, arrays are more useful when you know the number of elements will not
need to change. For example, if you were using the names of the month in a
program, you would probably use an array rather than a vector because you know
it will always contain 12 elements:
但是,当您知道元素数量不需要更改时,数组会更有用。例如,如果您在程序中使用月份名称,您可能会使用数组而不是向量,因为您知道它始终包含 12 个元素:
You write an array’s type using square brackets with the type of each element,
a semicolon, and then the number of elements in the array, like so:
您可以使用方括号、每个元素的类型、分号以及数组中元素的数量来编写数组的类型,如下所示:
Here, i32
is the type of each element. After the semicolon, the number 5
indicates the array contains five elements.
这里, i32
是每个元素的类型。分号后面的数字5
表示数组包含五个元素。
You can also initialize an array to contain the same value for each element by
specifying the initial value, followed by a semicolon, and then the length of
the array in square brackets, as shown here:
您还可以通过指定初始值、后跟分号、然后在方括号中指定数组的长度来初始化数组,使其每个元素包含相同的值,如下所示:
The array named a
will contain 5
elements that will all be set to the value
3
initially. This is the same as writing let a = [3, 3, 3, 3, 3];
but in a
more concise way.
名为a
数组将包含5
元素,最初全部设置为值3
。这与编写let a = [3, 3, 3, 3, 3];
但以更简洁的方式。
Accessing Array Elements 访问数组元素
An array is a single chunk of memory of a known, fixed size that can be
allocated on the stack. You can access elements of an array using indexing,
like this:
数组是可以在堆栈上分配的已知固定大小的单个内存块。您可以使用索引访问数组的元素,如下所示:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];
}
In this example, the variable named first
will get the value 1
because that
is the value at index [0]
in the array. The variable named second
will get
the value 2
from index [1]
in the array.
在此示例中,名为first
的变量将获得值1
因为这是数组中索引[0]
处的值。名为second
变量将从数组中的索引[1]
获取值2
。
Invalid Array Element Access
无效的数组元素访问
Let’s see what happens if you try to access an element of an array that is past
the end of the array. Say you run this code, similar to the guessing game in
Chapter 2, to get an array index from the user:
让我们看看如果尝试访问超出数组末尾的数组元素会发生什么。假设你运行这段代码,类似于第 2 章中的猜谜游戏,从用户那里获取数组索引:
Filename: src/main.rs 文件名:src/main.rs
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(&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}");
}
This code compiles successfully. If you run this code using cargo run
and
enter 0
, 1
, 2
, 3
, or 4
, the program will print out the corresponding
value at that index in the array. If you instead enter a number past the end of
the array, such as 10
, you’ll see output like this:
这段代码编译成功。如果您使用cargo run
运行此代码并输入0
、 1
、 2
、 3
或4
,程序将打印出数组中该索引处的相应值。如果您输入超出数组末尾的数字,例如10
,您将看到如下输出:
thread 'main' panicked at src/main.rs:19:19:
index out of bounds: the len is 5 but the index is 10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The program resulted in a runtime error at the point of using an invalid
value in the indexing operation. The program exited with an error message and
didn’t execute the final println!
statement. When you attempt to access an
element using indexing, Rust will check that the index you’ve specified is less
than the array length. If the index is greater than or equal to the length,
Rust will panic. This check has to happen at runtime, especially in this case,
because the compiler can’t possibly know what value a user will enter when they
run the code later.
该程序在索引操作中使用无效值时导致运行时错误。程序退出并显示错误消息,并且没有执行最终的println!
陈述。当您尝试使用索引访问元素时,Rust 将检查您指定的索引是否小于数组长度。如果索引大于或等于长度,Rust 就会出现恐慌。此检查必须在运行时进行,尤其是在这种情况下,因为编译器不可能知道用户稍后运行代码时将输入什么值。
This is an example of Rust’s memory safety principles in action. In many
low-level languages, this kind of check is not done, and when you provide an
incorrect index, invalid memory can be accessed. Rust protects you against this
kind of error by immediately exiting instead of allowing the memory access and
continuing. Chapter 9 discusses more of Rust’s error handling and how you can
write readable, safe code that neither panics nor allows invalid memory access.
这是 Rust 内存安全原则实际应用的一个例子。在许多低级语言中,没有进行这种检查,并且当您提供不正确的索引时,可以访问无效的内存。 Rust 通过立即退出而不是允许内存访问并继续来保护您免受此类错误的影响。第 9 章详细讨论了 Rust 的错误处理以及如何编写既不会发生恐慌也不会允许无效内存访问的可读、安全的代码。
Functions 功能
Functions are prevalent in Rust code. You’ve already seen one of the most
important functions in the language: the main
function, which is the entry
point of many programs. You’ve also seen the fn
keyword, which allows you to
declare new functions.
函数在 Rust 代码中很常见。您已经看到了该语言中最重要的函数之一: main
函数,它是许多程序的入口点。您还看到了fn
关键字,它允许您声明新函数。
Rust code uses snake case as the conventional style for function and variable
names, in which all letters are lowercase and underscores separate words.
Here’s a program that contains an example function definition:
Rust 代码使用蛇形命名法作为函数和变量名称的常规样式,其中所有字母均为小写,并为单独的单词添加下划线。这是一个包含示例函数定义的程序:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
println!("Hello, world!");
another_function();
}
fn another_function() {
println!("Another function.");
}
We define a function in Rust by entering fn
followed by a function name and a
set of parentheses. The curly brackets tell the compiler where the function
body begins and ends.
我们通过输入fn
后跟函数名和一组括号来定义 Rust 中的函数。大括号告诉编译器函数体的开始和结束位置。
We can call any function we’ve defined by entering its name followed by a set
of parentheses. Because another_function
is defined in the program, it can be
called from inside the main
function. Note that we defined another_function
after the main
function in the source code; we could have defined it before
as well. Rust doesn’t care where you define your functions, only that they’re
defined somewhere in a scope that can be seen by the caller.
我们可以通过输入其名称后跟一组括号来调用我们定义的任何函数。因为another_function
是在程序中定义的,所以可以从main
函数内部调用它。注意,我们在源代码中的main
函数之后定义了another_function
;我们之前也可以定义它。 Rust 并不关心你在哪里定义函数,只关心它们是在调用者可以看到的范围内的某个地方定义的。
Let’s start a new binary project named functions to explore functions
further. Place the another_function
example in src/main.rs and run it. You
should see the following output:
让我们启动一个名为Functions 的新二进制项目来进一步探索函数。将another_function
示例放入src/main.rs并运行它。您应该看到以下输出:
$ 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.
The lines execute in the order in which they appear in the main
function.
First the “Hello, world!” message prints, and then another_function
is called
and its message is printed.
这些行按照它们在main
函数中出现的顺序执行。首先是“你好,世界!”打印消息,然后调用another_function
并打印其消息。
Parameters 参数
We can define functions to have parameters, which are special variables that
are part of a function’s signature. When a function has parameters, you can
provide it with concrete values for those parameters. Technically, the concrete
values are called arguments, but in casual conversation, people tend to use
the words parameter and argument interchangeably for either the variables
in a function’s definition or the concrete values passed in when you call a
function.
我们可以定义具有参数的函数,这些参数是作为函数签名一部分的特殊变量。当函数有参数时,您可以为其提供这些参数的具体值。从技术上讲,具体值称为参数,但在日常对话中,人们倾向于交替使用参数和参数这两个词来表示函数定义中的变量或调用函数时传入的具体值。
In this version of another_function
we add a parameter:
在这个版本的another_function
中,我们添加了一个参数:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
another_function(5);
}
fn another_function(x: i32) {
println!("The value of x is: {x}");
}
Try running this program; you should get the following output:
尝试运行这个程序;你应该得到以下输出:
$ 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
The declaration of another_function
has one parameter named x
. The type of
x
is specified as i32
. When we pass 5
in to another_function
, the
println!
macro puts 5
where the pair of curly brackets containing x
was
in the format string.another_function
的声明有一个名为x
参数。 x
的类型指定为i32
。当我们将5
传递给another_function
时, println!
宏将5
放入格式字符串中包含x
的大括号对中。
In function signatures, you must declare the type of each parameter. This is
a deliberate decision in Rust’s design: requiring type annotations in function
definitions means the compiler almost never needs you to use them elsewhere in
the code to figure out what type you mean. The compiler is also able to give
more helpful error messages if it knows what types the function expects.
在函数签名中,必须声明每个参数的类型。这是 Rust 设计中经过深思熟虑的决定:在函数定义中要求类型注释意味着编译器几乎不需要您在代码中的其他地方使用它们来弄清楚您所指的类型。如果编译器知道函数需要什么类型,它还能够给出更有用的错误消息。
When defining multiple parameters, separate the parameter declarations with
commas, like this:
定义多个参数时,用逗号分隔参数声明,如下所示:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
print_labeled_measurement(5, 'h');
}
fn print_labeled_measurement(value: i32, unit_label: char) {
println!("The measurement is: {value}{unit_label}");
}
This example creates a function named print_labeled_measurement
with two
parameters. The first parameter is named value
and is an i32
. The second is
named unit_label
and is type char
. The function then prints text containing
both the value
and the unit_label
.
此示例创建一个名为print_labeled_measurement
的函数,该函数具有两个参数。第一个参数名为value
,是一个i32
。第二个名为unit_label
,类型为char
。然后该函数打印包含value
和unit_label
文本。
Let’s try running this code. Replace the program currently in your functions
project’s src/main.rs file with the preceding example and run it using cargo run
:
让我们尝试运行这段代码。将函数项目的src/main.rs文件中当前的程序替换为前面的示例,并使用cargo run
运行它:
$ 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
Because we called the function with 5
as the value for value
and 'h'
as
the value for unit_label
, the program output contains those values.
因为我们使用5
作为value
的值、 'h'
作为unit_label
的值来调用该函数,所以程序输出包含这些值。
Statements and Expressions
陈述和表达式
Function bodies are made up of a series of statements optionally ending in an
expression. So far, the functions we’ve covered haven’t included an ending
expression, but you have seen an expression as part of a statement. Because
Rust is an expression-based language, this is an important distinction to
understand. Other languages don’t have the same distinctions, so let’s look at
what statements and expressions are and how their differences affect the bodies
of functions.
函数体由一系列可选地以表达式结尾的语句组成。到目前为止,我们介绍的函数尚未包含结束表达式,但您已经看到表达式是语句的一部分。因为 Rust 是一种基于表达式的语言,所以这是一个需要理解的重要区别。其他语言没有相同的区别,所以让我们看看什么是语句和表达式以及它们的差异如何影响函数体。
- Statements are instructions that perform some action and do not return
a value.
语句是执行某些操作但不返回值的指令。 - Expressions evaluate to a resultant value. Let’s look at some examples.
表达式计算结果值。让我们看一些例子。
We’ve actually already used statements and expressions. Creating a variable and
assigning a value to it with the let
keyword is a statement. In Listing 3-1,
let y = 6;
is a statement.
我们实际上已经使用过语句和表达式。创建变量并使用let
关键字为其赋值是一条语句。在清单 3-1 中, let y = 6;
是一个声明。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let y = 6;
}
Function definitions are also statements; the entire preceding example is a
statement in itself.
函数定义也是语句;前面的整个例子本身就是一个陈述。
Statements do not return values. Therefore, you can’t assign a let
statement
to another variable, as the following code tries to do; you’ll get an error:
语句不返回值。因此,您不能将let
语句分配给另一个变量,如以下代码尝试执行的操作;你会得到一个错误:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = (let y = 6);
}
When you run this program, the error you’ll get looks like this:
当您运行该程序时,您将得到如下所示的错误:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error: expected expression, found `let` statement
--> 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
--> 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
The let y = 6
statement does not return a value, so there isn’t anything for
x
to bind to. This is different from what happens in other languages, such as
C and Ruby, where the assignment returns the value of the assignment. In those
languages, you can write x = y = 6
and have both x
and y
have the value
6
; that is not the case in Rust.let y = 6
语句不返回值,因此x
没有任何可绑定的内容。这与其他语言(例如 C 和 Ruby)中发生的情况不同,在其他语言中,赋值返回赋值的值。在这些语言中,您可以编写x = y = 6
并使x
和y
值为6
; Rust 中的情况并非如此。
Expressions evaluate to a value and make up most of the rest of the code that
you’ll write in Rust. Consider a math operation, such as 5 + 6
, which is an
expression that evaluates to the value 11
. Expressions can be part of
statements: in Listing 3-1, the 6
in the statement let y = 6;
is an
expression that evaluates to the value 6
. Calling a function is an
expression. Calling a macro is an expression. A new scope block created with
curly brackets is an expression, for example:
表达式求值并构成您将在 Rust 中编写的其余代码的大部分。考虑一个数学运算,例如5 + 6
,它是一个计算结果为11
表达式。表达式可以是语句的一部分:在清单 3-1 中,语句中的6
let y = 6;
是一个计算结果为值6
表达式。调用函数就是一个表达式。调用宏是一个表达式。使用大括号创建的新作用域块是一个表达式,例如:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let y = {
let x = 3;
x + 1
};
println!("The value of y is: {y}");
}
This expression: 这个表达式:
{
let x = 3;
x + 1
}
is a block that, in this case, evaluates to 4
. That value gets bound to y
as part of the let
statement. Note that the x + 1
line doesn’t have a
semicolon at the end, which is unlike most of the lines you’ve seen so far.
Expressions do not include ending semicolons. If you add a semicolon to the end
of an expression, you turn it into a statement, and it will then not return a
value. Keep this in mind as you explore function return values and expressions
next.
是一个块,在本例中,其计算结果为4
。该值作为let
语句的一部分绑定到y
。请注意, x + 1
行末尾没有分号,这与您目前看到的大多数行不同。表达式不包含结束分号。如果在表达式末尾添加分号,则将其转换为语句,并且它不会返回值。当您接下来探索函数返回值和表达式时,请记住这一点。
Functions with Return Values
有返回值的函数
Functions can return values to the code that calls them. We don’t name return
values, but we must declare their type after an arrow (->
). In Rust, the
return value of the function is synonymous with the value of the final
expression in the block of the body of a function. You can return early from a
function by using the return
keyword and specifying a value, but most
functions return the last expression implicitly. Here’s an example of a
function that returns a value:
函数可以将值返回给调用它们的代码。我们不命名返回值,但必须在箭头( ->
)后面声明它们的类型。在 Rust 中,函数的返回值与函数体块中最终表达式的值同义。您可以通过使用return
关键字并指定一个值来提前从函数返回,但大多数函数都会隐式返回最后一个表达式。下面是一个返回值的函数示例:
Filename: src/main.rs 文件名:src/main.rs
fn five() -> i32 {
5
}
fn main() {
let x = five();
println!("The value of x is: {x}");
}
There are no function calls, macros, or even let
statements in the five
function—just the number 5
by itself. That’s a perfectly valid function in
Rust. Note that the function’s return type is specified too, as -> i32
. Try
running this code; the output should look like this:five
函数中没有函数调用、宏,甚至let
语句,只有数字5
本身。这是 Rust 中一个完全有效的函数。请注意,该函数的返回类型也被指定为-> i32
。尝试运行这段代码;输出应如下所示:
$ 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
The 5
in five
is the function’s return value, which is why the return type
is i32
. Let’s examine this in more detail. There are two important bits:
first, the line let x = five();
shows that we’re using the return value of a
function to initialize a variable. Because the function five
returns a 5
,
that line is the same as the following:five
之5
是函数的返回值,这就是返回类型为i32
原因。让我们更详细地研究一下这一点。有两个重要的位:首先,行let x = five();
表明我们正在使用函数的返回值来初始化变量。因为函数five
返回5
,所以该行与以下内容相同:
Second, the five
function has no parameters and defines the type of the
return value, but the body of the function is a lonely 5
with no semicolon
because it’s an expression whose value we want to return.
其次, five
函数没有参数并定义了返回值的类型,但函数体是一个没有分号的孤独的5
因为它是一个我们想要返回其值的表达式。
Let’s look at another example:
让我们看另一个例子:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = plus_one(5);
println!("The value of x is: {x}");
}
fn plus_one(x: i32) -> i32 {
x + 1
}
Running this code will print The value of x is: 6
. But if we place a
semicolon at the end of the line containing x + 1
, changing it from an
expression to a statement, we’ll get an error:
运行此代码将打印The value of x is: 6
。但是如果我们在包含x + 1
行末尾放置一个分号,将其从表达式更改为语句,我们将收到错误:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = plus_one(5);
println!("The value of x is: {x}");
}
fn plus_one(x: i32) -> i32 {
x + 1;
}
Compiling this code produces an error, as follows:
编译此代码会产生错误,如下所示:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error[E0308]: mismatched types
--> src/main.rs:7:24
|
7 | fn plus_one(x: i32) -> 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
The main error message, mismatched types
, reveals the core issue with this
code. The definition of the function plus_one
says that it will return an
i32
, but statements don’t evaluate to a value, which is expressed by ()
,
the unit type. Therefore, nothing is returned, which contradicts the function
definition and results in an error. In this output, Rust provides a message to
possibly help rectify this issue: it suggests removing the semicolon, which
would fix the error.
主要的错误消息, mismatched types
,揭示了这段代码的核心问题。函数plus_one
的定义表示它将返回i32
,但语句不会求值,该值由单位类型()
表示。因此,不会返回任何内容,这与函数定义相矛盾并导致错误。在此输出中,Rust 提供了一条消息,可能有助于纠正此问题:它建议删除分号,这将修复错误。
Comments 评论
All programmers strive to make their code easy to understand, but sometimes
extra explanation is warranted. In these cases, programmers leave comments in
their source code that the compiler will ignore but people reading the source
code may find useful.
所有程序员都努力使他们的代码易于理解,但有时需要额外的解释。在这些情况下,程序员在源代码中留下注释,编译器将忽略这些注释,但阅读源代码的人可能会发现有用。
Here’s a simple comment: 这是一个简单的评论:
In Rust, the idiomatic comment style starts a comment with two slashes, and the
comment continues until the end of the line. For comments that extend beyond a
single line, you’ll need to include //
on each line, like this:
在 Rust 中,惯用的注释风格以两个斜杠开始注释,并且注释一直持续到行尾。对于超出单行的注释,您需要在每一行中包含//
,如下所示:
Comments can also be placed at the end of lines containing code:
注释也可以放置在包含代码的行的末尾:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let lucky_number = 7; // I’m feeling lucky today
}
But you’ll more often see them used in this format, with the comment on a
separate line above the code it’s annotating:
但您会更经常看到它们以这种格式使用,注释位于其注释的代码上方的单独行上:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
// I’m feeling lucky today
let lucky_number = 7;
}
Rust also has another kind of comment, documentation comments, which we’ll
discuss in the “Publishing a Crate to Crates.io”
section of Chapter 14.
Rust 还有另一种注释,即文档注释,我们将在第 14 章的“将 Crate 发布到 Crates.io”忽略部分中讨论。
Control Flow 控制流程
The ability to run some code depending on whether a condition is true
and to
run some code repeatedly while a condition is true
are basic building blocks
in most programming languages. The most common constructs that let you control
the flow of execution of Rust code are if
expressions and loops.
根据条件是否为true
来运行某些代码以及在条件为true
时重复运行某些代码的能力是大多数编程语言中的基本构建块。让您控制 Rust 代码执行流程的最常见结构是if
表达式和循环。
if
Expressions
if
表达式
An if
expression allows you to branch your code depending on conditions. You
provide a condition and then state, “If this condition is met, run this block
of code. If the condition is not met, do not run this block of code.”if
表达式允许您根据条件分支代码。您提供一个条件,然后声明:“如果满足此条件,则运行此代码块。如果不满足条件,则不要运行该代码块。”
Create a new project called branches in your projects directory to explore
the if
expression. In the src/main.rs file, input the following:
在项目目录中创建一个名为Branches的新项目来探索if
表达式。在src/main.rs文件中,输入以下内容:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
All if
expressions start with the keyword if
, followed by a condition. In
this case, the condition checks whether or not the variable number
has a
value less than 5. We place the block of code to execute if the condition is
true
immediately after the condition inside curly brackets. Blocks of code
associated with the conditions in if
expressions are sometimes called arms,
just like the arms in match
expressions that we discussed in the “Comparing
the Guess to the Secret Number” section of Chapter 2.
所有if
表达式都以关键字if
开头,后跟条件。在本例中,条件检查变量number
的值是否小于 5。如果条件为true
,我们将要执行的代码块放在大括号内的条件之后。 if
表达式中的条件相关的代码块有时称为Arms ,就像我们在第 2 章的“比较猜测与秘密数字”忽略部分中讨论的match
表达式中的 Arms 一样。
Optionally, we can also include an else
expression, which we chose to do
here, to give the program an alternative block of code to execute should the
condition evaluate to false
. If you don’t provide an else
expression and
the condition is false
, the program will just skip the if
block and move on
to the next bit of code.
或者,我们还可以包含一个else
表达式,我们在这里选择这样做,以便在条件评估为false
时为程序提供一个要执行的替代代码块。如果您不提供else
表达式并且条件为false
,则程序将跳过if
块并继续执行下一段代码。
Try running this code; you should see the following output:
尝试运行这段代码;您应该看到以下输出:
$ 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
Let’s try changing the value of number
to a value that makes the condition
false
to see what happens:
让我们尝试将number
的值更改为使条件为false
值,看看会发生什么:
Run the program again, and look at the output:
再次运行程序,查看输出:
$ 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
It’s also worth noting that the condition in this code must be a bool
. If
the condition isn’t a bool
, we’ll get an error. For example, try running the
following code:
还值得注意的是,此代码中的条件必须是bool
。如果条件不是bool
,我们会收到错误。例如,尝试运行以下代码:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let number = 3;
if number {
println!("number was three");
}
}
The if
condition evaluates to a value of 3
this time, and Rust throws an
error:
这次if
条件的计算结果为3
,Rust 抛出错误:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: mismatched types
--> 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
The error indicates that Rust expected a bool
but got an integer. Unlike
languages such as Ruby and JavaScript, Rust will not automatically try to
convert non-Boolean types to a Boolean. You must be explicit and always provide
if
with a Boolean as its condition. If we want the if
code block to run
only when a number is not equal to 0
, for example, we can change the if
expression to the following:
该错误表明 Rust 期望是bool
,但得到的是整数。与 Ruby 和 JavaScript 等语言不同,Rust 不会自动尝试将非布尔类型转换为布尔类型。您必须明确并始终提供以布尔值作为条件的if
。例如,如果我们希望if
代码块仅在数字不等于0
时运行,我们可以将if
表达式更改为以下内容:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let number = 3;
if number != 0 {
println!("number was something other than zero");
}
}
Running this code will print number was something other than zero
.
运行此代码将打印number was something other than zero
。
Handling Multiple Conditions with else if
使用else if
处理多个条件
You can use multiple conditions by combining if
and else
in an else if
expression. For example:
您可以通过在else if
表达式中组合if
和else
来使用多个条件。例如:
Filename: src/main.rs 文件名:src/main.rs
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");
}
}
This program has four possible paths it can take. After running it, you should
see the following output:
该程序有四种可能的路径。运行后,您应该看到以下输出:
$ 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
When this program executes, it checks each if
expression in turn and executes
the first body for which the condition evaluates to true
. Note that even
though 6 is divisible by 2, we don’t see the output number is divisible by 2
,
nor do we see the number is not divisible by 4, 3, or 2
text from the else
block. That’s because Rust only executes the block for the first true
condition, and once it finds one, it doesn’t even check the rest.
当该程序执行时,它依次检查每个if
表达式并执行条件评估为true
第一个主体。请注意,即使 6 可以被 2 整除,我们也看不到输出number is divisible by 2
,也没有看到该数字不能被else
块中的number is not divisible by 4, 3, or 2
。这是因为 Rust 只执行第一个true
条件的块,一旦找到一个,它甚至不会检查其余的。
Using too many else if
expressions can clutter your code, so if you have more
than one, you might want to refactor your code. Chapter 6 describes a powerful
Rust branching construct called match
for these cases.
使用太多else if
表达式会使您的代码变得混乱,因此如果您有多个 else if 表达式,您可能需要重构您的代码。第 6 章描述了一个强大的 Rust 分支结构,称为match
,适用于这些情况。
Using if
in a let
Statement
在let
语句中使用if
Because if
is an expression, we can use it on the right side of a let
statement to assign the outcome to a variable, as in Listing 3-2.
因为if
是一个表达式,所以我们可以在let
语句的右侧使用它来将结果分配给变量,如清单 3-2 所示。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {number}");
}
The number
variable will be bound to a value based on the outcome of the if
expression. Run this code to see what happens:number
变量将根据if
表达式的结果绑定到一个值。运行此代码看看会发生什么:
$ 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
Remember that blocks of code evaluate to the last expression in them, and
numbers by themselves are also expressions. In this case, the value of the
whole if
expression depends on which block of code executes. This means the
values that have the potential to be results from each arm of the if
must be
the same type; in Listing 3-2, the results of both the if
arm and the else
arm were i32
integers. If the types are mismatched, as in the following
example, we’ll get an error:
请记住,代码块的计算结果是其中的最后一个表达式,数字本身也是表达式。在这种情况下,整个if
表达式的值取决于执行哪个代码块。这意味着if
的每个分支可能产生的值必须是相同的类型;在清单 3-2 中, if
臂和else
臂的结果都是i32
整数。如果类型不匹配,如下例所示,我们将收到错误:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let condition = true;
let number = if condition { 5 } else { "six" };
println!("The value of number is: {number}");
}
When we try to compile this code, we’ll get an error. The if
and else
arms
have value types that are incompatible, and Rust indicates exactly where to
find the problem in the program:
当我们尝试编译此代码时,我们会收到错误。 if
和else
分支具有不兼容的值类型,Rust 准确指出了在程序中查找问题的位置:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: `if` and `else` have incompatible types
--> src/main.rs:4:44
|
4 | let number = if condition { 5 } else { "six" };
| - ^^^^^ expected integer, found `&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
The expression in the if
block evaluates to an integer, and the expression in
the else
block evaluates to a string. This won’t work because variables must
have a single type, and Rust needs to know at compile time what type the
number
variable is, definitively. Knowing the type of number
lets the
compiler verify the type is valid everywhere we use number
. Rust wouldn’t be
able to do that if the type of number
was only determined at runtime; the
compiler would be more complex and would make fewer guarantees about the code
if it had to keep track of multiple hypothetical types for any variable.if
块中的表达式计算结果为整数, else
块中的表达式计算结果为字符串。这是行不通的,因为变量必须具有单一类型,并且 Rust 需要在编译时明确知道number
变量是什么类型。了解number
的类型可以让编译器验证该类型在我们使用number
任何地方都有效。如果number
类型仅在运行时确定,Rust 将无法做到这一点;如果编译器必须跟踪任何变量的多个假设类型,编译器将会更加复杂,并且对代码的保证也会更少。
Repetition with Loops 循环重复
It’s often useful to execute a block of code more than once. For this task,
Rust provides several loops, which will run through the code inside the loop
body to the end and then start immediately back at the beginning. To experiment
with loops, let’s make a new project called loops.
多次执行一段代码通常很有用。对于这个任务,Rust 提供了几个循环,这些循环将运行循环体内的代码直到结束,然后立即从头开始。为了试验循环,让我们创建一个名为Loops的新项目。
Rust has three kinds of loops: loop
, while
, and for
. Let’s try each one.
Rust 具有三种循环: loop
、 while
和for
。让我们逐一尝试一下。
Repeating Code with loop
带loop
重复代码
The loop
keyword tells Rust to execute a block of code over and over again
forever or until you explicitly tell it to stop.loop
关键字告诉 Rust 永远一遍又一遍地执行代码块,或者直到你明确告诉它停止为止。
As an example, change the src/main.rs file in your loops directory to look
like this:
例如,将循环目录中的src/main.rs文件更改为如下所示:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
loop {
println!("again!");
}
}
When we run this program, we’ll see again!
printed over and over continuously
until we stop the program manually. Most terminals support the keyboard shortcut
ctrl-
当我们运行这个程序时,我们会again!
不断地打印,直到我们手动停止程序。大多数终端都支持键盘快捷键 ctrl - c 中断陷入连续循环的程序。尝试一下:
$ 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!
The symbol ^C
represents where you pressed ctrl-c. You
may or may not see the word again!
printed after the ^C
, depending on where
the code was in the loop when it received the interrupt signal.
符号^C
代表您按下的位置 ctrl - c 。您可能会也可能不会again!
在^C
之后打印,具体取决于收到中断信号时代码在循环中的位置。
Fortunately, Rust also provides a way to break out of a loop using code. You
can place the break
keyword within the loop to tell the program when to stop
executing the loop. Recall that we did this in the guessing game in the
“Quitting After a Correct Guess” section of Chapter 2 to exit the program when the user won the game by
guessing the correct number.
幸运的是,Rust 还提供了一种使用代码打破循环的方法。您可以在循环中放置break
关键字来告诉程序何时停止执行循环。回想一下,我们在第 2 章“猜对后退出”忽略部分的猜谜游戏中这样做了,当用户通过猜对数字赢得游戏时退出程序。
We also used continue
in the guessing game, which in a loop tells the program
to skip over any remaining code in this iteration of the loop and go to the
next iteration.
我们还在猜谜游戏中使用了continue
,它在循环中告诉程序跳过本次循环迭代中的任何剩余代码并进入下一次迭代。
Returning Values from Loops
从循环返回值
One of the uses of a loop
is to retry an operation you know might fail, such
as checking whether a thread has completed its job. You might also need to pass
the result of that operation out of the loop to the rest of your code. To do
this, you can add the value you want returned after the break
expression you
use to stop the loop; that value will be returned out of the loop so you can
use it, as shown here:loop
的用途之一是重试您知道可能会失败的操作,例如检查线程是否已完成其作业。您可能还需要将该操作的结果从循环传递到代码的其余部分。为此,您可以在用于停止循环的break
表达式之后添加您想要返回的值;该值将从循环中返回,以便您可以使用它,如下所示:
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}
Before the loop, we declare a variable named counter
and initialize it to
0
. Then we declare a variable named result
to hold the value returned from
the loop. On every iteration of the loop, we add 1
to the counter
variable,
and then check whether the counter
is equal to 10
. When it is, we use the
break
keyword with the value counter * 2
. After the loop, we use a
semicolon to end the statement that assigns the value to result
. Finally, we
print the value in result
, which in this case is 20
.
在循环之前,我们声明一个名为counter
变量并将其初始化为0
。然后我们声明一个名为result
的变量来保存循环返回的值。在循环的每次迭代中,我们将counter
变量加1
,然后检查counter
是否等于10
。如果是这样,我们使用带有值counter * 2
break
关键字。循环之后,我们使用分号来结束将值赋给result
的语句。最后,我们打印result
中的值,在本例中为20
。
You can also return
from inside a loop. While break
only exits the current
loop, return
always exits the current function.
您也可以从循环内部return
。 break
仅退出当前循环,而return
始终退出当前函数。
Loop Labels to Disambiguate Between Multiple Loops
用于消除多个循环之间歧义的循环标签
If you have loops within loops, break
and continue
apply to the innermost
loop at that point. You can optionally specify a loop label on a loop that
you can then use with break
or continue
to specify that those keywords
apply to the labeled loop instead of the innermost loop. Loop labels must begin
with a single quote. Here’s an example with two nested loops:
如果循环内有循环,则break
并continue
应用于该点的最内层循环。您可以选择在循环上指定循环标签,然后将其与break
一起使用,或continue
指定这些关键字应用于带标签的循环而不是最内层循环。循环标签必须以单引号开头。这是一个包含两个嵌套循环的示例:
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}");
}
The outer loop has the label 'counting_up
, and it will count up from 0 to 2.
The inner loop without a label counts down from 10 to 9. The first break
that
doesn’t specify a label will exit the inner loop only. The break 'counting_up;
statement will exit the outer loop. This code prints:
外循环有标签'counting_up
,它将从 0 到 2 递增计数。没有标签的内循环从 10 到 9 递减计数。第一个不指定标签的break
将仅退出内循环。 break 'counting_up;
语句将退出外循环。此代码打印:
$ 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
Conditional Loops with while
带while
条件循环
A program will often need to evaluate a condition within a loop. While the
condition is true
, the loop runs. When the condition ceases to be true
, the
program calls break
, stopping the loop. It’s possible to implement behavior
like this using a combination of loop
, if
, else
, and break
; you could
try that now in a program, if you’d like. However, this pattern is so common
that Rust has a built-in language construct for it, called a while
loop. In
Listing 3-3, we use while
to loop the program three times, counting down each
time, and then, after the loop, print a message and exit.
程序通常需要评估循环内的条件。当条件为true
时,循环运行。当条件不再为true
时,程序调用break
来停止循环。可以使用loop
、 if
、 else
和break
的组合来实现这样的行为;如果您愿意,您现在可以在程序中尝试一下。然而,这种模式非常常见,以至于 Rust 有一个内置的语言构造,称为while
循环。在清单 3-3 中,我们使用while
循环程序三次,每次倒计时,然后在循环结束后打印一条消息并退出。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
}
This construct eliminates a lot of nesting that would be necessary if you used
loop
, if
, else
, and break
, and it’s clearer. While a condition
evaluates to true
, the code runs; otherwise, it exits the loop.
这种结构消除了使用loop
、 if
、 else
和break
时所必需的大量嵌套,而且更加清晰。当条件评估为true
时,代码将运行;否则,它退出循环。
Looping Through a Collection with for
使用for
循环遍历集合
You can also use the while
construct to loop over the elements of a
collection, such as an array. For example, the loop in Listing 3-4 prints each
element in the array a
.
您还可以使用while
构造来循环集合(例如数组)的元素。例如,清单 3-4 中的循环打印数组a
中的每个元素。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}
Here, the code counts up through the elements in the array. It starts at index
0
, and then loops until it reaches the final index in the array (that is,
when index < 5
is no longer true
). Running this code will print every
element in the array:
此处,代码对数组中的元素进行向上计数。它从索引0
开始,然后循环直到到达数组中的最终索引(即,当index < 5
不再为true
时)。运行此代码将打印数组中的每个元素:
$ 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
All five array values appear in the terminal, as expected. Even though index
will reach a value of 5
at some point, the loop stops executing before trying
to fetch a sixth value from the array.
正如预期的那样,所有五个数组值都出现在终端中。即使index
在某个时刻将达到值5
,循环也会在尝试从数组中获取第六个值之前停止执行。
However, this approach is error prone; we could cause the program to panic if
the index value or test condition is incorrect. For example, if you changed the
definition of the a
array to have four elements but forgot to update the
condition to while index < 4
, the code would panic. It’s also slow, because
the compiler adds runtime code to perform the conditional check of whether the
index is within the bounds of the array on every iteration through the loop.
然而,这种方法很容易出错;如果索引值或测试条件不正确,我们可能会导致程序出现恐慌。例如,如果您将a
数组的定义更改为包含四个元素,但忘记将条件更新为while index < 4
,则代码将会出现混乱。它也很慢,因为编译器添加了运行时代码来在循环的每次迭代中执行索引是否在数组范围内的条件检查。
As a more concise alternative, you can use a for
loop and execute some code
for each item in a collection. A for
loop looks like the code in Listing 3-5.
作为更简洁的替代方案,您可以使用for
循环并为集合中的每个项目执行一些代码。 for
循环类似于清单 3-5 中的代码。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}
When we run this code, we’ll see the same output as in Listing 3-4. More
importantly, we’ve now increased the safety of the code and eliminated the
chance of bugs that might result from going beyond the end of the array or not
going far enough and missing some items.
当我们运行这段代码时,我们将看到与清单 3-4 相同的输出。更重要的是,我们现在提高了代码的安全性,并消除了由于超出数组末尾或不够远而丢失某些项目而可能导致错误的可能性。
Using the for
loop, you wouldn’t need to remember to change any other code if
you changed the number of values in the array, as you would with the method
used in Listing 3-4.
使用for
循环,如果您更改了数组中的值的数量,则无需记住更改任何其他代码,就像使用清单 3-4 中使用的方法一样。
The safety and conciseness of for
loops make them the most commonly used loop
construct in Rust. Even in situations in which you want to run some code a
certain number of times, as in the countdown example that used a while
loop
in Listing 3-3, most Rustaceans would use a for
loop. The way to do that
would be to use a Range
, provided by the standard library, which generates
all numbers in sequence starting from one number and ending before another
number.for
循环的安全性和简洁性使其成为 Rust 中最常用的循环结构。即使在您想要运行某些代码一定次数的情况下(如清单 3-3 中使用while
循环的倒计时示例),大多数 Rustaceans 也会使用for
循环。做到这一点的方法是使用标准库提供的Range
,它按顺序生成从一个数字开始到另一个数字之前结束的所有数字。
Here’s what the countdown would look like using a for
loop and another method
we’ve not yet talked about, rev
, to reverse the range:
这是使用for
循环和我们尚未讨论的另一种方法rev
来反转范围的倒计时:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}
This code is a bit nicer, isn’t it?
这段代码好一点,不是吗?
Summary 概括
You made it! This was a sizable chapter: you learned about variables, scalar
and compound data types, functions, comments, if
expressions, and loops! To
practice with the concepts discussed in this chapter, try building programs to
do the following:
你成功了!这是一个相当大的章节:您了解了变量、标量和复合数据类型、函数、注释、 if
表达式和循环!要练习本章讨论的概念,请尝试构建程序来执行以下操作:
- Convert temperatures between Fahrenheit and Celsius.
在华氏度和摄氏度之间转换温度。 - Generate the nth Fibonacci number.
生成第 n 个斐波那契数。 - Print the lyrics to the Christmas carol “The Twelve Days of Christmas,”
taking advantage of the repetition in the song.
利用歌曲中的重复内容打印圣诞颂歌“圣诞节的十二天”的歌词。
When you’re ready to move on, we’ll talk about a concept in Rust that doesn’t
commonly exist in other programming languages: ownership.
当您准备好继续前进时,我们将讨论 Rust 中的一个在其他编程语言中不常见的概念:所有权。
Understanding Ownership 了解所有权
Ownership is Rust’s most unique feature and has deep implications for the rest
of the language. It enables Rust to make memory safety guarantees without
needing a garbage collector, so it’s important to understand how ownership
works. In this chapter, we’ll talk about ownership as well as several related
features: borrowing, slices, and how Rust lays data out in memory.
所有权是 Rust 最独特的功能,对语言的其他部分有着深远的影响。它使 Rust 能够在不需要垃圾收集器的情况下保证内存安全,因此了解所有权的工作原理非常重要。在本章中,我们将讨论所有权以及几个相关功能:借用、切片以及 Rust 如何在内存中布置数据。
What Is Ownership? 什么是所有权?
Ownership is a set of rules that govern how a Rust program manages memory.
All programs have to manage the way they use a computer’s memory while running.
Some languages have garbage collection that regularly looks for no-longer-used
memory as the program runs; in other languages, the programmer must explicitly
allocate and free the memory. Rust uses a third approach: memory is managed
through a system of ownership with a set of rules that the compiler checks. If
any of the rules are violated, the program won’t compile. None of the features
of ownership will slow down your program while it’s running.
所有权是一组规则,用于控制 Rust 程序如何管理内存。所有程序都必须管理它们在运行时使用计算机内存的方式。有些语言具有垃圾收集功能,会在程序运行时定期查找不再使用的内存;在其他语言中,程序员必须显式分配和释放内存。 Rust 使用第三种方法:通过所有权系统和编译器检查的一组规则来管理内存。如果违反任何规则,程序将无法编译。所有权的任何功能都不会减慢程序运行的速度。
Because ownership is a new concept for many programmers, it does take some time
to get used to. The good news is that the more experienced you become with Rust
and the rules of the ownership system, the easier you’ll find it to naturally
develop code that is safe and efficient. Keep at it!
因为所有权对于许多程序员来说是一个新概念,所以确实需要一些时间来适应。好消息是,您对 Rust 和所有权系统规则的经验越丰富,您就越容易自然地开发出安全高效的代码。坚持下去!
When you understand ownership, you’ll have a solid foundation for understanding
the features that make Rust unique. In this chapter, you’ll learn ownership by
working through some examples that focus on a very common data structure:
strings.
当您了解所有权时,您将为了解 Rust 独特的功能奠定坚实的基础。在本章中,您将通过一些示例来学习所有权,这些示例重点关注非常常见的数据结构:字符串。
The Stack and the Heap
栈和堆
Many programming languages don’t require you to think about the stack and the
heap very often. But in a systems programming language like Rust, whether a
value is on the stack or the heap affects how the language behaves and why
you have to make certain decisions. Parts of ownership will be described in
relation to the stack and the heap later in this chapter, so here is a brief
explanation in preparation.
许多编程语言并不要求您经常考虑堆栈和堆。但在像 Rust 这样的系统编程语言中,值是在堆栈上还是在堆上会影响语言的行为方式以及为什么必须做出某些决定。本章稍后将描述与堆栈和堆相关的所有权部分,因此这里是准备中的简要说明。
Both the stack and the heap are parts of memory available to your code to use
at runtime, but they are structured in different ways. The stack stores
values in the order it gets them and removes the values in the opposite
order. This is referred to as last in, first out. Think of a stack of
plates: when you add more plates, you put them on top of the pile, and when
you need a plate, you take one off the top. Adding or removing plates from
the middle or bottom wouldn’t work as well! Adding data is called pushing
onto the stack, and removing data is called popping off the stack. All
data stored on the stack must have a known, fixed size. Data with an unknown
size at compile time or a size that might change must be stored on the heap
instead.
堆栈和堆都是可供代码在运行时使用的内存部分,但它们的结构方式不同。堆栈按照获取值的顺序存储值,并按照相反的顺序删除值。这称为后进先出。想象一叠盘子:当你添加更多盘子时,你把它们放在一堆盘子的顶部,当你需要一个盘子时,你从上面拿一个。从中间或底部添加或删除板也不起作用!添加数据称为压入堆栈,删除数据称为从堆栈弹出。存储在堆栈上的所有数据都必须具有已知的固定大小。编译时大小未知或大小可能更改的数据必须存储在堆上。
The heap is less organized: when you put data on the heap, you request a
certain amount of space. The memory allocator finds an empty spot in the heap
that is big enough, marks it as being in use, and returns a pointer, which
is the address of that location. This process is called allocating on the
heap and is sometimes abbreviated as just allocating (pushing values onto
the stack is not considered allocating). Because the pointer to the heap is a
known, fixed size, you can store the pointer on the stack, but when you want
the actual data, you must follow the pointer. Think of being seated at a
restaurant. When you enter, you state the number of people in your group, and
the host finds an empty table that fits everyone and leads you there. If
someone in your group comes late, they can ask where you’ve been seated to
find you.
堆的组织性较差:当您将数据放入堆上时,您会请求一定量的空间。内存分配器在堆中找到一个足够大的空位,将其标记为正在使用,并返回一个指针,它是该位置的地址。这个过程称为在堆上分配,有时缩写为分配(将值压入堆栈不被视为分配)。因为指向堆的指针是已知的、固定大小,所以您可以将指针存储在堆栈上,但是当您需要实际数据时,必须跟随指针。想象一下坐在一家餐馆里。当您进入时,请说出您的团体人数,然后主人会找到一张适合每个人的空桌子并带您前往那里。如果您的团队中有人迟到,他们可以询问您坐在哪里以便找到您。
Pushing to the stack is faster than allocating on the heap because the
allocator never has to search for a place to store new data; that location is
always at the top of the stack. Comparatively, allocating space on the heap
requires more work because the allocator must first find a big enough space
to hold the data and then perform bookkeeping to prepare for the next
allocation.
压入堆栈比在堆上分配更快,因为分配器永远不需要搜索存储新数据的位置;该位置始终位于堆栈的顶部。相比之下,在堆上分配空间需要更多的工作,因为分配器必须首先找到足够大的空间来容纳数据,然后进行簿记,为下一次分配做准备。
Accessing data in the heap is slower than accessing data on the stack because
you have to follow a pointer to get there. Contemporary processors are faster
if they jump around less in memory. Continuing the analogy, consider a server
at a restaurant taking orders from many tables. It’s most efficient to get
all the orders at one table before moving on to the next table. Taking an
order from table A, then an order from table B, then one from A again, and
then one from B again would be a much slower process. By the same token, a
processor can do its job better if it works on data that’s close to other
data (as it is on the stack) rather than farther away (as it can be on the
heap).
访问堆中的数据比访问堆栈中的数据慢,因为您必须遵循指针才能到达那里。如果现代处理器在内存中的跳跃次数更少,那么它们的速度就会更快。继续类比,考虑餐厅的服务员从许多桌子上点菜。在转到下一张桌子之前先在一张桌子上获得所有订单是最有效的。从 A 表中获取订单,然后从 B 表中获取订单,然后再次从 A 中获取订单,然后再次从 B 中获取订单,这将是一个慢得多的过程。出于同样的原因,如果处理器处理靠近其他数据(因为它在堆栈上)而不是较远的数据(因为它可以在堆上)的数据,那么它可以更好地完成工作。
When your code calls a function, the values passed into the function
(including, potentially, pointers to data on the heap) and the function’s
local variables get pushed onto the stack. When the function is over, those
values get popped off the stack.
当您的代码调用函数时,传递给函数的值(可能包括指向堆上数据的指针)和函数的局部变量被推送到堆栈上。当函数结束时,这些值将从堆栈中弹出。
Keeping track of what parts of code are using what data on the heap,
minimizing the amount of duplicate data on the heap, and cleaning up unused
data on the heap so you don’t run out of space are all problems that ownership
addresses. Once you understand ownership, you won’t need to think about the
stack and the heap very often, but knowing that the main purpose of ownership
is to manage heap data can help explain why it works the way it does.
跟踪代码的哪些部分正在使用堆上的哪些数据、最大限度地减少堆上的重复数据量以及清理堆上未使用的数据以免耗尽空间,这些都是所有权解决的问题。一旦理解了所有权,您就不需要经常考虑堆栈和堆,但是知道所有权的主要目的是管理堆数据可以帮助解释为什么它会这样工作。
Ownership Rules 所有权规则
First, let’s take a look at the ownership rules. Keep these rules in mind as we
work through the examples that illustrate them:
首先,我们来看看所有权规则。当我们通过示例来说明这些规则时,请记住这些规则:
- Each value in Rust has an owner.
Rust 中的每个值都有一个所有者。 - There can only be one owner at a time.
一次只能有一位所有者。 - When the owner goes out of scope, the value will be dropped.
当所有者超出范围时,该值将被删除。
Variable Scope 变量范围
Now that we’re past basic Rust syntax, we won’t include all the fn main() {
code in examples, so if you’re following along, make sure to put the following
examples inside a main
function manually. As a result, our examples will be a
bit more concise, letting us focus on the actual details rather than
boilerplate code.
现在我们已经了解了基本的 Rust 语法,我们不会在示例中包含所有fn main() {
代码,因此如果您正在遵循,请确保手动将以下示例放入main
函数中。因此,我们的示例将更加简洁,让我们专注于实际细节而不是样板代码。
As a first example of ownership, we’ll look at the scope of some variables. A
scope is the range within a program for which an item is valid. Take the
following variable:
作为所有权的第一个示例,我们将了解一些变量的范围。范围是程序内某项有效的范围。取以下变量:
The variable s
refers to a string literal, where the value of the string is
hardcoded into the text of our program. The variable is valid from the point at
which it’s declared until the end of the current scope. Listing 4-1 shows a
program with comments annotating where the variable s
would be valid.
变量s
指的是字符串文字,其中字符串的值被硬编码到我们程序的文本中。该变量从声明之日起一直有效,直至当前作用域结束。清单 4-1 显示了一个带有注释的程序,注释了变量s
的有效位置。
In other words, there are two important points in time here:
换句话说,这里有两个重要的时间点:
- When
s
comes into scope, it is valid.
当s
进入作用域时,它是有效的。 - It remains valid until it goes out of scope.
它一直有效,直到超出范围。
At this point, the relationship between scopes and when variables are valid is
similar to that in other programming languages. Now we’ll build on top of this
understanding by introducing the String
type.
此时,作用域和变量何时有效之间的关系与其他编程语言中的类似。现在我们将通过介绍String
类型来建立在这种理解的基础上。
The String
Type
String
类型
To illustrate the rules of ownership, we need a data type that is more complex
than those we covered in the “Data Types” section
of Chapter 3. The types covered previously are of a known size, can be stored
on the stack and popped off the stack when their scope is over, and can be
quickly and trivially copied to make a new, independent instance if another
part of code needs to use the same value in a different scope. But we want to
look at data that is stored on the heap and explore how Rust knows when to
clean up that data, and the String
type is a great example.
为了说明所有权规则,我们需要一个比第 3 章“数据类型”忽略部分中介绍的数据类型更复杂的数据类型。前面介绍的类型具有已知的大小,可以存储在堆栈上并弹出当它们的作用域结束时,它们会从堆栈中退出,并且如果代码的另一部分需要在不同的作用域中使用相同的值,则可以快速而简单地复制以创建新的独立实例。但我们想要查看存储在堆上的数据并探索 Rust 如何知道何时清理这些数据,而String
类型就是一个很好的例子。
We’ll concentrate on the parts of String
that relate to ownership. These
aspects also apply to other complex data types, whether they are provided by
the standard library or created by you. We’ll discuss String
in more depth in
Chapter 8.
我们将重点关注String
中与所有权相关的部分。这些方面也适用于其他复杂数据类型,无论它们是由标准库提供还是由您创建。我们将在第 8 章中更深入地讨论String
。
We’ve already seen string literals, where a string value is hardcoded into our
program. String literals are convenient, but they aren’t suitable for every
situation in which we may want to use text. One reason is that they’re
immutable. Another is that not every string value can be known when we write
our code: for example, what if we want to take user input and store it? For
these situations, Rust has a second string type, String
. This type manages
data allocated on the heap and as such is able to store an amount of text that
is unknown to us at compile time. You can create a String
from a string
literal using the from
function, like so:
我们已经见过字符串文字,其中字符串值被硬编码到我们的程序中。字符串文字很方便,但它们并不适合我们可能想要使用文本的所有情况。原因之一是它们是不可变的。另一个问题是,当我们编写代码时,并不是每个字符串值都是已知的:例如,如果我们想要获取用户输入并存储它怎么办?对于这些情况,Rust 有第二种字符串类型: String
。这种类型管理在堆上分配的数据,因此能够存储编译时我们未知的大量文本。您可以使用from
函数从字符串文字创建String
,如下所示:
The double colon ::
operator allows us to namespace this particular from
function under the String
type rather than using some sort of name like
string_from
. We’ll discuss this syntax more in the “Method
Syntax” section of Chapter 5, and when we talk
about namespacing with modules in “Paths for Referring to an Item in the
Module Tree” in Chapter 7.
双冒号::
运算符允许我们在String
类型下命名这个特定的from
函数,而不是使用某种名称,如string_from
。我们将在第 5 章的“方法语法”忽略部分中更多地讨论此语法,并且当我们在第 7 章的“引用模块树中的项目的路径”中讨论模块的命名空间时,忽略。
This kind of string can be mutated:
这种字符串可以改变:
So, what’s the difference here? Why can String
be mutated but literals
cannot? The difference is in how these two types deal with memory.
那么,这里有什么区别呢?为什么String
可以改变而文字却不能?区别在于这两种类型如何处理内存。
Memory and Allocation 内存和分配
In the case of a string literal, we know the contents at compile time, so the
text is hardcoded directly into the final executable. This is why string
literals are fast and efficient. But these properties only come from the string
literal’s immutability. Unfortunately, we can’t put a blob of memory into the
binary for each piece of text whose size is unknown at compile time and whose
size might change while running the program.
对于字符串文字,我们在编译时知道内容,因此文本被直接硬编码到最终的可执行文件中。这就是字符串文字快速且高效的原因。但这些属性仅来自字符串文字的不变性。不幸的是,我们无法为每个文本块放入二进制内存,这些文本块的大小在编译时未知,并且在运行程序时其大小可能会发生变化。
With the String
type, in order to support a mutable, growable piece of text,
we need to allocate an amount of memory on the heap, unknown at compile time,
to hold the contents. This means:
对于String
类型,为了支持可变、可增长的文本片段,我们需要在堆上分配一定量的内存(在编译时未知)来保存内容。这意味着:
- The memory must be requested from the memory allocator at runtime.
必须在运行时向内存分配器请求内存。 - We need a way of returning this memory to the allocator when we’re done with
our
String
.
当我们使用完String
后,我们需要一种将内存返回给分配器的方法。
That first part is done by us: when we call String::from
, its implementation
requests the memory it needs. This is pretty much universal in programming
languages.
第一部分是由我们完成的:当我们调用String::from
时,它的实现会请求它所需的内存。这在编程语言中几乎是通用的。
However, the second part is different. In languages with a garbage collector
(GC), the GC keeps track of and cleans up memory that isn’t being used
anymore, and we don’t need to think about it. In most languages without a GC,
it’s our responsibility to identify when memory is no longer being used and to
call code to explicitly free it, just as we did to request it. Doing this
correctly has historically been a difficult programming problem. If we forget,
we’ll waste memory. If we do it too early, we’ll have an invalid variable. If
we do it twice, that’s a bug too. We need to pair exactly one allocate
with
exactly one free
.
然而,第二部分则不同。在带有垃圾收集器(GC)的语言中,GC 会跟踪并清理不再使用的内存,我们不需要考虑它。在大多数没有 GC 的语言中,我们有责任确定内存何时不再被使用,并调用代码来显式释放它,就像我们请求它一样。历史上,正确执行此操作一直是一个困难的编程问题。如果我们忘记了,我们就会浪费记忆。如果我们做得太早,我们就会得到一个无效的变量。如果我们这样做两次,这也是一个错误。我们需要将一个allocate
与一个free
配对。
Rust takes a different path: the memory is automatically returned once the
variable that owns it goes out of scope. Here’s a version of our scope example
from Listing 4-1 using a String
instead of a string literal:
Rust 采用了不同的路径:一旦拥有内存的变量超出范围,内存就会自动返回。下面是清单 4-1 中的作用域示例的一个版本,使用了String
而不是字符串文字:
There is a natural point at which we can return the memory our String
needs
to the allocator: when s
goes out of scope. When a variable goes out of
scope, Rust calls a special function for us. This function is called
drop
, and it’s where the author of String
can put
the code to return the memory. Rust calls drop
automatically at the closing
curly bracket.
有一个自然的点,我们可以将String
所需的内存返回给分配器:当s
超出范围时。当变量超出范围时,Rust 会为我们调用一个特殊的函数。这个函数称为drop
, String
的作者可以在其中放置返回内存的代码。 Rust 调用会自动drop
右大括号处。
Note: In C++, this pattern of deallocating resources at the end of an item’s
lifetime is sometimes called Resource Acquisition Is Initialization (RAII).
The drop
function in Rust will be familiar to you if you’ve used RAII
patterns.
注意:在 C++ 中,这种在项目生命周期结束时释放资源的模式有时称为资源获取即初始化 (RAII) 。如果您使用过 RAII 模式,那么您会熟悉 Rust 中的drop
函数。
This pattern has a profound impact on the way Rust code is written. It may seem
simple right now, but the behavior of code can be unexpected in more
complicated situations when we want to have multiple variables use the data
we’ve allocated on the heap. Let’s explore some of those situations now.
这种模式对 Rust 代码的编写方式产生了深远的影响。现在看起来可能很简单,但在更复杂的情况下,当我们想让多个变量使用我们在堆上分配的数据时,代码的行为可能会出乎意料。现在让我们探讨其中的一些情况。
Variables and Data Interacting with Move
与 Move 交互的变量和数据
Multiple variables can interact with the same data in different ways in Rust.
Let’s look at an example using an integer in Listing 4-2.
在 Rust 中,多个变量可以以不同的方式与相同的数据交互。让我们看一下清单 4-2 中使用整数的示例。
We can probably guess what this is doing: “bind the value 5
to x
; then make
a copy of the value in x
and bind it to y
.” We now have two variables, x
and y
, and both equal 5
. This is indeed what is happening, because integers
are simple values with a known, fixed size, and these two 5
values are pushed
onto the stack.
我们大概可以猜到这是在做什么:“将值5
绑定到x
;然后复制x
中的值并将其绑定到y
。”我们现在有两个变量x
和y
,并且都等于5
。这确实是正在发生的事情,因为整数是具有已知固定大小的简单值,并且这两个5
值被压入堆栈。
Now let’s look at the String
version:
现在让我们看看String
版本:
This looks very similar, so we might assume that the way it works would be the
same: that is, the second line would make a copy of the value in s1
and bind
it to s2
. But this isn’t quite what happens.
这看起来非常相似,因此我们可以假设它的工作方式是相同的:也就是说,第二行将复制s1
中的值并将其绑定到s2
。但实际情况并非如此。
Take a look at Figure 4-1 to see what is happening to String
under the
covers. A String
is made up of three parts, shown on the left: a pointer to
the memory that holds the contents of the string, a length, and a capacity.
This group of data is stored on the stack. On the right is the memory on the
heap that holds the contents.
看一下图 4-1,看看String
到底发生了什么。 String
由三部分组成,如左图所示:指向保存字符串内容的内存的指针、长度和容量。这组数据存放在栈中。右侧是堆上保存内容的内存。
The length is how much memory, in bytes, the contents of the String
are
currently using. The capacity is the total amount of memory, in bytes, that the
String
has received from the allocator. The difference between length and
capacity matters, but not in this context, so for now, it’s fine to ignore the
capacity.
长度是String
的内容当前使用的内存量(以字节为单位)。容量是String
从分配器接收的内存总量(以字节为单位)。长度和容量之间的差异很重要,但在这种情况下并不重要,所以现在可以忽略容量。
When we assign s1
to s2
, the String
data is copied, meaning we copy the
pointer, the length, and the capacity that are on the stack. We do not copy the
data on the heap that the pointer refers to. In other words, the data
representation in memory looks like Figure 4-2.
当我们将s1
分配给s2
时, String
数据被复制,这意味着我们复制堆栈上的指针、长度和容量。我们不会复制指针引用的堆上的数据。换句话说,内存中的数据表示如图 4-2 所示。
The representation does not look like Figure 4-3, which is what memory would
look like if Rust instead copied the heap data as well. If Rust did this, the
operation s2 = s1
could be very expensive in terms of runtime performance if
the data on the heap were large.
该表示形式与图 4-3不同,如果 Rust 也复制堆数据,内存就会是什么样子。如果 Rust 这样做,如果堆上的数据很大,则操作s2 = s1
在运行时性能方面可能会非常昂贵。
Earlier, we said that when a variable goes out of scope, Rust automatically
calls the drop
function and cleans up the heap memory for that variable. But
Figure 4-2 shows both data pointers pointing to the same location. This is a
problem: when s2
and s1
go out of scope, they will both try to free the
same memory. This is known as a double free error and is one of the memory
safety bugs we mentioned previously. Freeing memory twice can lead to memory
corruption, which can potentially lead to security vulnerabilities.
之前,我们说过,当变量超出范围时,Rust 会自动调用drop
函数并清理该变量的堆内存。但图 4-2 显示两个数据指针都指向同一位置。这是一个问题:当s2
和s1
超出范围时,它们都会尝试释放相同的内存。这称为双重释放错误,是我们之前提到的内存安全错误之一。两次释放内存可能会导致内存损坏,从而可能导致安全漏洞。
To ensure memory safety, after the line let s2 = s1;
, Rust considers s1
as
no longer valid. Therefore, Rust doesn’t need to free anything when s1
goes
out of scope. Check out what happens when you try to use s1
after s2
is
created; it won’t work:
为了保证内存安全,在该行之后let s2 = s1;
,Rust 认为s1
不再有效。因此,当s1
超出范围时,Rust 不需要释放任何东西。查看创建s2
后尝试使用s1
时会发生什么情况;它不会工作:
You’ll get an error like this because Rust prevents you from using the
invalidated reference:
你会得到这样的错误,因为 Rust 阻止你使用无效的引用:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0382]: borrow of moved value: `s1`
--> 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
If you’ve heard the terms shallow copy and deep copy while working with
other languages, the concept of copying the pointer, length, and capacity
without copying the data probably sounds like making a shallow copy. But
because Rust also invalidates the first variable, instead of being called a
shallow copy, it’s known as a move. In this example, we would say that s1
was moved into s2
. So, what actually happens is shown in Figure 4-4.
如果您在使用其他语言时听说过浅表复制和深表复制这两个术语,那么复制指针、长度和容量而不复制数据的概念可能听起来像是浅表复制。但因为 Rust 也会使第一个变量无效,所以它不被称为浅拷贝,而是被称为move 。在此示例中,我们会说s1
已移至s2
中。因此,实际发生的情况如图 4-4 所示。
That solves our problem! With only s2
valid, when it goes out of scope it
alone will free the memory, and we’re done.
这解决了我们的问题!只有s2
有效,当它超出范围时,它就会单独释放内存,我们就完成了。
In addition, there’s a design choice that’s implied by this: Rust will never
automatically create “deep” copies of your data. Therefore, any automatic
copying can be assumed to be inexpensive in terms of runtime performance.
此外,这还暗示着一个设计选择:Rust 永远不会自动创建数据的“深层”副本。因此,就运行时性能而言,任何自动复制都可以被认为是廉价的。
Variables and Data Interacting with Clone
与克隆交互的变量和数据
If we do want to deeply copy the heap data of the String
, not just the
stack data, we can use a common method called clone
. We’ll discuss method
syntax in Chapter 5, but because methods are a common feature in many
programming languages, you’ve probably seen them before.
如果我们确实想要深度复制String
的堆数据,而不仅仅是堆栈数据,我们可以使用一个称为clone
的常用方法。我们将在第 5 章中讨论方法语法,但由于方法是许多编程语言的常见功能,因此您以前可能已经见过它们。
Here’s an example of the clone
method in action:
以下是clone
方法的实际应用示例:
This works just fine and explicitly produces the behavior shown in Figure 4-3,
where the heap data does get copied.
这工作得很好,并显式地产生如图 4-3 所示的行为,其中堆数据确实被复制。
When you see a call to clone
, you know that some arbitrary code is being
executed and that code may be expensive. It’s a visual indicator that something
different is going on.
当您看到对clone
的调用时,您就知道正在执行一些任意代码,并且该代码可能很昂贵。这是一个视觉指示器,表明正在发生不同的事情。
Stack-Only Data: Copy 仅堆栈数据:复制
There’s another wrinkle we haven’t talked about yet. This code using
integers—part of which was shown in Listing 4-2—works and is valid:
还有另一个问题我们还没有讨论过。这段使用整数的代码(部分代码如清单 4-2 所示)可以工作并且有效:
But this code seems to contradict what we just learned: we don’t have a call to
clone
, but x
is still valid and wasn’t moved into y
.
但这段代码似乎与我们刚刚了解到的内容相矛盾:我们没有调用clone
,但x
仍然有效并且没有移动到y
中。
The reason is that types such as integers that have a known size at compile
time are stored entirely on the stack, so copies of the actual values are quick
to make. That means there’s no reason we would want to prevent x
from being
valid after we create the variable y
. In other words, there’s no difference
between deep and shallow copying here, so calling clone
wouldn’t do anything
different from the usual shallow copying, and we can leave it out.
原因是在编译时具有已知大小的整数等类型完全存储在堆栈中,因此可以快速创建实际值的副本。这意味着我们没有理由在创建变量y
后阻止x
有效。换句话说,这里的深拷贝和浅拷贝没有区别,所以调用clone
不会做任何与通常的浅拷贝不同的事情,我们可以省略它。
Rust has a special annotation called the Copy
trait that we can place on
types that are stored on the stack, as integers are (we’ll talk more about
traits in Chapter 10). If a type implements the Copy
trait, variables that use it do not move, but rather are trivially copied,
making them still valid after assignment to another variable.
Rust 有一个特殊的注释,称为Copy
特征,我们可以将其放置在存储在堆栈中的类型上,就像整数一样(我们将在第 10 章中详细讨论忽略特征)。如果某个类型实现了Copy
特征,则使用它的变量不会移动,而是会被简单地复制,从而使它们在分配给另一个变量后仍然有效。
Rust won’t let us annotate a type with Copy
if the type, or any of its parts,
has implemented the Drop
trait. If the type needs something special to happen
when the value goes out of scope and we add the Copy
annotation to that type,
we’ll get a compile-time error. To learn about how to add the Copy
annotation
to your type to implement the trait, see “Derivable
Traits” in Appendix C.
如果类型或其任何部分实现了Drop
特征,Rust 不会让我们用Copy
注释类型。如果当值超出范围时类型需要发生一些特殊的事情,并且我们向该类型添加Copy
注释,我们将收到编译时错误。要了解如何将Copy
注释添加到您的类型以实现特征,请参阅附录 C 中的“可导出特征”忽略。
So, what types implement the Copy
trait? You can check the documentation for
the given type to be sure, but as a general rule, any group of simple scalar
values can implement Copy
, and nothing that requires allocation or is some
form of resource can implement Copy
. Here are some of the types that
implement Copy
:
那么,哪些类型实现了Copy
特征呢?您可以检查给定类型的文档来确定,但作为一般规则,任何一组简单标量值都可以实现Copy
,并且任何需要分配或某种形式的资源都可以实现Copy
。以下是一些实现Copy
的类型:
- All the integer types, such as
u32
.
所有整数类型,例如u32
。 - The Boolean type,
bool
, with valuestrue
andfalse
.
布尔类型bool
,值为true
和false
。 - All the floating-point types, such as
f64
.
所有浮点类型,例如f64
。 - The character type,
char
.
字符类型char
。 - Tuples, if they only contain types that also implement
Copy
. For example,(i32, i32)
implementsCopy
, but(i32, String)
does not.
元组,如果它们仅包含也实现Copy
的类型。例如,(i32, i32)
实现Copy
,但(i32, String)
没有。
Ownership and Functions 所有权和职能
The mechanics of passing a value to a function are similar to those when
assigning a value to a variable. Passing a variable to a function will move or
copy, just as assignment does. Listing 4-3 has an example with some annotations
showing where variables go into and out of scope.
将值传递给函数的机制与将值分配给变量时的机制类似。将变量传递给函数将会移动或复制,就像赋值一样。清单 4-3 有一个示例,其中一些注释显示了变量进入和超出范围的位置。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let s = String::from("hello"); // s comes into scope
takes_ownership(s); // s's value moves into the function...
// ... and so is no longer valid here
let x = 5; // x comes into scope
makes_copy(x); // x would move into the function,
// but i32 is Copy, so it's okay to still
// use x afterward
} // Here, x goes out of scope, then s. But because s's value was moved, nothing
// special happens.
fn takes_ownership(some_string: String) { // some_string comes into scope
println!("{some_string}");
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) { // some_integer comes into scope
println!("{some_integer}");
} // Here, some_integer goes out of scope. Nothing special happens.
If we tried to use s
after the call to takes_ownership
, Rust would throw a
compile-time error. These static checks protect us from mistakes. Try adding
code to main
that uses s
and x
to see where you can use them and where
the ownership rules prevent you from doing so.
如果我们在调用takes_ownership
之后尝试使用s
,Rust 会抛出编译时错误。这些静态检查可以保护我们免受错误的影响。尝试将使用s
和x
代码添加到main
中,看看可以在哪里使用它们以及所有权规则在哪里禁止您这样做。
Return Values and Scope 返回值和范围
Returning values can also transfer ownership. Listing 4-4 shows an example of a
function that returns some value, with similar annotations as those in Listing
4-3.
返回值也可以转移所有权。清单 4-4 显示了一个返回某个值的函数示例,其注释与清单 4-3 中的注释类似。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1
let s2 = String::from("hello"); // s2 comes into scope
let s3 = takes_and_gives_back(s2); // s2 is moved into
// takes_and_gives_back, which also
// moves its return value into s3
} // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing
// happens. s1 goes out of scope and is dropped.
fn gives_ownership() -> String { // gives_ownership will move its
// return value into the function
// that calls it
let some_string = String::from("yours"); // some_string comes into scope
some_string // some_string is returned and
// moves out to the calling
// function
}
// This function takes a String and returns one
fn takes_and_gives_back(a_string: String) -> String { // a_string comes into
// scope
a_string // a_string is returned and moves out to the calling function
}
The ownership of a variable follows the same pattern every time: assigning a
value to another variable moves it. When a variable that includes data on the
heap goes out of scope, the value will be cleaned up by drop
unless ownership
of the data has been moved to another variable.
变量的所有权每次都遵循相同的模式:将值分配给另一个变量会移动它。当包含堆上数据的变量超出范围时,该值将被drop
清理,除非数据的所有权已移至另一个变量。
While this works, taking ownership and then returning ownership with every
function is a bit tedious. What if we want to let a function use a value but
not take ownership? It’s quite annoying that anything we pass in also needs to
be passed back if we want to use it again, in addition to any data resulting
from the body of the function that we might want to return as well.
虽然这可行,但获取所有权然后返回每个函数的所有权有点乏味。如果我们想让一个函数使用一个值但不获取所有权怎么办?非常烦人的是,如果我们想再次使用我们传入的任何内容,除了我们可能想要返回的函数体产生的任何数据之外,还需要传回它。
Rust does let us return multiple values using a tuple, as shown in Listing 4-5.
Rust 确实允许我们使用元组返回多个值,如清单 4-5 所示。
Filename: src/main.rs 文件名:src/main.rs
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) -> (String, usize) {
let length = s.len(); // len() returns the length of a String
(s, length)
}
But this is too much ceremony and a lot of work for a concept that should be
common. Luckily for us, Rust has a feature for using a value without
transferring ownership, called references.
但对于一个应该通用的概念来说,这太过仪式和大量工作。对我们来说幸运的是,Rust 有一个使用值而不转移所有权的功能,称为引用。
References and Borrowing 参考文献和借用
The issue with the tuple code in Listing 4-5 is that we have to return the
String
to the calling function so we can still use the String
after the
call to calculate_length
, because the String
was moved into
calculate_length
. Instead, we can provide a reference to the String
value.
A reference is like a pointer in that it’s an address we can follow to access
the data stored at that address; that data is owned by some other variable.
Unlike a pointer, a reference is guaranteed to point to a valid value of a
particular type for the life of that reference.
清单 4-5 中元组代码的问题在于,我们必须将String
返回给调用函数,这样我们在调用calculate_length
之后仍然可以使用该String
,因为该String
已移至calculate_length
中。相反,我们可以提供对String
值的引用。引用就像一个指针,我们可以根据它来访问存储在该地址的数据;该数据由其他一些变量拥有。与指针不同,引用保证在该引用的生命周期内指向特定类型的有效值。
Here is how you would define and use a calculate_length
function that has a
reference to an object as a parameter instead of taking ownership of the value:
以下是定义和使用calculate_length
函数的方法,该函数将对对象的引用作为参数,而不是获取值的所有权:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{s1}' is {len}.");
}
fn calculate_length(s: &String) -> usize {
s.len()
}
First, notice that all the tuple code in the variable declaration and the
function return value is gone. Second, note that we pass &s1
into
calculate_length
and, in its definition, we take &String
rather than
String
. These ampersands represent references, and they allow you to refer
to some value without taking ownership of it. Figure 4-5 depicts this concept.
首先,请注意变量声明和函数返回值中的所有元组代码都消失了。其次,请注意,我们将&s1
传递给calculate_length
,并且在其定义中,我们采用&String
而不是String
。这些 & 符号代表引用,它们允许您引用某些值而不获取它的所有权。图 4-5 描述了这个概念。
Note: The opposite of referencing by using &
is dereferencing, which is
accomplished with the dereference operator, *
. We’ll see some uses of the
dereference operator in Chapter 8 and discuss details of dereferencing in
Chapter 15.
注意:与使用&
引用相反的是取消引用,这是通过取消引用运算符*
完成的。我们将在第 8 章中看到解引用运算符的一些用法,并在第 15 章中讨论解引用的细节。
Let’s take a closer look at the function call here:
让我们仔细看看这里的函数调用:
The &s1
syntax lets us create a reference that refers to the value of s1
but does not own it. Because it does not own it, the value it points to will
not be dropped when the reference stops being used.&s1
语法允许我们创建一个引用s1
的值但不拥有它。因为它不拥有它,所以当引用停止使用时,它指向的值不会被删除。
Likewise, the signature of the function uses &
to indicate that the type of
the parameter s
is a reference. Let’s add some explanatory annotations:
同样,函数的签名使用&
来指示参数s
的类型是引用。让我们添加一些解释性注释:
The scope in which the variable s
is valid is the same as any function
parameter’s scope, but the value pointed to by the reference is not dropped
when s
stops being used, because s
doesn’t have ownership. When functions
have references as parameters instead of the actual values, we won’t need to
return the values in order to give back ownership, because we never had
ownership.
变量s
有效范围与任何函数参数的范围相同,但当s
停止使用时,引用指向的值不会被删除,因为s
没有所有权。当函数将引用而不是实际值作为参数时,我们不需要返回值来归还所有权,因为我们从未拥有所有权。
We call the action of creating a reference borrowing. As in real life, if a
person owns something, you can borrow it from them. When you’re done, you have
to give it back. You don’t own it.
我们将创建引用的操作称为借用。就像在现实生活中一样,如果一个人拥有某样东西,你可以向他们借用。当你完成后,你必须把它还给你。你不拥有它。
So, what happens if we try to modify something we’re borrowing? Try the code in
Listing 4-6. Spoiler alert: it doesn’t work!
那么,如果我们尝试修改借用的东西会发生什么?尝试清单 4-6 中的代码。剧透警告:这不起作用!
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let s = String::from("hello");
change(&s);
}
fn change(some_string: &String) {
some_string.push_str(", world");
}
Here’s the error: 这是错误:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
--> src/main.rs:8:5
|
8 | some_string.push_str(", world");
| ^^^^^^^^^^^ `some_string` is a `&` 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: &mut String) {
| +++
For more information about this error, try `rustc --explain E0596`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
Just as variables are immutable by default, so are references. We’re not
allowed to modify something we have a reference to.
正如变量在默认情况下是不可变的一样,引用也是如此。我们不允许修改我们所引用的内容。
Mutable References 可变引用
We can fix the code from Listing 4-6 to allow us to modify a borrowed value
with just a few small tweaks that use, instead, a mutable reference:
我们可以修复清单 4-6 中的代码,只需要进行一些小调整即可修改借用的值,而这些调整使用的是可变引用:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let mut s = String::from("hello");
change(&mut s);
}
fn change(some_string: &mut String) {
some_string.push_str(", world");
}
First we change s
to be mut
. Then we create a mutable reference with &mut s
where we call the change
function, and update the function signature to
accept a mutable reference with some_string: &mut String
. This makes it very
clear that the change
function will mutate the value it borrows.
首先我们将s
更改为mut
。然后,我们使用&mut s
创建一个可变引用,在其中调用change
函数,并更新函数签名以接受使用some_string: &mut String
可变引用。这非常清楚地表明, change
函数将改变它借用的值。
Mutable references have one big restriction: if you have a mutable reference to
a value, you can have no other references to that value. This code that
attempts to create two mutable references to s
will fail:
可变引用有一个很大的限制:如果您有一个对某个值的可变引用,则不能有对该值的其他引用。尝试创建两个对s
的可变引用的代码将失败:
Filename: src/main.rs 文件名:src/main.rs
Here’s the error: 这是错误:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0499]: cannot borrow `s` as mutable more than once at a time
--> src/main.rs:5:14
|
4 | let r1 = &mut s;
| ------ first mutable borrow occurs here
5 | let r2 = &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
This error says that this code is invalid because we cannot borrow s
as
mutable more than once at a time. The first mutable borrow is in r1
and must
last until it’s used in the println!
, but between the creation of that
mutable reference and its usage, we tried to create another mutable reference
in r2
that borrows the same data as r1
.
此错误表明此代码无效,因为我们一次不能多次借用s
作为可变对象。第一个可变借用位于r1
中,并且必须持续到在println!
,但在创建该可变引用及其使用之间,我们尝试在r2
中创建另一个可变引用,借用与r1
相同的数据。
The restriction preventing multiple mutable references to the same data at the
same time allows for mutation but in a very controlled fashion. It’s something
that new Rustaceans struggle with because most languages let you mutate
whenever you’d like. The benefit of having this restriction is that Rust can
prevent data races at compile time. A data race is similar to a race
condition and happens when these three behaviors occur:
防止同时对同一数据进行多个可变引用的限制允许突变,但以非常受控的方式进行。这是新的 Rustaceans 所面临的问题,因为大多数语言都允许你随时进行变异。具有此限制的好处是 Rust 可以防止编译时的数据竞争。数据竞争与竞争条件类似,当发生以下三种行为时就会发生:
- Two or more pointers access the same data at the same time.
两个或多个指针同时访问相同的数据。 - At least one of the pointers is being used to write to the data.
至少有一个指针用于写入数据。 - There’s no mechanism being used to synchronize access to the data.
没有使用任何机制来同步对数据的访问。
Data races cause undefined behavior and can be difficult to diagnose and fix
when you’re trying to track them down at runtime; Rust prevents this problem by
refusing to compile code with data races!
数据争用会导致未定义的行为,并且当您尝试在运行时追踪数据争用时,可能很难诊断和修复; Rust 通过拒绝编译带有数据竞争的代码来防止这个问题!
As always, we can use curly brackets to create a new scope, allowing for
multiple mutable references, just not simultaneous ones:
与往常一样,我们可以使用大括号创建一个新范围,允许多个可变引用,但不能同时引用:
Rust enforces a similar rule for combining mutable and immutable references.
This code results in an error:
Rust 强制执行类似的规则来组合可变和不可变引用。此代码会导致错误:
Here’s the error: 这是错误:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:6:14
|
4 | let r1 = &s; // no problem
| -- immutable borrow occurs here
5 | let r2 = &s; // no problem
6 | let r3 = &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
Whew! We also cannot have a mutable reference while we have an immutable one
to the same value.
哇!当我们拥有相同值的不可变引用时,我们也不能拥有可变引用。
Users of an immutable reference don’t expect the value to suddenly change out
from under them! However, multiple immutable references are allowed because no
one who is just reading the data has the ability to affect anyone else’s
reading of the data.
不可变引用的用户不会期望其值会突然发生变化!然而,多个不可变引用是允许的,因为仅仅读取数据的人没有能力影响其他人对数据的读取。
Note that a reference’s scope starts from where it is introduced and continues
through the last time that reference is used. For instance, this code will
compile because the last usage of the immutable references, the println!
,
occurs before the mutable reference is introduced:
请注意,引用的范围从引入它的地方开始,一直持续到上次使用该引用时为止。例如,这段代码将会编译,因为最后一次使用了不可变引用println!
,发生在引入可变引用之前:
The scopes of the immutable references r1
and r2
end after the println!
where they are last used, which is before the mutable reference r3
is
created. These scopes don’t overlap, so this code is allowed: the compiler can
tell that the reference is no longer being used at a point before the end of
the scope.
不可变引用r1
和r2
的范围在println!
之后结束。它们最后一次使用的位置是在创建可变引用r3
之前。这些作用域不重叠,因此允许使用此代码:编译器可以判断在作用域结束之前的某个点不再使用该引用。
Even though borrowing errors may be frustrating at times, remember that it’s
the Rust compiler pointing out a potential bug early (at compile time rather
than at runtime) and showing you exactly where the problem is. Then you don’t
have to track down why your data isn’t what you thought it was.
尽管借用错误有时可能会令人沮丧,但请记住,Rust 编译器会尽早(在编译时而不是运行时)指出潜在的错误,并向您准确显示问题所在。这样您就不必追查为什么您的数据与您想象的不同。
Dangling References 悬空引用
In languages with pointers, it’s easy to erroneously create a dangling
pointer—a pointer that references a location in memory that may have been
given to someone else—by freeing some memory while preserving a pointer to that
memory. In Rust, by contrast, the compiler guarantees that references will
never be dangling references: if you have a reference to some data, the
compiler will ensure that the data will not go out of scope before the
reference to the data does.
在带有指针的语言中,通过释放一些内存同时保留指向该内存的指针,很容易错误地创建悬空指针(引用内存中可能已分配给其他人的位置的指针)。相比之下,在 Rust 中,编译器保证引用永远不会是悬空引用:如果您引用了某些数据,编译器将确保数据不会在数据引用超出范围之前超出范围。
Let’s try to create a dangling reference to see how Rust prevents them with a
compile-time error:
让我们尝试创建一个悬空引用,看看 Rust 如何通过编译时错误来防止它们:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
Here’s the error: 这是错误:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0106]: missing lifetime specifier
--> src/main.rs:5:16
|
5 | fn dangle() -> &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() -> &'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
5 - fn dangle() -> &String {
5 + fn dangle() -> String {
|
error[E0515]: cannot return reference to local variable `s`
--> src/main.rs:8:5
|
8 | &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
This error message refers to a feature we haven’t covered yet: lifetimes. We’ll
discuss lifetimes in detail in Chapter 10. But, if you disregard the parts
about lifetimes, the message does contain the key to why this code is a problem:
此错误消息涉及我们尚未介绍的功能:生命周期。我们将在第 10 章中详细讨论生命周期。但是,如果您忽略有关生命周期的部分,该消息确实包含了为什么此代码存在问题的关键:
this function's return type contains a borrowed value, but there is no value
for it to be borrowed from
Let’s take a closer look at exactly what’s happening at each stage of our
dangle
code:
让我们仔细看看dangle
代码的每个阶段到底发生了什么:
Filename: src/main.rs 文件名:src/main.rs
Because s
is created inside dangle
, when the code of dangle
is finished,
s
will be deallocated. But we tried to return a reference to it. That means
this reference would be pointing to an invalid String
. That’s no good! Rust
won’t let us do this.
因为s
是在dangle
内部创建的,所以当dangle
的代码完成时, s
将被释放。但我们试图返回对它的引用。这意味着此引用将指向无效的String
。这样可不行啊! Rust 不会让我们这样做。
The solution here is to return the String
directly:
这里的解决方案是直接返回String
:
This works without any problems. Ownership is moved out, and nothing is
deallocated.
这工作没有任何问题。所有权被移出,并且没有任何内容被释放。
The Rules of References 参考文献规则
Let’s recap what we’ve discussed about references:
让我们回顾一下我们讨论过的关于参考文献的内容:
- At any given time, you can have either one mutable reference or any
number of immutable references.
在任何给定时间,您可以拥有一个可变引用或任意数量的不可变引用。 - References must always be valid.
参考文献必须始终有效。
Next, we’ll look at a different kind of reference: slices.
接下来,我们将看看另一种不同的引用:切片。
The Slice Type 切片类型
Slices let you reference a contiguous sequence of elements in a
collection rather than the whole collection. A
slice is a kind of reference, so it does not have ownership.
切片允许您引用集合中连续的元素序列,而不是整个集合。切片是一种引用,因此它没有所有权。
Here’s a small programming problem: write a function that takes a string of
words separated by spaces and returns the first word it finds in that string.
If the function doesn’t find a space in the string, the whole string must be
one word, so the entire string should be returned.
这是一个小编程问题:编写一个函数,该函数接受由空格分隔的单词字符串,并返回在该字符串中找到的第一个单词。如果函数在字符串中没有找到空格,则整个字符串必须是一个单词,因此应返回整个字符串。
Let’s work through how we’d write the signature of this function without using
slices, to understand the problem that slices will solve:
让我们看看如何在不使用切片的情况下编写该函数的签名,以了解切片将解决的问题:
fn first_word(s: &String) -> ?
The first_word
function has a &String
as a parameter. We don’t want
ownership, so this is fine. But what should we return? We don’t really have a
way to talk about part of a string. However, we could return the index of the
end of the word, indicated by a space. Let’s try that, as shown in Listing 4-7.first_word
函数有一个&String
作为参数。我们不需要所有权,所以这很好。但我们应该返回什么?我们确实没有办法谈论字符串的一部分。但是,我们可以返回单词末尾的索引,以空格表示。让我们尝试一下,如清单 4-7 所示。
Filename: src/main.rs 文件名:src/main.rs
Because we need to go through the String
element by element and check whether
a value is a space, we’ll convert our String
to an array of bytes using the
as_bytes
method.
因为我们需要逐个元素地遍历String
并检查值是否为空格,所以我们将使用as_bytes
方法将String
转换为字节数组。
Next, we create an iterator over the array of bytes using the iter
method:
接下来,我们使用iter
方法在字节数组上创建一个迭代器:
We’ll discuss iterators in more detail in Chapter 13.
For now, know that iter
is a method that returns each element in a collection
and that enumerate
wraps the result of iter
and returns each element as
part of a tuple instead. The first element of the tuple returned from
enumerate
is the index, and the second element is a reference to the element.
This is a bit more convenient than calculating the index ourselves.
我们将在第 13 章中更详细地讨论迭代器。现在,我们知道iter
是一个返回集合中每个元素的方法,并且enumerate
包装了iter
的结果并将每个元素作为元组的一部分返回。 enumerate
返回的元组的第一个元素是索引,第二个元素是对该元素的引用。这比我们自己计算指数方便一点。
Because the enumerate
method returns a tuple, we can use patterns to
destructure that tuple. We’ll be discussing patterns more in Chapter
6. In the for
loop, we specify a pattern that has i
for the index in the tuple and &item
for the single byte in the tuple.
Because we get a reference to the element from .iter().enumerate()
, we use
&
in the pattern.
因为enumerate
方法返回一个元组,所以我们可以使用模式来解构该元组。我们将在第 6 章中更多地讨论忽略模式。在for
循环中,我们指定一个模式,其中i
为元组中的索引, &item
为元组中的单个字节。因为我们从.iter().enumerate()
获取对元素的引用,所以我们在模式中使用&
。
Inside the for
loop, we search for the byte that represents the space by
using the byte literal syntax. If we find a space, we return the position.
Otherwise, we return the length of the string by using s.len()
.
在for
循环内,我们使用字节文字语法搜索表示空间的字节。如果我们找到一个空间,我们就会返回该位置。否则,我们使用s.len()
返回字符串的长度。
We now have a way to find out the index of the end of the first word in the
string, but there’s a problem. We’re returning a usize
on its own, but it’s
only a meaningful number in the context of the &String
. In other words,
because it’s a separate value from the String
, there’s no guarantee that it
will still be valid in the future. Consider the program in Listing 4-8 that
uses the first_word
function from Listing 4-7.
我们现在有办法找出字符串中第一个单词末尾的索引,但是有一个问题。我们自己返回一个usize
,但它只是&String
上下文中的一个有意义的数字。换句话说,因为它是与String
不同的值,所以不能保证它在将来仍然有效。考虑清单 4-8 中的程序,它使用清单 4-7 中的first_word
函数。
Filename: src/main.rs 文件名:src/main.rs
This program compiles without any errors and would also do so if we used word
after calling s.clear()
. Because word
isn’t connected to the state of s
at all, word
still contains the value 5
. We could use that value 5
with
the variable s
to try to extract the first word out, but this would be a bug
because the contents of s
have changed since we saved 5
in word
.
该程序编译时没有任何错误,如果我们在调用s.clear()
后使用word
也会这样做。因为word
根本没有连接到s
的状态,所以word
仍然包含值5
。我们可以使用值5
和变量s
来尝试提取第一个单词,但这将是一个错误,因为自从我们在word
中保存5
以来s
的内容已经发生了变化。
Having to worry about the index in word
getting out of sync with the data in
s
is tedious and error prone! Managing these indices is even more brittle if
we write a second_word
function. Its signature would have to look like this:
不得不担心word
中的索引与s
中的数据不同步是乏味且容易出错的!如果我们编写second_word
函数,管理这些索引会更加脆弱。它的签名必须如下所示:
fn second_word(s: &String) -> (usize, usize) {
Now we’re tracking a starting and an ending index, and we have even more
values that were calculated from data in a particular state but aren’t tied to
that state at all. We have three unrelated variables floating around that need
to be kept in sync.
现在我们正在跟踪开始和结束索引,并且我们有更多的值是根据特定状态的数据计算出来的,但根本与该状态无关。我们有三个不相关的变量需要保持同步。
Luckily, Rust has a solution to this problem: string slices.
幸运的是,Rust 有一个解决这个问题的方法:字符串切片。
String Slices 字符串切片
A string slice is a reference to part of a String
, and it looks like this:
字符串切片是对String
的一部分的引用,它看起来像这样:
Rather than a reference to the entire String
, hello
is a reference to a
portion of the String
, specified in the extra [0..5]
bit. We create slices
using a range within brackets by specifying [starting_index..ending_index]
,
where starting_index
is the first position in the slice and ending_index
is
one more than the last position in the slice. Internally, the slice data
structure stores the starting position and the length of the slice, which
corresponds to ending_index
minus starting_index
. So, in the case of let world = &s[6..11];
, world
would be a slice that contains a pointer to the
byte at index 6 of s
with a length value of 5
.hello
不是对整个String
的引用,而是对String
的一部分的引用,在额外的[0..5]
位中指定。我们通过指定[starting_index..ending_index]
使用括号内的范围创建切片,其中starting_index
是切片中的第一个位置, ending_index
比切片中的最后一个位置多一个。在内部,切片数据结构存储切片的起始位置和长度,对应于ending_index
减去starting_index
。因此,在let world = &s[6..11];
的情况下, world
将是一个切片,其中包含指向s
索引 6 处的字节的指针,长度值为5
。
Figure 4-6 shows this in a diagram.
图 4-6 以图表形式展示了这一点。
With Rust’s ..
range syntax, if you want to start at index 0, you can drop
the value before the two periods. In other words, these are equal:
使用 Rust 的..
range 语法,如果您想从索引 0 开始,则可以删除两个句点之前的值。换句话说,它们是相等的:
By the same token, if your slice includes the last byte of the String
, you
can drop the trailing number. That means these are equal:
同样,如果您的切片包含String
的最后一个字节,则可以删除尾随数字。这意味着它们是相等的:
You can also drop both values to take a slice of the entire string. So these
are equal:
您还可以删除这两个值以获取整个字符串的一部分。所以这些是相等的:
Note: String slice range indices must occur at valid UTF-8 character
boundaries. If you attempt to create a string slice in the middle of a
multibyte character, your program will exit with an error. For the purposes
of introducing string slices, we are assuming ASCII only in this section; a
more thorough discussion of UTF-8 handling is in the “Storing UTF-8 Encoded
Text with Strings” section of Chapter 8.
注意:字符串切片范围索引必须出现在有效的 UTF-8 字符边界处。如果您尝试在多字节字符的中间创建字符串切片,您的程序将错误退出。为了介绍字符串切片,我们在本节中仅假设 ASCII;关于 UTF-8 处理的更全面的讨论在第 8 章的“用字符串存储 UTF-8 编码文本”忽略部分。
With all this information in mind, let’s rewrite first_word
to return a
slice. The type that signifies “string slice” is written as &str
:
考虑到所有这些信息,让我们重写first_word
以返回一个切片。表示“字符串切片”的类型写为&str
:
Filename: src/main.rs 文件名:src/main.rs
We get the index for the end of the word the same way we did in Listing 4-7, by
looking for the first occurrence of a space. When we find a space, we return a
string slice using the start of the string and the index of the space as the
starting and ending indices.
我们以与清单 4-7 中相同的方式获取单词结尾的索引,即查找第一次出现的空格。当我们找到一个空格时,我们使用字符串的开头和空格的索引作为开始和结束索引返回一个字符串切片。
Now when we call first_word
, we get back a single value that is tied to the
underlying data. The value is made up of a reference to the starting point of
the slice and the number of elements in the slice.
现在,当我们调用first_word
时,我们会返回一个与底层数据相关的单个值。该值由对切片起始点的引用和切片中元素的数量组成。
Returning a slice would also work for a second_word
function:
返回切片也适用于second_word
函数:
fn second_word(s: &String) -> &str {
We now have a straightforward API that’s much harder to mess up because the
compiler will ensure the references into the String
remain valid. Remember
the bug in the program in Listing 4-8, when we got the index to the end of the
first word but then cleared the string so our index was invalid? That code was
logically incorrect but didn’t show any immediate errors. The problems would
show up later if we kept trying to use the first word index with an emptied
string. Slices make this bug impossible and let us know we have a problem with
our code much sooner. Using the slice version of first_word
will throw a
compile-time error:
我们现在有了一个简单的 API,更难弄乱,因为编译器将确保对String
引用保持有效。还记得清单 4-8 中程序中的错误吗?当时我们获得了第一个单词末尾的索引,但随后清除了字符串,因此我们的索引无效了?该代码在逻辑上不正确,但没有显示任何直接错误。如果我们继续尝试将第一个单词索引与空字符串一起使用,问题稍后就会出现。切片使这个错误不可能发生,并让我们更快地知道我们的代码有问题。使用first_word
的切片版本将引发编译时错误:
Filename: src/main.rs 文件名:src/main.rs
Here’s the compiler error:
这是编译器错误:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:18:5
|
16 | let word = first_word(&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
Recall from the borrowing rules that if we have an immutable reference to
something, we cannot also take a mutable reference. Because clear
needs to
truncate the String
, it needs to get a mutable reference. The println!
after the call to clear
uses the reference in word
, so the immutable
reference must still be active at that point. Rust disallows the mutable
reference in clear
and the immutable reference in word
from existing at the
same time, and compilation fails. Not only has Rust made our API easier to use,
but it has also eliminated an entire class of errors at compile time!
回想一下借用规则,如果我们对某个东西有一个不可变的引用,我们就不能同时使用一个可变的引用。因为clear
需要截断String
,所以它需要获得一个可变引用。 println!
在调用clear
之后使用word
中的引用,因此不可变引用此时必须仍然处于活动状态。 Rust不允许clear
中的可变引用和word
中的不可变引用同时存在,并且编译失败。 Rust 不仅使我们的 API 更易于使用,而且还消除了编译时的一整类错误!
String Literals as Slices
字符串文字作为切片
Recall that we talked about string literals being stored inside the binary. Now
that we know about slices, we can properly understand string literals:
回想一下,我们讨论过存储在二进制文件中的字符串文字。现在我们了解了切片,我们可以正确理解字符串文字:
The type of s
here is &str
: it’s a slice pointing to that specific point of
the binary. This is also why string literals are immutable; &str
is an
immutable reference.
这里s
的类型是&str
:它是一个指向二进制文件的特定点的切片。这也是字符串文字不可变的原因; &str
是一个不可变的引用。
String Slices as Parameters
字符串切片作为参数
Knowing that you can take slices of literals and String
values leads us to
one more improvement on first_word
, and that’s its signature:
知道你可以获取文字和String
值的切片,这使我们对first_word
进行了进一步的改进,这就是它的签名:
fn first_word(s: &String) -> &str {
A more experienced Rustacean would write the signature shown in Listing 4-9
instead because it allows us to use the same function on both &String
values
and &str
values.
更有经验的 Rustacean 会编写清单 4-9 中所示的签名,因为它允许我们对&String
值和&str
值使用相同的函数。
If we have a string slice, we can pass that directly. If we have a String
, we
can pass a slice of the String
or a reference to the String
. This
flexibility takes advantage of deref coercions, a feature we will cover in the
“Implicit Deref Coercions with Functions and
Methods” section of Chapter 15.
如果我们有一个字符串切片,我们可以直接传递它。如果我们有一个String
,我们可以传递String
的切片或对String
引用。这种灵活性利用了deref 强制转换,我们将在第 15 章的“使用函数和方法进行隐式 Deref 强制转换”忽略部分中介绍该功能。
Defining a function to take a string slice instead of a reference to a String
makes our API more general and useful without losing any functionality:
定义一个函数来获取字符串切片而不是对String
的引用,使我们的 API 更加通用和有用,而不会丢失任何功能:
Filename: src/main.rs 文件名:src/main.rs
Other Slices 其他切片
String slices, as you might imagine, are specific to strings. But there’s a
more general slice type too. Consider this array:
正如您可能想象的那样,字符串切片特定于字符串。但还有更通用的切片类型。考虑这个数组:
Just as we might want to refer to part of a string, we might want to refer to
part of an array. We’d do so like this:
正如我们可能想要引用字符串的一部分一样,我们可能想要引用数组的一部分。我们会这样做:
This slice has the type &[i32]
. It works the same way as string slices do, by
storing a reference to the first element and a length. You’ll use this kind of
slice for all sorts of other collections. We’ll discuss these collections in
detail when we talk about vectors in Chapter 8.
该切片的类型为&[i32]
。它的工作方式与字符串切片相同,通过存储对第一个元素的引用和长度。您将把这种切片用于各种其他集合。当我们在第 8 章讨论向量时,我们将详细讨论这些集合。
Summary 概括
The concepts of ownership, borrowing, and slices ensure memory safety in Rust
programs at compile time. The Rust language gives you control over your memory
usage in the same way as other systems programming languages, but having the
owner of data automatically clean up that data when the owner goes out of scope
means you don’t have to write and debug extra code to get this control.
所有权、借用和切片的概念确保 Rust 程序在编译时的内存安全。 Rust 语言让您能够以与其他系统编程语言相同的方式控制内存使用情况,但是当数据所有者超出范围时,让数据所有者自动清理该数据意味着您无需编写和调试额外的代码来获得这个控制权。
Ownership affects how lots of other parts of Rust work, so we’ll talk about
these concepts further throughout the rest of the book. Let’s move on to
Chapter 5 and look at grouping pieces of data together in a struct
.
所有权会影响 Rust 许多其他部分的工作方式,因此我们将在本书的其余部分进一步讨论这些概念。让我们继续第 5 章,看看如何将数据片段分组到一个struct
中。
Using Structs to Structure Related Data
使用结构体构建相关数据
A struct, or structure, is a custom data type that lets you package
together and name multiple related values that make up a meaningful group. If
you’re familiar with an object-oriented language, a struct is like an
object’s data attributes. In this chapter, we’ll compare and contrast tuples
with structs to build on what you already know and demonstrate when structs are
a better way to group data.
struct或Structure是一种自定义数据类型,可让您将多个相关值打包并命名,从而组成一个有意义的组。如果您熟悉面向对象的语言,结构就像对象的数据属性。在本章中,我们将在您已知的基础上对元组与结构进行比较和对比,并演示结构何时是更好的数据分组方式。
We’ll demonstrate how to define and instantiate structs. We’ll discuss how to
define associated functions, especially the kind of associated functions called
methods, to specify behavior associated with a struct type. Structs and enums
(discussed in Chapter 6) are the building blocks for creating new types in your
program’s domain to take full advantage of Rust’s compile-time type checking.
我们将演示如何定义和实例化结构。我们将讨论如何定义关联函数,特别是称为方法的关联函数,以指定与结构类型关联的行为。结构体和枚举(在第 6 章中讨论)是在程序域中创建新类型的构建块,以充分利用 Rust 的编译时类型检查。
Defining and Instantiating Structs
定义和实例化结构
Structs are similar to tuples, discussed in “The Tuple Type” section, in that both hold multiple related values. Like tuples, the
pieces of a struct can be different types. Unlike with tuples, in a struct
you’ll name each piece of data so it’s clear what the values mean. Adding these
names means that structs are more flexible than tuples: you don’t have to rely
on the order of the data to specify or access the values of an instance.
结构体与元组类似(在“元组类型”忽略部分中讨论),因为两者都保存多个相关值。与元组一样,结构体的各个部分可以是不同的类型。与元组不同,在结构体中,您将为每条数据命名,以便清楚地了解这些值的含义。添加这些名称意味着结构比元组更灵活:您不必依赖数据的顺序来指定或访问实例的值。
To define a struct, we enter the keyword struct
and name the entire struct. A
struct’s name should describe the significance of the pieces of data being
grouped together. Then, inside curly brackets, we define the names and types of
the pieces of data, which we call fields. For example, Listing 5-1 shows a
struct that stores information about a user account.
要定义结构,我们输入关键字struct
并命名整个结构。结构体的名称应该描述分组在一起的数据片段的重要性。然后,在大括号内,我们定义数据块的名称和类型,我们将其称为fields 。例如,清单 5-1 显示了一个存储有关用户帐户信息的结构体。
Filename: src/main.rs 文件名:src/main.rs
To use a struct after we’ve defined it, we create an instance of that struct
by specifying concrete values for each of the fields. We create an instance by
stating the name of the struct and then add curly brackets containing key:
value pairs, where the keys are the names of the fields and the values are the
data we want to store in those fields. We don’t have to specify the fields in
the same order in which we declared them in the struct. In other words, the
struct definition is like a general template for the type, and instances fill
in that template with particular data to create values of the type. For
example, we can declare a particular user as shown in Listing 5-2.
要在定义结构后使用它,我们通过为每个字段指定具体值来创建该结构的实例。我们通过声明结构体的名称来创建一个实例,然后添加包含键:值对的大括号,其中键是字段的名称,值是我们要存储在这些字段中的数据。我们不必按照在结构中声明字段的顺序指定字段。换句话说,结构定义就像该类型的通用模板,实例使用特定数据填充该模板以创建该类型的值。例如,我们可以声明一个特定的用户,如清单 5-2 所示。
Filename: src/main.rs 文件名:src/main.rs
To get a specific value from a struct, we use dot notation. For example, to
access this user’s email address, we use user1.email
. If the instance is
mutable, we can change a value by using the dot notation and assigning into a
particular field. Listing 5-3 shows how to change the value in the email
field of a mutable User
instance.
为了从结构中获取特定值,我们使用点表示法。例如,要访问该用户的电子邮件地址,我们使用user1.email
。如果实例是可变的,我们可以通过使用点符号并分配到特定字段来更改值。清单 5-3 显示了如何更改可变User
实例的email
字段中的值。
Filename: src/main.rs 文件名:src/main.rs
Note that the entire instance must be mutable; Rust doesn’t allow us to mark
only certain fields as mutable. As with any expression, we can construct a new
instance of the struct as the last expression in the function body to
implicitly return that new instance.
请注意,整个实例必须是可变的; Rust 不允许我们仅将某些字段标记为可变。与任何表达式一样,我们可以构造结构体的新实例作为函数体中的最后一个表达式,以隐式返回该新实例。
Listing 5-4 shows a build_user
function that returns a User
instance with
the given email and username. The active
field gets the value of true
, and
the sign_in_count
gets a value of 1
.
清单 5-4 显示了一个build_user
函数,它返回具有给定电子邮件和用户名的User
实例。 active
字段的值为true
, sign_in_count
的值为1
。
Filename: src/main.rs 文件名:src/main.rs
It makes sense to name the function parameters with the same name as the struct
fields, but having to repeat the email
and username
field names and
variables is a bit tedious. If the struct had more fields, repeating each name
would get even more annoying. Luckily, there’s a convenient shorthand!
使用与结构字段相同的名称来命名函数参数是有意义的,但必须重复email
和username
段名称和变量有点乏味。如果结构体有更多字段,重复每个名称会变得更加烦人。幸运的是,有一个方便的速记法!
Using the Field Init Shorthand
使用 Field Init 简写
Because the parameter names and the struct field names are exactly the same in
Listing 5-4, we can use the field init shorthand syntax to rewrite
build_user
so it behaves exactly the same but doesn’t have the repetition of
username
and email
, as shown in Listing 5-5.
由于清单 5-4 中的参数名称和结构体字段名称完全相同,因此我们可以使用field init 简写语法来重写build_user
,使其行为完全相同,但不会重复username
和email
,如图所示如清单 5-5 所示。
Filename: src/main.rs 文件名:src/main.rs
Here, we’re creating a new instance of the User
struct, which has a field
named email
. We want to set the email
field’s value to the value in the
email
parameter of the build_user
function. Because the email
field and
the email
parameter have the same name, we only need to write email
rather
than email: email
.
在这里,我们创建User
结构的一个新实例,其中有一个名为email
字段。我们希望将email
字段的值设置为build_user
函数的email
参数中的值。因为email
字段和email
参数同名,所以我们只需要写email
而不是email: email
。
Creating Instances from Other Instances with Struct Update Syntax
使用结构更新语法从其他实例创建实例
It’s often useful to create a new instance of a struct that includes most of
the values from another instance, but changes some. You can do this using
struct update syntax.
创建一个结构体的新实例通常很有用,该实例包含另一个实例的大部分值,但更改了一些值。您可以使用结构更新语法来完成此操作。
First, in Listing 5-6 we show how to create a new User
instance in user2
regularly, without the update syntax. We set a new value for email
but
otherwise use the same values from user1
that we created in Listing 5-2.
首先,在清单 5-6 中,我们展示了如何定期在user2
中创建一个新的User
实例,而不使用 update 语法。我们为email
设置了一个新值,但在其他方面使用我们在清单 5-2 中创建的user1
中的相同值。
Filename: src/main.rs 文件名:src/main.rs
Using struct update syntax, we can achieve the same effect with less code, as
shown in Listing 5-7. The syntax ..
specifies that the remaining fields not
explicitly set should have the same value as the fields in the given instance.
使用struct update语法,我们可以用更少的代码实现相同的效果,如清单5-7所示。语法..
指定未显式设置的其余字段应具有与给定实例中的字段相同的值。
Filename: src/main.rs 文件名:src/main.rs
The code in Listing 5-7 also creates an instance in user2
that has a
different value for email
but has the same values for the username
,
active
, and sign_in_count
fields from user1
. The ..user1
must come last
to specify that any remaining fields should get their values from the
corresponding fields in user1
, but we can choose to specify values for as
many fields as we want in any order, regardless of the order of the fields in
the struct’s definition.
清单 5-7 中的代码还在user2
中创建了一个实例,该实例具有不同的email
值,但与user1
的username
、 active
和sign_in_count
字段具有相同的值。 ..user1
必须放在最后,以指定任何剩余字段应从user1
中的相应字段获取其值,但我们可以选择以任何顺序为任意数量的字段指定值,而不管中字段的顺序如何结构体的定义。
Note that the struct update syntax uses =
like an assignment; this is because
it moves the data, just as we saw in the “Variables and Data Interacting with
Move” section. In this example, we can no longer use
user1
as a whole after creating user2
because the String
in the
username
field of user1
was moved into user2
. If we had given user2
new
String
values for both email
and username
, and thus only used the
active
and sign_in_count
values from user1
, then user1
would still be
valid after creating user2
. Both active
and sign_in_count
are types that
implement the Copy
trait, so the behavior we discussed in the “Stack-Only
Data: Copy” section would apply.
请注意,结构体更新语法使用=
就像赋值一样;这是因为它移动了数据,正如我们在“与移动交互的变量和数据”忽略部分中看到的那样。在这个例子中,我们在创建user2
之后就不能再使用user1
了,因为user1
的username
字段中的String
被移到了user2
中。如果我们为user2
提供了email
和username
的新String
值,因此只使用了user1
中的active
和sign_in_count
值,那么user1
在创建user2
后仍然有效。 active
和sign_in_count
都是实现Copy
特征的类型,因此我们在“仅堆栈数据:复制”忽略部分中讨论的行为将适用。
Using Tuple Structs Without Named Fields to Create Different Types
使用没有命名字段的元组结构来创建不同的类型
Rust also supports structs that look similar to tuples, called tuple structs.
Tuple structs have the added meaning the struct name provides but don’t have
names associated with their fields; rather, they just have the types of the
fields. Tuple structs are useful when you want to give the whole tuple a name
and make the tuple a different type from other tuples, and when naming each
field as in a regular struct would be verbose or redundant.
Rust 还支持看起来类似于元组的结构,称为元组结构。元组结构具有结构名称提供的附加含义,但没有与其字段关联的名称;相反,它们只有字段的类型。当您想要为整个元组指定一个名称并使该元组与其他元组具有不同的类型,并且像在常规结构中那样命名每个字段时会很冗长或多余时,元组结构非常有用。
To define a tuple struct, start with the struct
keyword and the struct name
followed by the types in the tuple. For example, here we define and use two
tuple structs named Color
and Point
:
要定义元组结构体,请从struct
关键字和结构体名称开始,后跟元组中的类型。例如,这里我们定义并使用两个名为Color
和Point
的元组结构:
Filename: src/main.rs 文件名:src/main.rs
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
fn main() {
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
}
Note that the black
and origin
values are different types because they’re
instances of different tuple structs. Each struct you define is its own type,
even though the fields within the struct might have the same types. For
example, a function that takes a parameter of type Color
cannot take a
Point
as an argument, even though both types are made up of three i32
values. Otherwise, tuple struct instances are similar to tuples in that you can
destructure them into their individual pieces, and you can use a .
followed
by the index to access an individual value.
请注意, black
和origin
值是不同的类型,因为它们是不同元组结构的实例。您定义的每个结构都是其自己的类型,即使结构中的字段可能具有相同的类型。例如,采用Color
类型参数的函数不能采用Point
作为参数,即使这两种类型均由三个i32
值组成。否则,元组结构实例与元组类似,您可以将它们解构为单独的部分,并且可以使用.
后跟索引以访问单个值。
Unit-Like Structs Without Any Fields
没有任何字段的类似单元的结构
You can also define structs that don’t have any fields! These are called
unit-like structs because they behave similarly to ()
, the unit type that
we mentioned in “The Tuple Type” section. Unit-like
structs can be useful when you need to implement a trait on some type but don’t
have any data that you want to store in the type itself. We’ll discuss traits
in Chapter 10. Here’s an example of declaring and instantiating a unit struct
named AlwaysEqual
:
您还可以定义没有任何字段的结构!这些被称为类单元结构,因为它们的行为类似于我们在“元组类型”忽略部分中提到的单元类型()
。当您需要在某种类型上实现特征但没有想要在类型本身中存储任何数据时,类似单元的结构会很有用。我们将在第 10 章中讨论特征。下面是声明和实例化名为AlwaysEqual
的单元结构的示例:
Filename: src/main.rs 文件名:src/main.rs
struct AlwaysEqual;
fn main() {
let subject = AlwaysEqual;
}
To define AlwaysEqual
, we use the struct
keyword, the name we want, and
then a semicolon. No need for curly brackets or parentheses! Then we can get an
instance of AlwaysEqual
in the subject
variable in a similar way: using the
name we defined, without any curly brackets or parentheses. Imagine that later
we’ll implement behavior for this type such that every instance of
AlwaysEqual
is always equal to every instance of any other type, perhaps to
have a known result for testing purposes. We wouldn’t need any data to
implement that behavior! You’ll see in Chapter 10 how to define traits and
implement them on any type, including unit-like structs.
为了定义AlwaysEqual
,我们使用struct
关键字、我们想要的名称,然后是分号。不需要大括号或圆括号!然后我们可以以类似的方式在subject
变量中获取AlwaysEqual
的实例:使用我们定义的名称,不带任何大括号或圆括号。想象一下,稍后我们将实现此类型的行为,以便AlwaysEqual
的每个实例始终等于任何其他类型的每个实例,也许为了测试目的而获得已知结果。我们不需要任何数据来实现该行为!您将在第 10 章中看到如何定义特征并在任何类型(包括类似单元的结构)上实现它们。
Ownership of Struct Data 结构数据的所有权
In the User
struct definition in Listing 5-1, we used the owned String
type rather than the &str
string slice type. This is a deliberate choice
because we want each instance of this struct to own all of its data and for
that data to be valid for as long as the entire struct is valid.
在清单 5-1 的User
结构体定义中,我们使用了拥有的String
类型而不是&str
字符串切片类型。这是一个经过深思熟虑的选择,因为我们希望该结构的每个实例都拥有其所有数据,并且只要整个结构有效,该数据就有效。
It’s also possible for structs to store references to data owned by something
else, but to do so requires the use of lifetimes, a Rust feature that we’ll
discuss in Chapter 10. Lifetimes ensure that the data referenced by a struct
is valid for as long as the struct is. Let’s say you try to store a reference
in a struct without specifying lifetimes, like the following; this won’t work:
结构体也可以存储对其他对象所拥有的数据的引用,但这样做需要使用生命周期,这是我们将在第 10 章中讨论的 Rust 功能。生命周期确保结构体引用的数据在以下情况下有效:只要结构是。假设您尝试在结构中存储引用而不指定生命周期,如下所示;这是行不通的:
Filename: src/main.rs 文件名:src/main.rs
struct User {
active: bool,
username: &str,
email: &str,
sign_in_count: u64,
}
fn main() {
let user1 = User {
active: true,
username: "someusername123",
email: "someone@example.com",
sign_in_count: 1,
};
}
The compiler will complain that it needs lifetime specifiers:
编译器会抱怨它需要生命周期说明符:
$ cargo run
Compiling structs v0.1.0 (file:///projects/structs)
error[E0106]: missing lifetime specifier
--> src/main.rs:3:15
|
3 | username: &str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct User<'a> {
2 | active: bool,
3 ~ username: &'a str,
|
error[E0106]: missing lifetime specifier
--> src/main.rs:4:12
|
4 | email: &str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct User<'a> {
2 | active: bool,
3 | username: &str,
4 ~ email: &'a str,
|
For more information about this error, try `rustc --explain E0106`.
error: could not compile `structs` (bin "structs") due to 2 previous errors
In Chapter 10, we’ll discuss how to fix these errors so you can store
references in structs, but for now, we’ll fix errors like these using owned
types like String
instead of references like &str
.
在第 10 章中,我们将讨论如何修复这些错误,以便您可以在结构中存储引用,但现在,我们将使用String
等自有类型而不是&str
等引用来修复此类错误。
An Example Program Using Structs
使用结构的示例程序
To understand when we might want to use structs, let’s write a program that
calculates the area of a rectangle. We’ll start by using single variables, and
then refactor the program until we’re using structs instead.
为了了解何时需要使用结构体,让我们编写一个计算矩形面积的程序。我们将从使用单个变量开始,然后重构程序,直到我们使用结构体。
Let’s make a new binary project with Cargo called rectangles that will take
the width and height of a rectangle specified in pixels and calculate the area
of the rectangle. Listing 5-8 shows a short program with one way of doing
exactly that in our project’s src/main.rs.
让我们用 Cargo 创建一个名为矩形的新二进制项目,它将采用以像素为单位指定的矩形的宽度和高度并计算矩形的面积。清单 5-8 显示了一个简短的程序,其中一种方法在我们项目的src/main.rs中实现了这一点。
Filename: src/main.rs 文件名:src/main.rs
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) -> u32 {
width * height
}
Now, run this program using cargo run
:
现在,使用cargo run
运行该程序:
$ 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.
This code succeeds in figuring out the area of the rectangle by calling the
area
function with each dimension, but we can do more to make this code clear
and readable.
这段代码通过调用每个维度的area
函数成功地计算出了矩形的面积,但是我们可以做更多的事情来使这段代码清晰易读。
The issue with this code is evident in the signature of area
:
该代码的问题在area
的签名中很明显:
The area
function is supposed to calculate the area of one rectangle, but the
function we wrote has two parameters, and it’s not clear anywhere in our
program that the parameters are related. It would be more readable and more
manageable to group width and height together. We’ve already discussed one way
we might do that in “The Tuple Type” section
of Chapter 3: by using tuples.area
函数应该计算一个矩形的面积,但是我们编写的函数有两个参数,并且我们程序中的任何地方都不清楚这些参数是相关的。将宽度和高度组合在一起会更具可读性和更易于管理。我们已经在第 3 章的“元组类型”忽略部分中讨论了一种可以做到这一点的方法:使用元组。
Refactoring with Tuples 使用元组重构
Listing 5-9 shows another version of our program that uses tuples.
清单 5-9 显示了使用元组的程序的另一个版本。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let rect1 = (30, 50);
println!(
"The area of the rectangle is {} square pixels.",
area(rect1)
);
}
fn area(dimensions: (u32, u32)) -> u32 {
dimensions.0 * dimensions.1
}
In one way, this program is better. Tuples let us add a bit of structure, and
we’re now passing just one argument. But in another way, this version is less
clear: tuples don’t name their elements, so we have to index into the parts of
the tuple, making our calculation less obvious.
从某种意义上说,这个程序更好。元组让我们添加一点结构,现在我们只传递一个参数。但从另一方面来说,这个版本不太清楚:元组不会命名它们的元素,因此我们必须对元组的各个部分进行索引,从而使我们的计算不那么明显。
Mixing up the width and height wouldn’t matter for the area calculation, but if
we want to draw the rectangle on the screen, it would matter! We would have to
keep in mind that width
is the tuple index 0
and height
is the tuple
index 1
. This would be even harder for someone else to figure out and keep in
mind if they were to use our code. Because we haven’t conveyed the meaning of
our data in our code, it’s now easier to introduce errors.
混合宽度和高度对于面积计算来说并不重要,但如果我们想在屏幕上绘制矩形,那就很重要了!我们必须记住, width
是元组索引0
, height
是元组索引1
。如果其他人使用我们的代码,他们将更难弄清楚并记住这一点。因为我们没有在代码中传达数据的含义,所以现在更容易引入错误。
Refactoring with Structs: Adding More Meaning
使用结构重构:添加更多含义
We use structs to add meaning by labeling the data. We can transform the tuple
we’re using into a struct with a name for the whole as well as names for the
parts, as shown in Listing 5-10.
我们使用结构通过标记数据来添加含义。我们可以将我们使用的元组转换为一个结构体,该结构体具有整体名称和部分名称,如清单 5-10 所示。
Filename: src/main.rs 文件名:src/main.rs
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(&rect1)
);
}
fn area(rectangle: &Rectangle) -> u32 {
rectangle.width * rectangle.height
}
Here we’ve defined a struct and named it Rectangle
. Inside the curly
brackets, we defined the fields as width
and height
, both of which have
type u32
. Then, in main
, we created a particular instance of Rectangle
that has a width of 30
and a height of 50
.
这里我们定义了一个结构体并将其命名为Rectangle
。在大括号内,我们将字段定义为width
和height
,这两个字段的类型均为u32
。然后,在main
中,我们创建了一个特定的Rectangle
实例,其宽度为30
,高度为50
。
Our area
function is now defined with one parameter, which we’ve named
rectangle
, whose type is an immutable borrow of a struct Rectangle
instance. As mentioned in Chapter 4, we want to borrow the struct rather than
take ownership of it. This way, main
retains its ownership and can continue
using rect1
, which is the reason we use the &
in the function signature and
where we call the function.
我们的area
函数现在用一个参数定义,我们将其命名为rectangle
,其类型是 struct Rectangle
实例的不可变借用。正如第 4 章中提到的,我们想要借用该结构而不是拥有它。这样, main
保留其所有权并可以继续使用rect1
,这就是我们在函数签名和调用该函数的位置中使用&
原因。
The area
function accesses the width
and height
fields of the Rectangle
instance (note that accessing fields of a borrowed struct instance does not
move the field values, which is why you often see borrows of structs). Our
function signature for area
now says exactly what we mean: calculate the area
of Rectangle
, using its width
and height
fields. This conveys that the
width and height are related to each other, and it gives descriptive names to
the values rather than using the tuple index values of 0
and 1
. This is a
win for clarity.area
函数访问Rectangle
实例的width
和height
字段(请注意,访问借用的结构体实例的字段不会移动字段值,这就是您经常看到结构体借用的原因)。我们的area
函数签名现在准确地表达了我们的意思:使用其width
和height
字段计算Rectangle
的面积。这表明宽度和高度彼此相关,并且它为值提供描述性名称,而不是使用元组索引值0
和1
。这是一个清晰的胜利。
Adding Useful Functionality with Derived Traits
通过派生特征添加有用的功能
It’d be useful to be able to print an instance of Rectangle
while we’re
debugging our program and see the values for all its fields. Listing 5-11 tries
using the println!
macro as we have used in
previous chapters. This won’t work, however.
当我们调试程序并查看其所有字段的值时,能够打印Rectangle
的实例会很有用。清单 5-11 尝试使用println!
我们在前面的章节中使用过宏忽略。然而,这行不通。
Filename: src/main.rs 文件名:src/main.rs
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {}", rect1);
}
When we compile this code, we get an error with this core message:
当我们编译这段代码时,我们收到一条错误消息:
error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`
The println!
macro can do many kinds of formatting, and by default, the curly
brackets tell println!
to use formatting known as Display
: output intended
for direct end user consumption. The primitive types we’ve seen so far
implement Display
by default because there’s only one way you’d want to show
a 1
or any other primitive type to a user. But with structs, the way
println!
should format the output is less clear because there are more
display possibilities: Do you want commas or not? Do you want to print the
curly brackets? Should all the fields be shown? Due to this ambiguity, Rust
doesn’t try to guess what we want, and structs don’t have a provided
implementation of Display
to use with println!
and the {}
placeholder.println!
宏可以进行多种格式化,默认情况下,大括号告诉println!
使用称为Display
的格式:旨在供最终用户直接使用的输出。到目前为止,我们看到的基本类型默认实现Display
因为只有一种方法可以向用户显示1
或任何其他基本类型。但是对于结构体, println!
的方式应该格式化输出不太清楚,因为有更多的显示可能性:您是否想要逗号?您想打印大括号吗?是否应该显示所有字段?由于这种歧义,Rust 不会尝试猜测我们想要什么,并且结构没有提供与 println 一起使用的Display
实现println!
和{}
占位符。
If we continue reading the errors, we’ll find this helpful note:
如果我们继续阅读错误,我们会发现以下有用的注释:
= 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
Let’s try it! The println!
macro call will now look like println!("rect1 is {rect1:?}");
. Putting the specifier :?
inside the curly brackets tells
println!
we want to use an output format called Debug
. The Debug
trait
enables us to print our struct in a way that is useful for developers so we can
see its value while we’re debugging our code.
我们来试试吧! println!
宏调用现在看起来像println!("rect1 is {rect1:?}");
。放置说明符:?
大括号内告诉println!
我们想使用名为Debug
的输出格式。 Debug
特征使我们能够以对开发人员有用的方式打印结构,以便我们在调试代码时可以看到它的值。
Compile the code with this change. Drat! We still get an error:
编译包含此更改的代码。讨厌!我们仍然收到错误:
error[E0277]: `Rectangle` doesn't implement `Debug`
But again, the compiler gives us a helpful note:
但编译器再次给了我们一个有用的注释:
= help: the trait `Debug` is not implemented for `Rectangle`
= note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle`
Rust does include functionality to print out debugging information, but we
have to explicitly opt in to make that functionality available for our struct.
To do that, we add the outer attribute #[derive(Debug)]
just before the
struct definition, as shown in Listing 5-12.
Rust确实包含打印调试信息的功能,但我们必须明确选择使该功能可用于我们的结构。为此,我们在结构体定义之前添加外部属性#[derive(Debug)]
,如清单 5-12 所示。
Filename: src/main.rs 文件名:src/main.rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {rect1:?}");
}
Now when we run the program, we won’t get any errors, and we’ll see the
following output:
现在,当我们运行该程序时,我们不会收到任何错误,并且我们将看到以下输出:
$ 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 }
Nice! It’s not the prettiest output, but it shows the values of all the fields
for this instance, which would definitely help during debugging. When we have
larger structs, it’s useful to have output that’s a bit easier to read; in
those cases, we can use {:#?}
instead of {:?}
in the println!
string. In
this example, using the {:#?}
style will output the following:
好的!它不是最漂亮的输出,但它显示了该实例的所有字段的值,这在调试过程中肯定会有所帮助。当我们有更大的结构时,让输出更容易阅读会很有用;在这些情况下,我们可以在println!
中使用{:#?}
而不是{:?}
细绳。在此示例中,使用{:#?}
样式将输出以下内容:
$ 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,
}
Another way to print out a value using the Debug
format is to use the dbg!
macro, which takes ownership of an expression (as opposed
to println!
, which takes a reference), prints the file and line number of
where that dbg!
macro call occurs in your code along with the resultant value
of that expression, and returns ownership of the value.
使用Debug
格式打印值的另一种方法是使用dbg!
宏ignore,它获取表达式的所有权(与println!
相反,它获取引用),打印dbg!
所在的文件和行号。宏调用与该表达式的结果值一起发生在代码中,并返回该值的所有权。
Note: Calling the dbg!
macro prints to the standard error console stream
(stderr
), as opposed to println!
, which prints to the standard output
console stream (stdout
). We’ll talk more about stderr
and stdout
in the
“Writing Error Messages to Standard Error Instead of Standard Output”
section in Chapter 12.
注意:调用dbg!
宏打印到标准错误控制台流 ( stderr
),而不是println!
,它打印到标准输出控制台流( stdout
)。我们将在第 12 章中的“将错误消息写入标准错误而不是标准输出”部分中详细讨论stderr
和stdout
。
Here’s an example where we’re interested in the value that gets assigned to the
width
field, as well as the value of the whole struct in rect1
:
下面是一个示例,我们对分配给width
字段的值以及rect1
中整个结构的值感兴趣:
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let scale = 2;
let rect1 = Rectangle {
width: dbg!(30 * scale),
height: 50,
};
dbg!(&rect1);
}
We can put dbg!
around the expression 30 * scale
and, because dbg!
returns ownership of the expression’s value, the width
field will get the
same value as if we didn’t have the dbg!
call there. We don’t want dbg!
to
take ownership of rect1
, so we use a reference to rect1
in the next call.
Here’s what the output of this example looks like:
我们可以把dbg!
围绕表达式30 * scale
,因为dbg!
返回表达式值的所有权, width
字段将获得与没有dbg!
打电话到那里。我们不需要dbg!
取得rect1
的所有权,因此我们在下一次调用中使用对rect1
的引用。此示例的输出如下所示:
$ 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] &rect1 = Rectangle {
width: 60,
height: 50,
}
We can see the first bit of output came from src/main.rs line 10 where we’re
debugging the expression 30 * scale
, and its resultant value is 60
(the
Debug
formatting implemented for integers is to print only their value). The
dbg!
call on line 14 of src/main.rs outputs the value of &rect1
, which is
the Rectangle
struct. This output uses the pretty Debug
formatting of the
Rectangle
type. The dbg!
macro can be really helpful when you’re trying to
figure out what your code is doing!
我们可以看到输出的第一位来自src/main.rs第 10 行,我们正在调试表达式30 * scale
,其结果值为60
(为整数实现的Debug
格式仅打印它们的值)。 dbg!
src/main.rs第 14 行调用输出&rect1
的值,它是Rectangle
结构。此输出使用Rectangle
类型的漂亮Debug
格式。 dbg!
当您试图弄清楚代码在做什么时,宏真的很有帮助!
In addition to the Debug
trait, Rust has provided a number of traits for us
to use with the derive
attribute that can add useful behavior to our custom
types. Those traits and their behaviors are listed in Appendix C. We’ll cover how to implement these traits with custom behavior as
well as how to create your own traits in Chapter 10. There are also many
attributes other than derive
; for more information, see the “Attributes”
section of the Rust Reference.
除了Debug
特征之外,Rust 还提供了许多特征供我们与derive
属性一起使用,这些属性可以为我们的自定义类型添加有用的行为。这些特征及其行为列在附录 C中。我们将在第 10 章中介绍如何使用derive
定义行为实现这些特征,以及如何创建自己的特征。有关更多信息,请参阅Rust 参考的“属性”部分。
Our area
function is very specific: it only computes the area of rectangles.
It would be helpful to tie this behavior more closely to our Rectangle
struct
because it won’t work with any other type. Let’s look at how we can continue to
refactor this code by turning the area
function into an area
method
defined on our Rectangle
type.
我们的area
函数非常具体:它只计算矩形的面积。将此行为与我们的Rectangle
结构更紧密地联系起来会很有帮助,因为它不适用于任何其他类型。让我们看看如何通过将area
函数转换为在我们的Rectangle
类型上定义的area
方法来继续重构此代码。
Method Syntax 方法语法
Methods are similar to functions: we declare them with the fn
keyword and a
name, they can have parameters and a return value, and they contain some code
that’s run when the method is called from somewhere else. Unlike functions,
methods are defined within the context of a struct (or an enum or a trait
object, which we cover in Chapter 6 and Chapter
17, respectively), and their first parameter is
always self
, which represents the instance of the struct the method is being
called on.
方法与函数类似:我们使用fn
关键字和名称来声明它们,它们可以具有参数和返回值,并且它们包含从其他地方调用该方法时运行的一些代码。与函数不同,方法是在结构体(或枚举或特征对象,我们分别在第 6 章ignore 和第 17 章ignore 中介绍)的上下文中定义的,并且它们的第一个参数始终是self
,它表示该对象的实例struct 正在调用的方法。
Defining Methods 定义方法
Let’s change the area
function that has a Rectangle
instance as a parameter
and instead make an area
method defined on the Rectangle
struct, as shown
in Listing 5-13.
让我们更改以Rectangle
实例作为参数的area
函数,并在Rectangle
结构上定义一个area
方法,如清单 5-13 所示。
Filename: src/main.rs 文件名:src/main.rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> 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()
);
}
To define the function within the context of Rectangle
, we start an impl
(implementation) block for Rectangle
. Everything within this impl
block
will be associated with the Rectangle
type. Then we move the area
function
within the impl
curly brackets and change the first (and in this case, only)
parameter to be self
in the signature and everywhere within the body. In
main
, where we called the area
function and passed rect1
as an argument,
we can instead use method syntax to call the area
method on our Rectangle
instance. The method syntax goes after an instance: we add a dot followed by
the method name, parentheses, and any arguments.
为了在Rectangle
的上下文中定义函数,我们为Rectangle
启动一个impl
(实现)块。此impl
块中的所有内容都将与Rectangle
类型关联。然后,我们将area
函数移动到impl
花括号内,并将签名中和正文中的第一个(在本例中是唯一)参数更改为self
。在main
中,我们调用了area
函数并传递了rect1
作为参数,我们可以使用方法语法来调用Rectangle
实例上的area
方法。方法语法位于实例之后:我们添加一个点,后跟方法名称、括号和任何参数。
In the signature for area
, we use &self
instead of rectangle: &Rectangle
.
The &self
is actually short for self: &Self
. Within an impl
block, the
type Self
is an alias for the type that the impl
block is for. Methods must
have a parameter named self
of type Self
for their first parameter, so Rust
lets you abbreviate this with only the name self
in the first parameter spot.
Note that we still need to use the &
in front of the self
shorthand to
indicate that this method borrows the Self
instance, just as we did in
rectangle: &Rectangle
. Methods can take ownership of self
, borrow self
immutably, as we’ve done here, or borrow self
mutably, just as they can any
other parameter.
在area
的签名中,我们使用&self
而不是rectangle: &Rectangle
。 &self
实际上是self: &Self
。在impl
块中, Self
类型是impl
块所属类型的别名。方法的第一个参数必须有一个名为self
的Self
类型参数,因此 Rust 允许您在第一个参数位置仅使用名称self
来缩写它。请注意,我们仍然需要在self
简写前面使用&
来指示该方法借用Self
实例,就像我们在rectangle: &Rectangle
中所做的那样。方法可以取得self
的所有权,不变地借用self
,就像我们在这里所做的那样,或者可变地借用self
,就像它们可以使用任何其他参数一样。
We chose &self
here for the same reason we used &Rectangle
in the function
version: we don’t want to take ownership, and we just want to read the data in
the struct, not write to it. If we wanted to change the instance that we’ve
called the method on as part of what the method does, we’d use &mut self
as
the first parameter. Having a method that takes ownership of the instance by
using just self
as the first parameter is rare; this technique is usually
used when the method transforms self
into something else and you want to
prevent the caller from using the original instance after the transformation.
我们在这里选择&self
原因与我们在函数版本中使用&Rectangle
原因相同:我们不想获得所有权,我们只想读取结构中的数据,而不是写入它。如果我们想要更改调用该方法的实例(作为该方法的一部分),我们可以使用&mut self
作为第一个参数。通过仅使用self
作为第一个参数来获取实例所有权的方法很少见;当方法将self
转换为其他内容并且您希望防止调用者在转换后使用原始实例时,通常会使用此技术。
The main reason for using methods instead of functions, in addition to
providing method syntax and not having to repeat the type of self
in every
method’s signature, is for organization. We’ve put all the things we can do
with an instance of a type in one impl
block rather than making future users
of our code search for capabilities of Rectangle
in various places in the
library we provide.
使用方法而不是函数的主要原因,除了提供方法语法并且不必在每个方法的签名中重复self
类型之外,还有为了组织。我们已经将类型实例可以做的所有事情都放在一个impl
块中,而不是让我们代码的未来用户在我们提供的库的各个位置搜索Rectangle
的功能。
Note that we can choose to give a method the same name as one of the struct’s
fields. For example, we can define a method on Rectangle
that is also named
width
:
请注意,我们可以选择为方法指定与结构体字段之一相同的名称。例如,我们可以在Rectangle
上定义一个也名为width
方法:
Filename: src/main.rs 文件名:src/main.rs
Here, we’re choosing to make the width
method return true
if the value in
the instance’s width
field is greater than 0
and false
if the value is
0
: we can use a field within a method of the same name for any purpose. In
main
, when we follow rect1.width
with parentheses, Rust knows we mean the
method width
. When we don’t use parentheses, Rust knows we mean the field
width
.
在这里,我们选择如果实例的width
字段中的值大于0
,则让width
方法返回true
;如果值为0
,则让 width 方法返回false
:我们可以出于任何目的使用同名方法中的字段。在main
中,当我们在rect1.width
后面加上括号时,Rust 知道我们指的是方法width
。当我们不使用括号时,Rust 知道我们指的是字段width
。
Often, but not always, when we give a method the same name as a field we want
it to only return the value in the field and do nothing else. Methods like this
are called getters, and Rust does not implement them automatically for struct
fields as some other languages do. Getters are useful because you can make the
field private but the method public, and thus enable read-only access to that
field as part of the type’s public API. We will discuss what public and private
are and how to designate a field or method as public or private in Chapter
7.
通常,但并非总是,当我们给一个方法提供与字段相同的名称时,我们希望它只返回字段中的值,而不执行其他操作。像这样的方法称为getters ,Rust 不会像其他语言那样自动为结构体字段实现它们。 Getter 很有用,因为您可以将字段设为私有,但将方法设为公共,从而作为类型的公共 API 的一部分启用对该字段的只读访问。我们将在第 7 章中讨论什么是公共和私有以及如何将字段或方法指定为公共或私有。
Where’s the ->
Operator?
->
运算符在哪里?
In C and C++, two different operators are used for calling methods: you use
.
if you’re calling a method on the object directly and ->
if you’re
calling the method on a pointer to the object and need to dereference the
pointer first. In other words, if object
is a pointer,
object->something()
is similar to (*object).something()
.
在 C 和 C++ 中,使用两种不同的运算符来调用方法:使用.
如果您直接在对象上调用方法,并且->
如果您在指向对象的指针上调用方法并且需要首先取消引用该指针。换句话说,如果object
是指针, object->something()
类似于(*object).something()
。
Rust doesn’t have an equivalent to the ->
operator; instead, Rust has a
feature called automatic referencing and dereferencing. Calling methods is
one of the few places in Rust that has this behavior.
Rust 没有与->
等价的运算符;相反,Rust 有一个称为自动引用和取消引用的功能。调用方法是 Rust 中少数具有这种行为的地方之一。
Here’s how it works: when you call a method with object.something()
, Rust
automatically adds in &
, &mut
, or *
so object
matches the signature of
the method. In other words, the following are the same:
它的工作原理如下:当您使用object.something()
调用方法时,Rust 会自动添加&
、 &mut
或*
,以便object
与方法的签名匹配。换句话说,以下内容是相同的:
The first one looks much cleaner. This automatic referencing behavior works
because methods have a clear receiver—the type of self
. Given the receiver
and name of a method, Rust can figure out definitively whether the method is
reading (&self
), mutating (&mut self
), or consuming (self
). The fact
that Rust makes borrowing implicit for method receivers is a big part of
making ownership ergonomic in practice.
第一个看起来干净得多。这种自动引用行为之所以有效,是因为方法有一个明确的接收者—— self
的类型。给定方法的接收者和名称,Rust 可以明确地确定该方法是否正在读取 ( &self
)、变异 ( &mut self
) 或消耗 ( self
)。事实上,Rust 使方法接收者隐式借用,这是在实践中使所有权符合人体工程学的一个重要部分。
Methods with More Parameters
具有更多参数的方法
Let’s practice using methods by implementing a second method on the Rectangle
struct. This time we want an instance of Rectangle
to take another instance
of Rectangle
and return true
if the second Rectangle
can fit completely
within self
(the first Rectangle
); otherwise, it should return false
.
That is, once we’ve defined the can_hold
method, we want to be able to write
the program shown in Listing 5-14.
让我们通过在Rectangle
结构上实现第二个方法来练习使用方法。这次,我们希望Rectangle
的实例获取Rectangle
的另一个实例,如果第二个Rectangle
可以完全适合self
(第一个Rectangle
),则返回true
;否则,它应该返回false
。也就是说,一旦定义了can_hold
方法,我们就希望能够编写清单 5-14 中所示的程序。
Filename: src/main.rs 文件名:src/main.rs
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(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
The expected output would look like the following because both dimensions of
rect2
are smaller than the dimensions of rect1
, but rect3
is wider than
rect1
:
预期输出如下所示,因为rect2
的两个尺寸都小于rect1
的尺寸,但rect3
比rect1
宽:
Can rect1 hold rect2? true
Can rect1 hold rect3? false
We know we want to define a method, so it will be within the impl Rectangle
block. The method name will be can_hold
, and it will take an immutable borrow
of another Rectangle
as a parameter. We can tell what the type of the
parameter will be by looking at the code that calls the method:
rect1.can_hold(&rect2)
passes in &rect2
, which is an immutable borrow to
rect2
, an instance of Rectangle
. This makes sense because we only need to
read rect2
(rather than write, which would mean we’d need a mutable borrow),
and we want main
to retain ownership of rect2
so we can use it again after
calling the can_hold
method. The return value of can_hold
will be a
Boolean, and the implementation will check whether the width and height of
self
are greater than the width and height of the other Rectangle
,
respectively. Let’s add the new can_hold
method to the impl
block from
Listing 5-13, shown in Listing 5-15.
我们知道我们想要定义一个方法,因此它将位于impl Rectangle
块内。方法名称为can_hold
,它将采用另一个Rectangle
的不可变借用作为参数。我们可以通过查看调用该方法的代码来判断参数的类型: rect1.can_hold(&rect2)
传入&rect2
,它是rect2
的不可变借用,它是Rectangle
的一个实例。这是有道理的,因为我们只需要读取rect2
(而不是写入,这意味着我们需要可变借位),并且我们希望main
保留rect2
的所有权,以便我们可以在调用can_hold
方法后再次使用它。 can_hold
的返回值将是一个布尔值,并且实现将分别检查self
的宽度和高度是否大于另一个Rectangle
的宽度和高度。让我们将新的can_hold
方法添加到清单 5-13 中的impl
块中,如清单 5-15 所示。
Filename: src/main.rs 文件名:src/main.rs
When we run this code with the main
function in Listing 5-14, we’ll get our
desired output. Methods can take multiple parameters that we add to the
signature after the self
parameter, and those parameters work just like
parameters in functions.
当我们使用清单 5-14 中的main
函数运行此代码时,我们将得到所需的输出。方法可以采用我们在self
参数之后添加到签名中的多个参数,这些参数的工作方式就像函数中的参数一样。
Associated Functions 相关功能
All functions defined within an impl
block are called associated functions
because they’re associated with the type named after the impl
. We can define
associated functions that don’t have self
as their first parameter (and thus
are not methods) because they don’t need an instance of the type to work with.
We’ve already used one function like this: the String::from
function that’s
defined on the String
type.impl
块中定义的所有函数都称为关联函数,因为它们与以impl
命名的类型关联。我们可以定义不将self
作为第一个参数的关联函数(因此不是方法),因为它们不需要使用该类型的实例。我们已经使用过这样一个函数:在String
类型上定义的String::from
函数。
Associated functions that aren’t methods are often used for constructors that
will return a new instance of the struct. These are often called new
, but
new
isn’t a special name and isn’t built into the language. For example, we
could choose to provide an associated function named square
that would have
one dimension parameter and use that as both width and height, thus making it
easier to create a square Rectangle
rather than having to specify the same
value twice:
非方法的关联函数通常用于将返回结构的新实例的构造函数。它们通常被称为new
,但new
不是一个特殊的名称,也没有内置到语言中。例如,我们可以选择提供一个名为square
关联函数,该函数具有一个维度参数,并将其用作宽度和高度,从而更容易创建正方形Rectangle
,而不必两次指定相同的值:
Filename: src/main.rs 文件名:src/main.rs
The Self
keywords in the return type and in the body of the function are
aliases for the type that appears after the impl
keyword, which in this case
is Rectangle
.
返回类型和函数体中的Self
关键字是impl
关键字后面出现的类型的别名,在本例中为Rectangle
。
To call this associated function, we use the ::
syntax with the struct name;
let sq = Rectangle::square(3);
is an example. This function is namespaced by
the struct: the ::
syntax is used for both associated functions and
namespaces created by modules. We’ll discuss modules in Chapter
7.
为了调用这个关联函数,我们使用::
语法和结构名称; let sq = Rectangle::square(3);
就是一个例子。该函数由结构体命名::
语法用于关联函数和模块创建的命名空间。我们将在第 7 章中讨论模块ignore。
Multiple impl
Blocks
多个impl
块
Each struct is allowed to have multiple impl
blocks. For example, Listing
5-15 is equivalent to the code shown in Listing 5-16, which has each method in
its own impl
block.
每个结构体允许有多个impl
块。例如,清单 5-15 与清单 5-16 中所示的代码等效,其中每个方法都位于其自己的impl
块中。
There’s no reason to separate these methods into multiple impl
blocks here,
but this is valid syntax. We’ll see a case in which multiple impl
blocks are
useful in Chapter 10, where we discuss generic types and traits.
这里没有理由将这些方法分成多个impl
块,但这是有效的语法。我们将在第 10 章中看到多个impl
块很有用的情况,其中我们将讨论泛型类型和特征。
Summary 概括
Structs let you create custom types that are meaningful for your domain. By
using structs, you can keep associated pieces of data connected to each other
and name each piece to make your code clear. In impl
blocks, you can define
functions that are associated with your type, and methods are a kind of
associated function that let you specify the behavior that instances of your
structs have.
结构允许您创建对您的域有意义的自定义类型。通过使用结构,您可以保持关联的数据片段相互连接,并为每个片段命名以使代码清晰。在impl
块中,您可以定义与您的类型关联的函数,而方法是一种关联函数,可让您指定结构体实例所具有的行为。
But structs aren’t the only way you can create custom types: let’s turn to
Rust’s enum feature to add another tool to your toolbox.
但结构并不是创建自定义类型的唯一方法:让我们转向 Rust 的枚举功能,将另一个工具添加到您的工具箱中。
Enums and Pattern Matching
枚举和模式匹配
In this chapter, we’ll look at enumerations, also referred to as enums.
Enums allow you to define a type by enumerating its possible variants. First
we’ll define and use an enum to show how an enum can encode meaning along with
data. Next, we’ll explore a particularly useful enum, called Option
, which
expresses that a value can be either something or nothing. Then we’ll look at
how pattern matching in the match
expression makes it easy to run different
code for different values of an enum. Finally, we’ll cover how the if let
construct is another convenient and concise idiom available to handle enums in
your code.
在本章中,我们将讨论枚举,也称为枚举。枚举允许您通过枚举其可能的变体来定义类型。首先,我们将定义并使用枚举来展示枚举如何将含义与数据一起编码。接下来,我们将探索一个特别有用的枚举,称为Option
,它表示一个值可以是某物或什么都不是。然后我们将了解match
表达式中的模式匹配如何轻松地为枚举的不同值运行不同的代码。最后,我们将介绍if let
构造如何成为另一种方便且简洁的习惯用法,可用于处理代码中的枚举。
Defining an Enum 定义枚举
Where structs give you a way of grouping together related fields and data, like
a Rectangle
with its width
and height
, enums give you a way of saying a
value is one of a possible set of values. For example, we may want to say that
Rectangle
is one of a set of possible shapes that also includes Circle
and
Triangle
. To do this, Rust allows us to encode these possibilities as an enum.
结构为您提供了一种将相关字段和数据分组在一起的方法,例如具有width
和height
的Rectangle
,而枚举为您提供了一种表示某个值是一组可能的值之一的方法。例如,我们可能想说Rectangle
是一组可能的形状之一,其中还包括Circle
和Triangle
。为此,Rust 允许我们将这些可能性编码为枚举。
Let’s look at a situation we might want to express in code and see why enums
are useful and more appropriate than structs in this case. Say we need to work
with IP addresses. Currently, two major standards are used for IP addresses:
version four and version six. Because these are the only possibilities for an
IP address that our program will come across, we can enumerate all possible
variants, which is where enumeration gets its name.
让我们看一下我们可能想要在代码中表达的情况,看看为什么枚举在这种情况下有用并且比结构更合适。假设我们需要使用 IP 地址。目前,IP 地址使用两个主要标准:第四版和第六版。因为这些是我们的程序将遇到的 IP 地址的唯一可能性,所以我们可以枚举所有可能的变体,这就是枚举名称的由来。
Any IP address can be either a version four or a version six address, but not
both at the same time. That property of IP addresses makes the enum data
structure appropriate because an enum value can only be one of its variants.
Both version four and version six addresses are still fundamentally IP
addresses, so they should be treated as the same type when the code is handling
situations that apply to any kind of IP address.
任何 IP 地址都可以是版本 4 或版本 6 地址,但不能同时是两者。 IP 地址的这一属性使得枚举数据结构变得合适,因为枚举值只能是其变体之一。版本四和版本六地址本质上仍然是 IP 地址,因此当代码处理适用于任何类型 IP 地址的情况时,应将它们视为同一类型。
We can express this concept in code by defining an IpAddrKind
enumeration and
listing the possible kinds an IP address can be, V4
and V6
. These are the
variants of the enum:
我们可以通过定义IpAddrKind
枚举并列出 IP 地址可能的类型( V4
和V6
来用代码表达这个概念。这些是枚举的变体:
IpAddrKind
is now a custom data type that we can use elsewhere in our code.IpAddrKind
现在是一种自定义数据类型,我们可以在代码的其他地方使用它。
Enum Values 枚举值
We can create instances of each of the two variants of IpAddrKind
like this:
我们可以像这样创建IpAddrKind
的两个变体的实例:
Note that the variants of the enum are namespaced under its identifier, and we
use a double colon to separate the two. This is useful because now both values
IpAddrKind::V4
and IpAddrKind::V6
are of the same type: IpAddrKind
. We
can then, for instance, define a function that takes any IpAddrKind
:
请注意,枚举的变体在其标识符下命名,我们使用双冒号来分隔两者。这很有用,因为现在IpAddrKind::V4
和IpAddrKind::V6
的类型相同: IpAddrKind
。例如,我们可以定义一个接受任何IpAddrKind
的函数:
And we can call this function with either variant:
我们可以使用任一变体来调用该函数:
Using enums has even more advantages. Thinking more about our IP address type,
at the moment we don’t have a way to store the actual IP address data; we
only know what kind it is. Given that you just learned about structs in
Chapter 5, you might be tempted to tackle this problem with structs as shown in
Listing 6-1.
使用枚举还有更多优点。进一步考虑我们的 IP 地址类型,目前我们没有办法存储实际的 IP 地址数据;我们只知道它是什么类型。鉴于您刚刚在第 5 章中了解了结构体,您可能会想使用结构体来解决这个问题,如清单 6-1 所示。
Here, we’ve defined a struct IpAddr
that has two fields: a kind
field that
is of type IpAddrKind
(the enum we defined previously) and an address
field
of type String
. We have two instances of this struct. The first is home
,
and it has the value IpAddrKind::V4
as its kind
with associated address
data of 127.0.0.1
. The second instance is loopback
. It has the other
variant of IpAddrKind
as its kind
value, V6
, and has address ::1
associated with it. We’ve used a struct to bundle the kind
and address
values together, so now the variant is associated with the value.
在这里,我们定义了一个 struct IpAddr
,它有两个字段:一个IpAddrKind
类型的kind
字段(我们之前定义的枚举)和一个String
类型的address
字段。我们有这个结构的两个实例。第一个是home
,它的kind
值为IpAddrKind::V4
,关联地址数据为127.0.0.1
。第二个实例是loopback
。它具有IpAddrKind
的另一个变体作为其kind
值V6
,并具有与其关联的地址::1
。我们使用了一个结构体将kind
和address
值捆绑在一起,因此现在变体与该值相关联。
However, representing the same concept using just an enum is more concise:
rather than an enum inside a struct, we can put data directly into each enum
variant. This new definition of the IpAddr
enum says that both V4
and V6
variants will have associated String
values:
然而,仅使用枚举来表示相同的概念更简洁:我们可以将数据直接放入每个枚举变体中,而不是结构中的枚举。 IpAddr
枚举的新定义表示V4
和V6
变体都将具有关联的String
值:
We attach data to each variant of the enum directly, so there is no need for an
extra struct. Here, it’s also easier to see another detail of how enums work:
the name of each enum variant that we define also becomes a function that
constructs an instance of the enum. That is, IpAddr::V4()
is a function call
that takes a String
argument and returns an instance of the IpAddr
type. We
automatically get this constructor function defined as a result of defining the
enum.
我们直接将数据附加到枚举的每个变体,因此不需要额外的结构。在这里,还可以更容易地看到枚举如何工作的另一个细节:我们定义的每个枚举变体的名称也成为构造枚举实例的函数。也就是说, IpAddr::V4()
是一个函数调用,它接受String
参数并返回IpAddr
类型的实例。作为定义枚举的结果,我们自动定义了这个构造函数。
There’s another advantage to using an enum rather than a struct: each variant
can have different types and amounts of associated data. Version four IP
addresses will always have four numeric components that will have values
between 0 and 255. If we wanted to store V4
addresses as four u8
values but
still express V6
addresses as one String
value, we wouldn’t be able to with
a struct. Enums handle this case with ease:
使用枚举而不是结构体还有另一个优点:每个变体可以具有不同类型和数量的关联数据。版本四的 IP 地址将始终具有四个数字组件,其值介于 0 到 255 之间。如果我们想要将V4
地址存储为四个u8
值,但仍将V6
地址表示为一个String
值,我们将无法使用结构体。枚举可以轻松处理这种情况:
We’ve shown several different ways to define data structures to store version
four and version six IP addresses. However, as it turns out, wanting to store
IP addresses and encode which kind they are is so common that the standard
library has a definition we can use! Let’s look at how
the standard library defines IpAddr
: it has the exact enum and variants that
we’ve defined and used, but it embeds the address data inside the variants in
the form of two different structs, which are defined differently for each
variant:
我们展示了几种不同的方法来定义数据结构来存储第四版和第六版 IP 地址。然而,事实证明,想要存储 IP 地址并对其类型进行编码非常常见,以至于标准库有一个我们可以使用的定义!让我们看看标准库如何定义IpAddr
:它具有我们定义和使用的精确枚举和变体,但它以两种不同结构的形式将地址数据嵌入到变体中,每个结构体的定义不同:
This code illustrates that you can put any kind of data inside an enum variant:
strings, numeric types, or structs, for example. You can even include another
enum! Also, standard library types are often not much more complicated than
what you might come up with.
此代码说明您可以将任何类型的数据放入枚举变体中:例如字符串、数字类型或结构。您甚至可以包含另一个枚举!此外,标准库类型通常并不比您可能想到的复杂多少。
Note that even though the standard library contains a definition for IpAddr
,
we can still create and use our own definition without conflict because we
haven’t brought the standard library’s definition into our scope. We’ll talk
more about bringing types into scope in Chapter 7.
请注意,即使标准库包含IpAddr
的定义,我们仍然可以创建和使用我们自己的定义而不会发生冲突,因为我们尚未将标准库的定义纳入我们的范围。我们将在第 7 章中详细讨论将类型纳入作用域。
Let’s look at another example of an enum in Listing 6-2: this one has a wide
variety of types embedded in its variants.
让我们看一下清单 6-2 中的另一个枚举示例:这个枚举的变体中嵌入了多种类型。
This enum has four variants with different types:
该枚举有四种不同类型的变体:
Quit
has no data associated with it at all.Quit
根本没有与之相关的数据。Move
has named fields, like a struct does.Move
具有命名字段,就像结构一样。Write
includes a singleString
.Write
包含一个String
。ChangeColor
includes threei32
values.ChangeColor
包括三个i32
值。
Defining an enum with variants such as the ones in Listing 6-2 is similar to
defining different kinds of struct definitions, except the enum doesn’t use the
struct
keyword and all the variants are grouped together under the Message
type. The following structs could hold the same data that the preceding enum
variants hold:
使用诸如清单 6-2 中的变体定义枚举类似于定义不同类型的结构体定义,只不过枚举不使用struct
关键字并且所有变体都在Message
类型下分组在一起。以下结构可以保存与前面的枚举变体保存的相同数据:
But if we used the different structs, each of which has its own type, we
couldn’t as easily define a function to take any of these kinds of messages as
we could with the Message
enum defined in Listing 6-2, which is a single type.
但是,如果我们使用不同的结构,每个结构都有自己的类型,我们就无法像清单 6-2 中定义的Message
枚举那样轻松地定义一个函数来获取任何此类消息,该枚举是一个单一类型。
There is one more similarity between enums and structs: just as we’re able to
define methods on structs using impl
, we’re also able to define methods on
enums. Here’s a method named call
that we could define on our Message
enum:
枚举和结构之间还有一个相似之处:就像我们能够使用impl
在结构上定义方法一样,我们也能够在枚举上定义方法。这是一个名为call
方法,我们可以在Message
枚举上定义它:
The body of the method would use self
to get the value that we called the
method on. In this example, we’ve created a variable m
that has the value
Message::Write(String::from("hello"))
, and that is what self
will be in the
body of the call
method when m.call()
runs.
方法的主体将使用self
来获取我们调用该方法的值。在此示例中,我们创建了一个变量m
,其值为Message::Write(String::from("hello"))
,这self
当call
m.call()
运行。
Let’s look at another enum in the standard library that is very common and
useful: Option
.
让我们看一下标准库中另一个非常常见且有用的枚举: Option
。
The Option
Enum and Its Advantages Over Null Values
Option
枚举及其相对于空值的优势
This section explores a case study of Option
, which is another enum defined
by the standard library. The Option
type encodes the very common scenario in
which a value could be something or it could be nothing.
本节探讨Option
的案例研究,它是标准库定义的另一个枚举。 Option
类型对非常常见的场景进行编码,其中值可能是某物,也可能是什么。
For example, if you request the first item in a non-empty list, you would get
a value. If you request the first item in an empty list, you would get nothing.
Expressing this concept in terms of the type system means the compiler can
check whether you’ve handled all the cases you should be handling; this
functionality can prevent bugs that are extremely common in other programming
languages.
例如,如果您请求非空列表中的第一项,您将获得一个值。如果您请求空列表中的第一项,您将一无所获。用类型系统表达这个概念意味着编译器可以检查您是否已经处理了应该处理的所有情况;此功能可以防止其他编程语言中极其常见的错误。
Programming language design is often thought of in terms of which features you
include, but the features you exclude are important too. Rust doesn’t have the
null feature that many other languages have. Null is a value that means there
is no value there. In languages with null, variables can always be in one of
two states: null or not-null.
编程语言设计通常根据包含哪些功能来考虑,但排除哪些功能也很重要。 Rust 没有许多其他语言所具有的 null 功能。 Null是一个值,意味着那里没有值。在带有 null 的语言中,变量始终可以处于两种状态之一:null 或 not-null。
In his 2009 presentation “Null References: The Billion Dollar Mistake,” Tony
Hoare, the inventor of null, has this to say:
null 的发明者托尼·霍尔 (Tony Hoare) 在 2009 年的演讲“空引用:价值数十亿美元的错误”中说道:
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.
我称之为我的十亿美元错误。当时,我正在设计第一个面向对象语言的综合引用类型系统。我的目标是确保所有引用的使用都绝对安全,并由编译器自动执行检查。但我无法抗拒放入空引用的诱惑,只是因为它很容易实现。这导致了无数的错误、漏洞和系统崩溃,在过去四十年中可能造成了数十亿美元的痛苦和损失。
The problem with null values is that if you try to use a null value as a
not-null value, you’ll get an error of some kind. Because this null or not-null
property is pervasive, it’s extremely easy to make this kind of error.
空值的问题在于,如果您尝试将空值用作非空值,则会收到某种错误。由于 null 或非 null 属性非常普遍,因此很容易犯这种错误。
However, the concept that null is trying to express is still a useful one: a
null is a value that is currently invalid or absent for some reason.
然而,null 试图表达的概念仍然是一个有用的概念:null 是当前无效或由于某种原因不存在的值。
The problem isn’t really with the concept but with the particular
implementation. As such, Rust does not have nulls, but it does have an enum
that can encode the concept of a value being present or absent. This enum is
Option<T>
, and it is defined by the standard library
as follows:
问题实际上不在于概念,而在于特定的实现。因此,Rust 没有空值,但它有一个枚举,可以对值存在或不存在的概念进行编码。该枚举是Option<T>
,它由标准库忽略定义如下:
The Option<T>
enum is so useful that it’s even included in the prelude; you
don’t need to bring it into scope explicitly. Its variants are also included in
the prelude: you can use Some
and None
directly without the Option::
prefix. The Option<T>
enum is still just a regular enum, and Some(T)
and
None
are still variants of type Option<T>
.Option<T>
枚举非常有用,甚至包含在前奏中;您不需要明确地将其纳入范围。它的变体也包含在前奏中:您可以直接使用Some
和None
,而不需要Option::
前缀。 Option<T>
枚举仍然只是常规枚举,而Some(T)
和None
仍然是Option<T>
类型的变体。
The <T>
syntax is a feature of Rust we haven’t talked about yet. It’s a
generic type parameter, and we’ll cover generics in more detail in Chapter 10.
For now, all you need to know is that <T>
means that the Some
variant of
the Option
enum can hold one piece of data of any type, and that each
concrete type that gets used in place of T
makes the overall Option<T>
type
a different type. Here are some examples of using Option
values to hold
number types and string types:<T>
语法是 Rust 的一个特性,我们还没有讨论过。它是一个泛型类型参数,我们将在第 10 章中更详细地介绍泛型。现在,您需要知道的是<T>
意味着Option
枚举的Some
变体可以保存任意的一条数据类型,并且用于代替T
的每个具体类型使整个Option<T>
类型成为不同的类型。以下是使用Option
值保存数字类型和字符串类型的一些示例:
The type of some_number
is Option<i32>
. The type of some_char
is
Option<char>
, which is a different type. Rust can infer these types because
we’ve specified a value inside the Some
variant. For absent_number
, Rust
requires us to annotate the overall Option
type: the compiler can’t infer the
type that the corresponding Some
variant will hold by looking only at a
None
value. Here, we tell Rust that we mean for absent_number
to be of type
Option<i32>
.some_number
的类型是Option<i32>
。 some_char
的类型是Option<char>
,这是一种不同的类型。 Rust 可以推断这些类型,因为我们在Some
变体中指定了一个值。对于absent_number
,Rust 要求我们注释整个Option
类型:编译器无法仅通过查看None
值来推断相应Some
变体将持有的类型。在这里,我们告诉 Rust,我们的意思是absent_number
的类型为Option<i32>
。
When we have a Some
value, we know that a value is present and the value is
held within the Some
. When we have a None
value, in some sense it means the
same thing as null: we don’t have a valid value. So why is having Option<T>
any better than having null?
当我们有Some
值时,我们知道存在一个值并且该值保存在Some
中。当我们有一个None
值时,在某种意义上它与 null 意味着同样的事情:我们没有一个有效的值。那么为什么拥有Option<T>
比拥有 null 更好呢?
In short, because Option<T>
and T
(where T
can be any type) are different
types, the compiler won’t let us use an Option<T>
value as if it were
definitely a valid value. For example, this code won’t compile, because it’s
trying to add an i8
to an Option<i8>
:
简而言之,因为Option<T>
和T
(其中T
可以是任何类型)是不同的类型,所以编译器不会让我们使用Option<T>
值,就好像它绝对是有效值一样。例如,此代码将无法编译,因为它试图将i8
添加到Option<i8>
:
If we run this code, we get an error message like this one:
如果我们运行这段代码,我们会收到如下错误消息:
$ cargo run
Compiling enums v0.1.0 (file:///projects/enums)
error[E0277]: cannot add `Option<i8>` to `i8`
--> src/main.rs:5:17
|
5 | let sum = x + y;
| ^ no implementation for `i8 + Option<i8>`
|
= help: the trait `Add<Option<i8>>` is not implemented for `i8`
= help: the following other types implement trait `Add<Rhs>`:
<i8 as Add>
<i8 as Add<&i8>>
<&'a i8 as Add<i8>>
<&i8 as Add<&i8>>
For more information about this error, try `rustc --explain E0277`.
error: could not compile `enums` (bin "enums") due to 1 previous error
Intense! In effect, this error message means that Rust doesn’t understand how
to add an i8
and an Option<i8>
, because they’re different types. When we
have a value of a type like i8
in Rust, the compiler will ensure that we
always have a valid value. We can proceed confidently without having to check
for null before using that value. Only when we have an Option<i8>
(or
whatever type of value we’re working with) do we have to worry about possibly
not having a value, and the compiler will make sure we handle that case before
using the value.
激烈的!实际上,此错误消息意味着 Rust 不理解如何添加i8
和Option<i8>
,因为它们是不同的类型。当我们在 Rust 中拥有像i8
这样的类型的值时,编译器将确保我们始终拥有有效的值。我们可以放心地继续操作,而无需在使用该值之前检查 null 。仅当我们有Option<i8>
(或我们正在使用的任何类型的值)时,我们才需要担心可能没有值,并且编译器将确保我们在使用该值之前处理这种情况。
In other words, you have to convert an Option<T>
to a T
before you can
perform T
operations with it. Generally, this helps catch one of the most
common issues with null: assuming that something isn’t null when it actually is.
换句话说,您必须先将Option<T>
转换为T
,然后才能使用它执行T
操作。一般来说,这有助于捕获 null 最常见的问题之一:假设某些内容实际上不为 null。
Eliminating the risk of incorrectly assuming a not-null value helps you to be
more confident in your code. In order to have a value that can possibly be
null, you must explicitly opt in by making the type of that value Option<T>
.
Then, when you use that value, you are required to explicitly handle the case
when the value is null. Everywhere that a value has a type that isn’t an
Option<T>
, you can safely assume that the value isn’t null. This was a
deliberate design decision for Rust to limit null’s pervasiveness and increase
the safety of Rust code.
消除错误假设非空值的风险可以帮助您对代码更有信心。为了获得可能为 null 的值,您必须通过将该值的类型设置Option<T>
显式选择加入。然后,当您使用该值时,需要显式处理该值为 null 的情况。只要值的类型不是Option<T>
,您就可以安全地假设该值不为 null。这是 Rust 的一个深思熟虑的设计决策,旨在限制 null 的普遍性并提高 Rust 代码的安全性。
So how do you get the T
value out of a Some
variant when you have a value
of type Option<T>
so that you can use that value? The Option<T>
enum has a
large number of methods that are useful in a variety of situations; you can
check them out in its documentation. Becoming familiar
with the methods on Option<T>
will be extremely useful in your journey with
Rust.
那么,当您有Option<T>
类型的值时,如何从Some
变体中获取T
值以便可以使用该值呢? Option<T>
枚举具有大量可用于各种情况的方法;您可以在其文档中查看它们ignore。熟悉Option<T>
上的方法对于您的 Rust 之旅非常有用。
In general, in order to use an Option<T>
value, you want to have code that
will handle each variant. You want some code that will run only when you have a
Some(T)
value, and this code is allowed to use the inner T
. You want some
other code to run only if you have a None
value, and that code doesn’t have a
T
value available. The match
expression is a control flow construct that
does just this when used with enums: it will run different code depending on
which variant of the enum it has, and that code can use the data inside the
matching value.
通常,为了使用Option<T>
值,您需要拥有能够处理每个变体的代码。您希望某些代码仅当您具有Some(T)
值时才会运行,并且允许该代码使用内部T
。您希望某些其他代码仅在具有None
值且该代码没有可用的T
值时才运行。 match
表达式是一个控制流构造,与枚举一起使用时会执行此操作:它将根据其具有的枚举变体运行不同的代码,并且该代码可以使用匹配值内的数据。
The match
Control Flow Construct
match
控制流构造
Rust has an extremely powerful control flow construct called match
that
allows you to compare a value against a series of patterns and then execute
code based on which pattern matches. Patterns can be made up of literal values,
variable names, wildcards, and many other things; Chapter
18 covers all the different kinds of patterns
and what they do. The power of match
comes from the expressiveness of the
patterns and the fact that the compiler confirms that all possible cases are
handled.
Rust 有一个非常强大的控制流结构,称为match
,它允许您将一个值与一系列模式进行比较,然后根据模式匹配执行代码。模式可以由文字值、变量名、通配符和许多其他内容组成;第 18 章“忽略”涵盖了所有不同类型的模式及其作用。 match
的力量来自模式的表达能力以及编译器确认所有可能的情况都已处理的事实。
Think of a match
expression as being like a coin-sorting machine: coins slide
down a track with variously sized holes along it, and each coin falls through
the first hole it encounters that it fits into. In the same way, values go
through each pattern in a match
, and at the first pattern the value “fits,”
the value falls into the associated code block to be used during execution.
将match
表达式想象为硬币分类机:硬币沿着带有不同大小孔的轨道滑下,每枚硬币都会从它遇到的第一个适合的孔落下。以同样的方式,值会遍历match
中的每个模式,并且在第一个模式中值“适合”,该值落入要在执行期间使用的关联代码块中。
Speaking of coins, let’s use them as an example using match
! We can write a
function that takes an unknown US coin and, in a similar way as the counting
machine, determines which coin it is and returns its value in cents, as shown
in Listing 6-3.
说到硬币,让我们以它们为例,使用match
!我们可以编写一个函数,接受一枚未知的美国硬币,并以与计数机类似的方式确定它是哪种硬币并返回其价值(以美分为单位),如清单 6-3 所示。
Let’s break down the match
in the value_in_cents
function. First we list
the match
keyword followed by an expression, which in this case is the value
coin
. This seems very similar to a conditional expression used with if
, but
there’s a big difference: with if
, the condition needs to evaluate to a
Boolean value, but here it can be any type. The type of coin
in this example
is the Coin
enum that we defined on the first line.
让我们分解value_in_cents
函数中的match
。首先,我们列出match
关键字,后跟一个表达式,在本例中是值coin
。这看起来与if
中使用的条件表达式非常相似,但有一个很大的区别:对于if
,条件需要计算为布尔值,但这里它可以是任何类型。本例中的coin
类型是我们在第一行定义的Coin
枚举。
Next are the match
arms. An arm has two parts: a pattern and some code. The
first arm here has a pattern that is the value Coin::Penny
and then the =>
operator that separates the pattern and the code to run. The code in this case
is just the value 1
. Each arm is separated from the next with a comma.
接下来是match
臂。手臂有两部分:图案和代码。这里的第一个分支有一个模式,即值Coin::Penny
,然后是=>
运算符,该运算符将模式和要运行的代码分开。本例中的代码只是值1
。每个臂与下一个臂之间用逗号分隔。
When the match
expression executes, it compares the resultant value against
the pattern of each arm, in order. If a pattern matches the value, the code
associated with that pattern is executed. If that pattern doesn’t match the
value, execution continues to the next arm, much as in a coin-sorting machine.
We can have as many arms as we need: in Listing 6-3, our match
has four arms.
当match
表达式执行时,它会按顺序将结果值与每个臂的模式进行比较。如果模式与值匹配,则执行与该模式关联的代码。如果该模式与值不匹配,则继续执行下一个臂,就像硬币分类机一样。我们可以根据需要拥有任意数量的手臂:在清单 6-3 中,我们的match
有四个手臂。
The code associated with each arm is an expression, and the resultant value of
the expression in the matching arm is the value that gets returned for the
entire match
expression.
与每个臂关联的代码是一个表达式,匹配臂中表达式的结果值是整个match
表达式的返回值。
We don’t typically use curly brackets if the match arm code is short, as it is
in Listing 6-3 where each arm just returns a value. If you want to run multiple
lines of code in a match arm, you must use curly brackets, and the comma
following the arm is then optional. For example, the following code prints
“Lucky penny!” every time the method is called with a Coin::Penny
, but still
returns the last value of the block, 1
:
如果匹配臂代码很短,我们通常不会使用大括号,如清单 6-3 所示,其中每个臂仅返回一个值。如果要在匹配臂中运行多行代码,则必须使用大括号,并且臂后面的逗号是可选的。例如,以下代码打印“Lucky penny!”每次使用Coin::Penny
调用该方法时,但仍返回块的最后一个值1
:
Patterns That Bind to Values
与值绑定的模式
Another useful feature of match arms is that they can bind to the parts of the
values that match the pattern. This is how we can extract values out of enum
variants.
匹配臂的另一个有用的功能是它们可以绑定到与模式匹配的值的部分。这就是我们从枚举变量中提取值的方法。
As an example, let’s change one of our enum variants to hold data inside it.
From 1999 through 2008, the United States minted quarters with different
designs for each of the 50 states on one side. No other coins got state
designs, so only quarters have this extra value. We can add this information to
our enum
by changing the Quarter
variant to include a UsState
value
stored inside it, which we’ve done in Listing 6-4.
作为示例,让我们更改枚举变体之一以在其中保存数据。从 1999 年到 2008 年,美国为一侧 50 个州铸造了不同设计的 25 美分硬币。没有其他硬币有国家设计,因此只有 25 美分硬币具有这种额外价值。我们可以通过更改Quarter
变量以包含存储在其中的UsState
值来将此信息添加到我们的enum
中,如清单 6-4 中所示。
Let’s imagine that a friend is trying to collect all 50 state quarters. While
we sort our loose change by coin type, we’ll also call out the name of the
state associated with each quarter so that if it’s one our friend doesn’t have,
they can add it to their collection.
让我们想象一下,一位朋友正在尝试收集全部 50 个州 25 美分。当我们按硬币类型对零钱进行分类时,我们还会标出与每个季度相关的州名称,以便如果我们的朋友没有,他们可以将其添加到他们的收藏中。
In the match expression for this code, we add a variable called state
to the
pattern that matches values of the variant Coin::Quarter
. When a
Coin::Quarter
matches, the state
variable will bind to the value of that
quarter’s state. Then we can use state
in the code for that arm, like so:
在此代码的匹配表达式中,我们将一个名为state
的变量添加到与变体Coin::Quarter
的值匹配的模式中。当Coin::Quarter
匹配时, state
变量将绑定到该季度的状态值。然后我们可以在该手臂的代码中使用state
,如下所示:
If we were to call value_in_cents(Coin::Quarter(UsState::Alaska))
, coin
would be Coin::Quarter(UsState::Alaska)
. When we compare that value with each
of the match arms, none of them match until we reach Coin::Quarter(state)
. At
that point, the binding for state
will be the value UsState::Alaska
. We can
then use that binding in the println!
expression, thus getting the inner
state value out of the Coin
enum variant for Quarter
.
如果我们调用value_in_cents(Coin::Quarter(UsState::Alaska))
, coin
将是Coin::Quarter(UsState::Alaska)
。当我们将该值与每个匹配臂进行比较时,直到到达Coin::Quarter(state)
为止,它们都不匹配。此时, state
的绑定将是值UsState::Alaska
。然后我们可以在println!
表达式,从而从Quarter
Coin
枚举变体中获取内部状态值。
Matching with Option<T>
与Option<T>
匹配
In the previous section, we wanted to get the inner T
value out of the Some
case when using Option<T>
; we can also handle Option<T>
using match
, as
we did with the Coin
enum! Instead of comparing coins, we’ll compare the
variants of Option<T>
, but the way the match
expression works remains the
same.
在上一节中,我们希望在使用Option<T>
时从Some
case 中获取内部T
值;我们还可以使用match
处理Option<T>
,就像我们对Coin
枚举所做的那样!我们将比较Option<T>
的变体,而不是比较硬币,但match
表达式的工作方式保持不变。
Let’s say we want to write a function that takes an Option<i32>
and, if
there’s a value inside, adds 1 to that value. If there isn’t a value inside,
the function should return the None
value and not attempt to perform any
operations.
假设我们要编写一个接受Option<i32>
的函数,如果里面有值,则将该值加 1。如果内部没有值,则该函数应返回None
值并且不尝试执行任何操作。
This function is very easy to write, thanks to match
, and will look like
Listing 6-5.
得益于match
,这个函数非常容易编写,如清单 6-5 所示。
Let’s examine the first execution of plus_one
in more detail. When we call
plus_one(five)
, the variable x
in the body of plus_one
will have the
value Some(5)
. We then compare that against each match arm:
让我们更详细地检查plus_one
的第一次执行。当我们调用plus_one(five)
时, plus_one
主体中的变量x
值为Some(5)
。然后我们将其与每个匹配组进行比较:
The Some(5)
value doesn’t match the pattern None
, so we continue to the
next arm:Some(5)
值与模式None
不匹配,因此我们继续下一个分支:
Does Some(5)
match Some(i)
? It does! We have the same variant. The i
binds to the value contained in Some
, so i
takes the value 5
. The code in
the match arm is then executed, so we add 1 to the value of i
and create a
new Some
value with our total 6
inside.Some(5)
与Some(i)
匹配吗?确实如此!我们有相同的变体。 i
绑定到Some
中包含的值,因此i
的值为5
。然后执行 match 臂中的代码,因此我们将i
的值加 1 并创建一个新的Some
值,其中包含总计6
。
Now let’s consider the second call of plus_one
in Listing 6-5, where x
is
None
. We enter the match
and compare to the first arm:
现在让我们考虑清单 6-5 中plus_one
的第二次调用,其中x
是None
。我们进入match
并与第一组进行比较:
It matches! There’s no value to add to, so the program stops and returns the
None
value on the right side of =>
. Because the first arm matched, no other
arms are compared.
很匹配!没有可添加的值,因此程序停止并返回=>
右侧的None
值。由于第一个臂已匹配,因此不会比较其他臂。
Combining match
and enums is useful in many situations. You’ll see this
pattern a lot in Rust code: match
against an enum, bind a variable to the
data inside, and then execute code based on it. It’s a bit tricky at first, but
once you get used to it, you’ll wish you had it in all languages. It’s
consistently a user favorite.
组合match
和枚举在许多情况下都很有用。您会在 Rust 代码中经常看到这种模式:与枚举match
,将变量绑定到内部数据,然后基于它执行代码。一开始有点棘手,但一旦习惯了,您会希望拥有所有语言版本。它始终是用户的最爱。
Matches Are Exhaustive 比赛内容详尽
There’s one other aspect of match
we need to discuss: the arms’ patterns must
cover all possibilities. Consider this version of our plus_one
function,
which has a bug and won’t compile:
我们还需要讨论match
的另一个方面:手臂的图案必须涵盖所有可能性。考虑我们的plus_one
函数的这个版本,它有一个错误并且无法编译:
We didn’t handle the None
case, so this code will cause a bug. Luckily, it’s
a bug Rust knows how to catch. If we try to compile this code, we’ll get this
error:
我们没有处理None
情况,因此这段代码会导致错误。幸运的是,Rust 知道如何捕获这个错误。如果我们尝试编译此代码,我们将收到此错误:
$ cargo run
Compiling enums v0.1.0 (file:///projects/enums)
error[E0004]: non-exhaustive patterns: `None` not covered
--> src/main.rs:3:15
|
3 | match x {
| ^ pattern `None` not covered
|
note: `Option<i32>` defined here
--> /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/core/src/option.rs:572:1
::: /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/core/src/option.rs:576:5
|
= note: not covered
= note: the matched value is of type `Option<i32>`
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) => Some(i + 1),
5 ~ None => todo!(),
|
For more information about this error, try `rustc --explain E0004`.
error: could not compile `enums` (bin "enums") due to 1 previous error
Rust knows that we didn’t cover every possible case, and even knows which
pattern we forgot! Matches in Rust are exhaustive: we must exhaust every last
possibility in order for the code to be valid. Especially in the case of
Option<T>
, when Rust prevents us from forgetting to explicitly handle the
None
case, it protects us from assuming that we have a value when we might
have null, thus making the billion-dollar mistake discussed earlier impossible.
Rust 知道我们没有涵盖所有可能的情况,甚至知道我们忘记了哪种模式! Rust 中的匹配是详尽的:我们必须穷尽所有最后的可能性才能使代码有效。特别是在Option<T>
的情况下,当 Rust 防止我们忘记显式处理None
情况时,它可以保护我们在可能有 null 的情况下假设我们有一个值,从而使之前讨论的数十亿美元的错误成为不可能。
Catch-all Patterns and the _
Placeholder
包罗万象的模式和_
占位符
Using enums, we can also take special actions for a few particular values, but
for all other values take one default action. Imagine we’re implementing a game
where, if you roll a 3 on a dice roll, your player doesn’t move, but instead
gets a new fancy hat. If you roll a 7, your player loses a fancy hat. For all
other values, your player moves that number of spaces on the game board. Here’s
a match
that implements that logic, with the result of the dice roll
hardcoded rather than a random value, and all other logic represented by
functions without bodies because actually implementing them is out of scope for
this example:
使用枚举,我们还可以对一些特定值采取特殊操作,但对所有其他值采取一种默认操作。想象一下,我们正在实现一个游戏,如果您在骰子上掷出 3,您的玩家不会移动,而是会获得一顶新的精美帽子。如果你掷出 7,你的玩家就会失去一顶漂亮的帽子。对于所有其他值,您的玩家将在游戏板上移动该数量的空格。这是一个实现该逻辑的match
,掷骰子的结果是硬编码的而不是随机值,所有其他逻辑都由没有主体的函数表示,因为实际实现它们超出了本示例的范围:
For the first two arms, the patterns are the literal values 3
and 7
. For
the last arm that covers every other possible value, the pattern is the
variable we’ve chosen to name other
. The code that runs for the other
arm
uses the variable by passing it to the move_player
function.
对于前两个臂,模式是文字值3
和7
。对于覆盖所有其他可能值的最后一个臂,模式是我们选择命名为other
变量。为other
手臂运行的代码通过将变量传递给move_player
函数来使用该变量。
This code compiles, even though we haven’t listed all the possible values a
u8
can have, because the last pattern will match all values not specifically
listed. This catch-all pattern meets the requirement that match
must be
exhaustive. Note that we have to put the catch-all arm last because the
patterns are evaluated in order. If we put the catch-all arm earlier, the other
arms would never run, so Rust will warn us if we add arms after a catch-all!
即使我们没有列出u8
可以具有的所有可能值,此代码也会编译,因为最后一个模式将匹配所有未特别列出的值。这种包罗万象的模式满足match
必须详尽的要求。请注意,我们必须将全能臂放在最后,因为模式是按顺序评估的。如果我们提前放置 catch-all 手臂,其他手臂将永远不会运行,因此如果我们在 catch-all 之后添加手臂,Rust 会警告我们!
Rust also has a pattern we can use when we want a catch-all but don’t want to
use the value in the catch-all pattern: _
is a special pattern that matches
any value and does not bind to that value. This tells Rust we aren’t going to
use the value, so Rust won’t warn us about an unused variable.
Rust 还有一个当我们想要包罗万象但又不想使用包罗万象模式中的值时可以使用的模式: _
是一种特殊模式,可以匹配任何值但不绑定到该值。这告诉 Rust 我们不会使用该值,因此 Rust 不会警告我们有关未使用的变量。
Let’s change the rules of the game: now, if you roll anything other than a 3 or
a 7, you must roll again. We no longer need to use the catch-all value, so we
can change our code to use _
instead of the variable named other
:
让我们改变游戏规则:现在,如果你掷出 3 或 7 以外的任何东西,你必须再次掷出。我们不再需要使用 catch-all 值,因此我们可以更改代码以使用_
而不是名为other
变量:
This example also meets the exhaustiveness requirement because we’re explicitly
ignoring all other values in the last arm; we haven’t forgotten anything.
此示例也满足详尽性要求,因为我们明确忽略了最后一个臂中的所有其他值;我们没有忘记任何事情。
Finally, we’ll change the rules of the game one more time so that nothing else
happens on your turn if you roll anything other than a 3 or a 7. We can express
that by using the unit value (the empty tuple type we mentioned in “The Tuple
Type” section) as the code that goes with the _
arm:
最后,我们将再次更改游戏规则,这样,如果您掷出 3 或 7 以外的任何内容,则轮到您时不会发生任何其他情况。我们可以使用单位值(我们提到的空元组类型)来表达这一点在“元组类型”忽略部分中)作为与_
一起使用的代码:
Here, we’re telling Rust explicitly that we aren’t going to use any other value
that doesn’t match a pattern in an earlier arm, and we don’t want to run any
code in this case.
在这里,我们明确告诉 Rust,我们不会使用与早期分支中的模式不匹配的任何其他值,并且在这种情况下我们不想运行任何代码。
There’s more about patterns and matching that we’ll cover in Chapter
18. For now, we’re going to move on to the
if let
syntax, which can be useful in situations where the match
expression
is a bit wordy.
我们将在第 18 章中介绍更多关于模式和匹配的内容。现在,我们将继续讨论if let
语法,它在match
表达式有点冗长的情况下很有用。
Concise Control Flow with if let
使用if let
简洁控制流程
The if let
syntax lets you combine if
and let
into a less verbose way to
handle values that match one pattern while ignoring the rest. Consider the
program in Listing 6-6 that matches on an Option<u8>
value in the
config_max
variable but only wants to execute code if the value is the Some
variant.if let
语法允许您将if
和let
组合成一种不太冗长的方式来处理与一种模式匹配的值,同时忽略其余模式。考虑清单 6-6 中的程序,它匹配config_max
变量中的Option<u8>
值,但只想在该值是Some
变体时执行代码。
If the value is Some
, we print out the value in the Some
variant by binding
the value to the variable max
in the pattern. We don’t want to do anything
with the None
value. To satisfy the match
expression, we have to add _ => ()
after processing just one variant, which is annoying boilerplate code to
add.
如果值为Some
,我们通过将该值绑定到模式中的变量max
来打印Some
变体中的值。我们不想对None
值做任何事情。为了满足match
表达式,我们必须在仅处理一个变体后添加_ => ()
,这是令人讨厌的样板代码。
Instead, we could write this in a shorter way using if let
. The following
code behaves the same as the match
in Listing 6-6:
相反,我们可以使用if let
以更短的方式编写它。以下代码的行为与清单 6-6 中的match
相同:
The syntax if let
takes a pattern and an expression separated by an equal
sign. It works the same way as a match
, where the expression is given to the
match
and the pattern is its first arm. In this case, the pattern is
Some(max)
, and the max
binds to the value inside the Some
. We can then
use max
in the body of the if let
block in the same way we used max
in
the corresponding match
arm. The code in the if let
block isn’t run if the
value doesn’t match the pattern.
语法if let
采用由等号分隔的模式和表达式。它的工作方式与match
相同,其中表达式被赋予match
,模式是它的第一个分支。在本例中,模式为Some(max)
,并且max
绑定到Some
内的值。然后,我们可以在if let
块的主体中使用max
,就像我们在相应的match
臂中使用max
一样。如果值与模式不匹配,则if let
块中的代码不会运行。
Using if let
means less typing, less indentation, and less boilerplate code.
However, you lose the exhaustive checking that match
enforces. Choosing
between match
and if let
depends on what you’re doing in your particular
situation and whether gaining conciseness is an appropriate trade-off for
losing exhaustive checking.
使用if let
意味着更少的打字、更少的缩进和更少的样板代码。但是,您会失去match
强制执行的详尽检查。在match
和if let
之间进行选择取决于您在特定情况下所做的事情,以及获得简洁性是否是失去详尽检查的适当权衡。
In other words, you can think of if let
as syntax sugar for a match
that
runs code when the value matches one pattern and then ignores all other values.
换句话说,您可以将if let
视为match
语法糖,当值与一种模式匹配时运行代码,然后忽略所有其他值。
We can include an else
with an if let
. The block of code that goes with the
else
is the same as the block of code that would go with the _
case in the
match
expression that is equivalent to the if let
and else
. Recall the
Coin
enum definition in Listing 6-4, where the Quarter
variant also held a
UsState
value. If we wanted to count all non-quarter coins we see while also
announcing the state of the quarters, we could do that with a match
expression, like this:
我们可以在if let
中包含else
。与else
一起使用的代码块与与match
表达式中的_
case 一起使用的代码块相同,相当于if let
和else
。回想一下清单 6-4 中的Coin
枚举定义,其中Quarter
变量还包含一个UsState
值。如果我们想计算我们看到的所有非 25 分硬币,同时宣布 25 分硬币的状态,我们可以使用match
表达式来实现,如下所示:
Or we could use an if let
and else
expression, like this:
或者我们可以使用if let
和else
表达式,如下所示:
If you have a situation in which your program has logic that is too verbose to
express using a match
, remember that if let
is in your Rust toolbox as well.
如果您的程序的逻辑过于冗长而无法使用match
来表达,请记住if let
也在您的 Rust 工具箱中。
Summary 概括
We’ve now covered how to use enums to create custom types that can be one of a
set of enumerated values. We’ve shown how the standard library’s Option<T>
type helps you use the type system to prevent errors. When enum values have
data inside them, you can use match
or if let
to extract and use those
values, depending on how many cases you need to handle.
我们现在已经介绍了如何使用枚举来创建可以是一组枚举值之一的自定义类型。我们展示了标准库的Option<T>
类型如何帮助您使用类型系统来防止错误。当枚举值内部包含数据时,您可以使用match
或if let
来提取和使用这些值,具体取决于您需要处理的情况数量。
Your Rust programs can now express concepts in your domain using structs and
enums. Creating custom types to use in your API ensures type safety: the
compiler will make certain your functions only get values of the type each
function expects.
您的 Rust 程序现在可以使用结构和枚举来表达您领域中的概念。创建在 API 中使用的自定义类型可确保类型安全:编译器将确保您的函数仅获取每个函数期望的类型的值。
In order to provide a well-organized API to your users that is straightforward
to use and only exposes exactly what your users will need, let’s now turn to
Rust’s modules.
为了向用户提供组织良好、易于使用且仅公开用户需要的 API,现在让我们转向 Rust 的模块。
Managing Growing Projects with Packages, Crates, and Modules
使用包、板条箱和模块管理不断增长的项目
As you write large programs, organizing your code will become increasingly
important. By grouping related functionality and separating code with distinct
features, you’ll clarify where to find code that implements a particular
feature and where to go to change how a feature works.
当您编写大型程序时,组织代码将变得越来越重要。通过对相关功能进行分组并将代码与不同的功能分开,您将弄清楚在哪里可以找到实现特定功能的代码以及在哪里可以更改功能的工作方式。
The programs we’ve written so far have been in one module in one file. As a
project grows, you should organize code by splitting it into multiple modules
and then multiple files. A package can contain multiple binary crates and
optionally one library crate. As a package grows, you can extract parts into
separate crates that become external dependencies. This chapter covers all
these techniques. For very large projects comprising a set of interrelated
packages that evolve together, Cargo provides workspaces, which we’ll cover
in the “Cargo Workspaces” section in Chapter 14.
到目前为止,我们编写的程序都位于一个文件的一个模块中。随着项目的增长,您应该通过将代码拆分为多个模块,然后拆分为多个文件来组织代码。一个包可以包含多个二进制 crate,也可以包含一个库 crate。随着包的增长,您可以将各个部分提取到单独的包中,这些包将成为外部依赖项。本章涵盖了所有这些技术。对于由一组共同发展的相互关联的包组成的非常大的项目,Cargo 提供了工作空间,我们将在第 14 章的“Cargo 工作空间”忽略部分中介绍它。
We’ll also discuss encapsulating implementation details, which lets you reuse
code at a higher level: once you’ve implemented an operation, other code can
call your code via its public interface without having to know how the
implementation works. The way you write code defines which parts are public for
other code to use and which parts are private implementation details that you
reserve the right to change. This is another way to limit the amount of detail
you have to keep in your head.
我们还将讨论封装实现细节,这使您可以在更高级别重用代码:一旦实现了一个操作,其他代码就可以通过其公共接口调用您的代码,而无需了解实现的工作原理。您编写代码的方式定义了哪些部分是可供其他代码使用的公共部分,以及哪些部分是您保留更改权利的私有实现细节。这是限制您必须记住的细节数量的另一种方法。
A related concept is scope: the nested context in which code is written has a
set of names that are defined as “in scope.” When reading, writing, and
compiling code, programmers and compilers need to know whether a particular
name at a particular spot refers to a variable, function, struct, enum, module,
constant, or other item and what that item means. You can create scopes and
change which names are in or out of scope. You can’t have two items with the
same name in the same scope; tools are available to resolve name conflicts.
一个相关的概念是范围:编写代码的嵌套上下文有一组定义为“范围内”的名称。在读取、编写和编译代码时,程序员和编译器需要知道特定位置的特定名称是否引用变量、函数、结构、枚举、模块、常量或其他项目以及该项目的含义。您可以创建范围并更改范围内或范围外的名称。同一范围内不能有两个同名的项目;可以使用工具来解决名称冲突。
Rust has a number of features that allow you to manage your code’s
organization, including which details are exposed, which details are private,
and what names are in each scope in your programs. These features, sometimes
collectively referred to as the module system, include:
Rust 具有许多功能,可让您管理代码的组织,包括公开哪些详细信息、哪些详细信息是私有的,以及程序中每个范围内的名称。这些功能有时统称为模块系统,包括:
- Packages: A Cargo feature that lets you build, test, and share crates
Packages: Cargo 功能,可让您构建、测试和共享 crate - Crates: A tree of modules that produces a library or executable
板条箱:生成库或可执行文件的模块树 - Modules and use: Let you control the organization, scope, and
privacy of paths
模块和使用:让您控制路径的组织、范围和隐私 - Paths: A way of naming an item, such as a struct, function, or module
路径:命名项目(例如结构、函数或模块)的一种方式
In this chapter, we’ll cover all these features, discuss how they interact, and
explain how to use them to manage scope. By the end, you should have a solid
understanding of the module system and be able to work with scopes like a pro!
在本章中,我们将介绍所有这些功能,讨论它们如何交互,并解释如何使用它们来管理范围。最后,您应该对模块系统有深入的了解,并能够像专业人士一样使用示波器!
Packages and Crates 包装和板条箱
The first parts of the module system we’ll cover are packages and crates.
我们将介绍的模块系统的第一部分是包和板条箱。
A crate is the smallest amount of code that the Rust compiler considers at a
time. Even if you run rustc
rather than cargo
and pass a single source code
file (as we did all the way back in the “Writing and Running a Rust Program”
section of Chapter 1), the compiler considers that file to be a crate. Crates
can contain modules, and the modules may be defined in other files that get
compiled with the crate, as we’ll see in the coming sections.
箱子是 Rust 编译器一次考虑的最小代码量。即使您运行rustc
而不是cargo
并传递单个源代码文件(正如我们在第 1 章的“编写和运行 Rust 程序”部分所做的那样),编译器也会认为该文件是一个 crate。板条箱可以包含模块,并且模块可以在与板条箱一起编译的其他文件中定义,正如我们将在接下来的部分中看到的那样。
A crate can come in one of two forms: a binary crate or a library crate.
Binary crates are programs you can compile to an executable that you can run,
such as a command-line program or a server. Each must have a function called
main
that defines what happens when the executable runs. All the crates we’ve
created so far have been binary crates.
板条箱可以采用以下两种形式之一:二进制板条箱或库板条箱。二进制包是可以编译为可以运行的可执行文件的程序,例如命令行程序或服务器。每个都必须有一个名为main
函数,该函数定义可执行文件运行时会发生什么。到目前为止,我们创建的所有 crate 都是二进制 crate。
Library crates don’t have a main
function, and they don’t compile to an
executable. Instead, they define functionality intended to be shared with
multiple projects. For example, the rand
crate we used in Chapter
2 provides functionality that generates random numbers.
Most of the time when Rustaceans say “crate”, they mean library crate, and they
use “crate” interchangeably with the general programming concept of a “library“.
库包没有main
函数,并且它们不会编译为可执行文件。相反,它们定义了旨在与多个项目共享的功能。例如,我们在第 2 章中使用的rand
crateignore 提供了生成随机数的功能。大多数时候,Rustaceans 说“crate”时,他们指的是库 crate,并且他们将“crate”与“库”的一般编程概念互换使用。
The crate root is a source file that the Rust compiler starts from and makes
up the root module of your crate (we’ll explain modules in depth in the
“Defining Modules to Control Scope and Privacy”
section).
crate 根是 Rust 编译器启动的源文件,并构成 crate 的根模块(我们将在“定义控制范围和隐私的模块”忽略部分中深入解释模块)。
A package is a bundle of one or more crates that provides a set of
functionality. A package contains a Cargo.toml file that describes how to
build those crates. Cargo is actually a package that contains the binary crate
for the command-line tool you’ve been using to build your code. The Cargo
package also contains a library crate that the binary crate depends on. Other
projects can depend on the Cargo library crate to use the same logic the Cargo
command-line tool uses.
包是一个或多个提供一组功能的包的捆绑。包中包含一个Cargo.toml文件,该文件描述了如何构建这些 crate。 Cargo 实际上是一个包,其中包含您用来构建代码的命令行工具的二进制包。 Cargo 包还包含二进制 crate 所依赖的库 crate。其他项目可以依赖 Cargo 库 crate 来使用 Cargo 命令行工具使用的相同逻辑。
A crate can come in one of two forms: a binary crate or a library crate. A
package can contain as many binary crates as you like, but at most only one
library crate. A package must contain at least one crate, whether that’s a
library or binary crate.
板条箱可以采用以下两种形式之一:二进制板条箱或库板条箱。一个包可以包含任意多个二进制 crate,但最多只能包含一个库 crate。一个包必须至少包含一个 crate,无论是库还是二进制 crate。
Let’s walk through what happens when we create a package. First we enter the
command cargo new my-project
:
让我们来看看创建包时会发生什么。首先我们输入命令cargo new my-project
:
$ cargo new my-project
Created binary (application) `my-project` package
$ ls my-project
Cargo.toml
src
$ ls my-project/src
main.rs
After we run cargo new my-project
, we use ls
to see what Cargo creates. In
the project directory, there’s a Cargo.toml file, giving us a package.
There’s also a src directory that contains main.rs. Open Cargo.toml in
your text editor, and note there’s no mention of src/main.rs. Cargo follows a
convention that src/main.rs is the crate root of a binary crate with the same
name as the package. Likewise, Cargo knows that if the package directory
contains src/lib.rs, the package contains a library crate with the same name
as the package, and src/lib.rs is its crate root. Cargo passes the crate root
files to rustc
to build the library or binary.
运行cargo new my-project
后,我们使用ls
来查看 Cargo 创建了什么。在项目目录中,有一个Cargo.toml文件,为我们提供了一个包。还有一个包含main.rs的src目录。在文本编辑器中打开Cargo.toml ,请注意没有提及src/main.rs 。 Cargo 遵循一个约定,即src/main.rs是与包同名的二进制 crate 的 crate 根。同样,Cargo 知道如果包目录包含src/lib.rs ,则该包包含一个与该包同名的库 crate,并且src/lib.rs是其 crate 根。 Cargo 将板条箱根文件传递给rustc
以构建库或二进制文件。
Here, we have a package that only contains src/main.rs, meaning it only
contains a binary crate named my-project
. If a package contains src/main.rs
and src/lib.rs, it has two crates: a binary and a library, both with the same
name as the package. A package can have multiple binary crates by placing files
in the src/bin directory: each file will be a separate binary crate.
在这里,我们有一个仅包含src/main.rs的包,这意味着它仅包含一个名为my-project
的二进制包。如果一个包包含src/main.rs和src/lib.rs ,它有两个 crate:一个二进制文件和一个库,两者都与包同名。通过将文件放置在src/bin目录中,一个包可以拥有多个二进制 crate:每个文件将是一个单独的二进制 crate。
Defining Modules to Control Scope and Privacy
定义模块来控制范围和隐私
In this section, we’ll talk about modules and other parts of the module system,
namely paths, which allow you to name items; the use
keyword that brings a
path into scope; and the pub
keyword to make items public. We’ll also discuss
the as
keyword, external packages, and the glob operator.
在本节中,我们将讨论模块和模块系统的其他部分,即路径,它允许您命名项目; use
关键字将路径引入范围;和pub
关键字使项目公开。我们还将讨论as
关键字、外部包和 glob 运算符。
Modules Cheat Sheet 模块备忘单
Before we get to the details of modules and paths, here we provide a quick
reference on how modules, paths, the use
keyword, and the pub
keyword work
in the compiler, and how most developers organize their code. We’ll be going
through examples of each of these rules throughout this chapter, but this is a
great place to refer to as a reminder of how modules work.
在详细介绍模块和路径之前,我们先提供一个快速参考,了解模块、路径、 use
关键字和pub
关键字如何在编译器中工作,以及大多数开发人员如何组织他们的代码。我们将在本章中介绍每条规则的示例,但这是一个很好的地方,可以用来提醒模块如何工作。
- Start from the crate root: When compiling a crate, the compiler first
looks in the crate root file (usually src/lib.rs for a library crate or
src/main.rs for a binary crate) for code to compile.
从 crate 根开始:编译 crate 时,编译器首先在 crate 根文件(对于库 crate 通常为 src/lib.rs ,对于二进制 crate 通常为src/main.rs )查找要编译的代码。 - Declaring modules: In the crate root file, you can declare new modules;
say you declare a “garden” module with
mod garden;
. The compiler will look for the module’s code in these places:
声明模块:在 crate 根文件中,您可以声明新模块; 假设你用mod garden;
。编译器会看 对于这些地方的模块代码:- Inline, within curly brackets that replace the semicolon following
mod garden
内联,在大括号内,替换mod garden
后面的分号 - In the file src/garden.rs
在文件src/garden.rs中 - In the file src/garden/mod.rs
在文件src/garden/mod.rs中
- Inline, within curly brackets that replace the semicolon following
- Declaring submodules: In any file other than the crate root, you can
declare submodules. For example, you might declare
mod vegetables;
in src/garden.rs. The compiler will look for the submodule’s code within the directory named for the parent module in these places:
声明子模块:在除 crate 根目录之外的任何文件中,您可以 声明子模块。例如,您可以声明mod vegetables;
在 src/garden.rs 。编译器将在以下位置查找子模块的代码 在这些位置以父模块命名的目录:- Inline, directly following
mod vegetables
, within curly brackets instead of the semicolon
内联,直接跟在mod vegetables
后面,在大括号内而不是分号内 - In the file src/garden/vegetables.rs
在文件src/garden/vegetables.rs中 - In the file src/garden/vegetables/mod.rs
在文件src/garden/vegetables/mod.rs中
- Inline, directly following
- Paths to code in modules: Once a module is part of your crate, you can
refer to code in that module from anywhere else in that same crate, as long
as the privacy rules allow, using the path to the code. For example, an
Asparagus
type in the garden vegetables module would be found atcrate::garden::vegetables::Asparagus
.
模块中代码的路径:一旦模块成为您的 crate 的一部分,只要隐私规则允许,您就可以使用代码的路径从同一 crate 中的其他任何位置引用该模块中的代码。例如,花园蔬菜模块中的Asparagus
类型可以在crate::garden::vegetables::Asparagus
中找到。 - Private vs. public: Code within a module is private from its parent
modules by default. To make a module public, declare it with
pub mod
instead ofmod
. To make items within a public module public as well, usepub
before their declarations.
私有与公共:默认情况下,模块内的代码对其父模块而言是私有的。要使模块公开,请使用pub mod
而不是mod
声明它。要使公共模块中的项目也成为公共的,请在其声明之前使用pub
。 - The
use
keyword: Within a scope, theuse
keyword creates shortcuts to items to reduce repetition of long paths. In any scope that can refer tocrate::garden::vegetables::Asparagus
, you can create a shortcut withuse crate::garden::vegetables::Asparagus;
and from then on you only need to writeAsparagus
to make use of that type in the scope.use
关键字:在某个范围内,use
关键字创建项目的快捷方式以减少长路径的重复。在任何可以引用crate::garden::vegetables::Asparagus
作用域中,您可以use crate::garden::vegetables::Asparagus;
从那时起,您只需要编写Asparagus
即可在作用域中使用该类型。
Here, we create a binary crate named backyard
that illustrates these rules.
The crate’s directory, also named backyard
, contains these files and
directories:
在这里,我们创建一个名为backyard
的二进制箱来说明这些规则。该板条箱的目录也称为backyard
,包含以下文件和目录:
backyard
├── Cargo.lock
├── Cargo.toml
└── src
├── garden
│ └── vegetables.rs
├── garden.rs
└── main.rs
The crate root file in this case is src/main.rs, and it contains:
本例中的板条箱根文件是src/main.rs ,它包含:
Filename: src/main.rs 文件名:src/main.rs
use crate::garden::vegetables::Asparagus;
pub mod garden;
fn main() {
let plant = Asparagus {};
println!("I'm growing {plant:?}!");
}
The pub mod garden;
line tells the compiler to include the code it finds in
src/garden.rs, which is:pub mod garden;
该行告诉编译器包含在src/garden.rs中找到的代码,即:
Filename: src/garden.rs 文件名:src/garden.rs
pub mod vegetables;
Here, pub mod vegetables;
means the code in src/garden/vegetables.rs is
included too. That code is:
在这里, pub mod vegetables;
意味着src/garden/vegetables.rs中的代码也包含在内。该代码是:
#[derive(Debug)]
pub struct Asparagus {}
Now let’s get into the details of these rules and demonstrate them in action!
现在让我们详细了解这些规则并在实践中演示它们!
Grouping Related Code in Modules
将相关代码分组到模块中
Modules let us organize code within a crate for readability and easy reuse.
Modules also allow us to control the privacy of items because code within a
module is private by default. Private items are internal implementation details
not available for outside use. We can choose to make modules and the items
within them public, which exposes them to allow external code to use and depend
on them.
模块让我们可以在包内组织代码,以提高可读性和易于重用。模块还允许我们控制项目的隐私,因为模块内的代码默认是私有的。私有项目是内部实现细节,不可供外部使用。我们可以选择将模块及其中的项目公开,从而公开它们以允许外部代码使用和依赖它们。
As an example, let’s write a library crate that provides the functionality of a
restaurant. We’ll define the signatures of functions but leave their bodies
empty to concentrate on the organization of the code rather than the
implementation of a restaurant.
作为示例,让我们编写一个提供餐厅功能的库箱。我们将定义函数的签名,但将其主体留空,以便专注于代码的组织而不是餐厅的实现。
In the restaurant industry, some parts of a restaurant are referred to as
front of house and others as back of house. Front of house is where
customers are; this encompasses where the hosts seat customers, servers take
orders and payment, and bartenders make drinks. Back of house is where the
chefs and cooks work in the kitchen, dishwashers clean up, and managers do
administrative work.
在餐饮业中,餐厅的某些部分称为前台,其他部分称为后台。前台是顾客所在的地方;这包括主人让顾客就座、服务员接受订单和付款以及调酒师调制饮料的地方。后厨是厨师和厨师在厨房工作、洗碗机清洁以及经理进行行政工作的地方。
To structure our crate in this way, we can organize its functions into nested
modules. Create a new library named restaurant
by running cargo new restaurant --lib
. Then enter the code in Listing 7-1 into src/lib.rs to
define some modules and function signatures; this code is the front of house
section.
为了以这种方式构建我们的箱子,我们可以将其功能组织到嵌套模块中。通过运行cargo new restaurant --lib
创建一个名为restaurant
新库。然后将清单7-1中的代码输入到src/lib.rs中,定义一些模块和函数签名;此代码是房屋前部部分。
Filename: src/lib.rs 文件名:src/lib.rs
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() {}
}
}
We define a module with the mod
keyword followed by the name of the module
(in this case, front_of_house
). The body of the module then goes inside curly
brackets. Inside modules, we can place other modules, as in this case with the
modules hosting
and serving
. Modules can also hold definitions for other
items, such as structs, enums, constants, traits, and—as in Listing
7-1—functions.
我们使用mod
关键字定义一个模块,后跟模块名称(在本例中front_of_house
)。然后模块的主体进入大括号内。在模块内部,我们可以放置其他模块,就像本例中的hosting
和serving
模块一样。模块还可以保存其他项目的定义,例如结构、枚举、常量、特征以及(如清单 7-1 所示)函数。
By using modules, we can group related definitions together and name why
they’re related. Programmers using this code can navigate the code based on the
groups rather than having to read through all the definitions, making it easier
to find the definitions relevant to them. Programmers adding new functionality
to this code would know where to place the code to keep the program organized.
通过使用模块,我们可以将相关的定义分组在一起并指出它们相关的原因。使用此代码的程序员可以根据组导航代码,而不必通读所有定义,从而更容易找到与其相关的定义。向此代码添加新功能的程序员将知道将代码放置在哪里以保持程序的组织性。
Earlier, we mentioned that src/main.rs and src/lib.rs are called crate
roots. The reason for their name is that the contents of either of these two
files form a module named crate
at the root of the crate’s module structure,
known as the module tree.
之前,我们提到src/main.rs和src/lib.rs称为 crate 根。它们的名称的原因是这两个文件中的任何一个的内容在 crate 模块结构的根部形成一个名为crate
模块,称为模块树。
Listing 7-2 shows the module tree for the structure in Listing 7-1.
清单 7-2 显示了清单 7-1 中结构的模块树。
crate
└── front_of_house
├── hosting
│ ├── add_to_waitlist
│ └── seat_at_table
└── serving
├── take_order
├── serve_order
└── take_payment
This tree shows how some of the modules nest inside other modules; for example,
hosting
nests inside front_of_house
. The tree also shows that some modules
are siblings, meaning they’re defined in the same module; hosting
and
serving
are siblings defined within front_of_house
. If module A is
contained inside module B, we say that module A is the child of module B and
that module B is the parent of module A. Notice that the entire module tree
is rooted under the implicit module named crate
.
该树显示了一些模块如何嵌套在其他模块中;例如,在front_of_house
内hosting
巢穴。该树还显示一些模块是兄弟模块,这意味着它们是在同一模块中定义的; hosting
和serving
是front_of_house
中定义的兄弟。如果模块 A 包含在模块 B 内,则我们说模块 A 是模块 B 的子级,而模块 B 是模块 A 的父级。请注意,整个模块树的根位于名为crate
的隐式模块下。
The module tree might remind you of the filesystem’s directory tree on your
computer; this is a very apt comparison! Just like directories in a filesystem,
you use modules to organize your code. And just like files in a directory, we
need a way to find our modules.
模块树可能会让您想起计算机上文件系统的目录树;这是一个非常恰当的比较!就像文件系统中的目录一样,您可以使用模块来组织代码。就像目录中的文件一样,我们需要一种方法来查找模块。
Paths for Referring to an Item in the Module Tree
引用模块树中项目的路径
To show Rust where to find an item in a module tree, we use a path in the same
way we use a path when navigating a filesystem. To call a function, we need to
know its path.
为了向 Rust 展示在模块树中的何处查找项目,我们使用路径,就像导航文件系统时使用路径一样。要调用一个函数,我们需要知道它的路径。
A path can take two forms:
路径可以采用两种形式:
- An absolute path is the full path starting from a crate root; for code
from an external crate, the absolute path begins with the crate name, and for
code from the current crate, it starts with the literal
crate
.
绝对路径是从 crate 根开始的完整路径;对于来自外部 crate 的代码,绝对路径以 crate 名称开头,对于来自当前 crate 的代码,绝对路径以文字crate
开头。 - A relative path starts from the current module and uses
self
,super
, or an identifier in the current module.
相对路径从当前模块开始,并使用self
、super
或当前模块中的标识符。
Both absolute and relative paths are followed by one or more identifiers
separated by double colons (::
).
绝对路径和相对路径都后跟一个或多个以双冒号 ( ::
) 分隔的标识符。
Returning to Listing 7-1, say we want to call the add_to_waitlist
function.
This is the same as asking: what’s the path of the add_to_waitlist
function?
Listing 7-3 contains Listing 7-1 with some of the modules and functions
removed.
返回清单 7-1,假设我们要调用add_to_waitlist
函数。这相当于问: add_to_waitlist
函数的路径是什么?清单 7-3 包含清单 7-1,其中删除了一些模块和函数。
We’ll show two ways to call the add_to_waitlist
function from a new function,
eat_at_restaurant
, defined in the crate root. These paths are correct, but
there’s another problem remaining that will prevent this example from compiling
as is. We’ll explain why in a bit.
我们将展示从 crate 根中定义的新函数eat_at_restaurant
调用add_to_waitlist
函数的两种方法。这些路径是正确的,但是还存在另一个问题,该问题将阻止该示例按原样编译。我们稍后会解释原因。
The eat_at_restaurant
function is part of our library crate’s public API, so
we mark it with the pub
keyword. In the “Exposing Paths with the pub
Keyword” section, we’ll go into more detail about pub
.eat_at_restaurant
函数是我们库 crate 的公共 API 的一部分,因此我们用pub
关键字标记它。在“使用pub
关键字公开路径”忽略部分中,我们将详细介绍pub
。
Filename: src/lib.rs 文件名:src/lib.rs
mod front_of_house {
mod hosting {
fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
The first time we call the add_to_waitlist
function in eat_at_restaurant
,
we use an absolute path. The add_to_waitlist
function is defined in the same
crate as eat_at_restaurant
, which means we can use the crate
keyword to
start an absolute path. We then include each of the successive modules until we
make our way to add_to_waitlist
. You can imagine a filesystem with the same
structure: we’d specify the path /front_of_house/hosting/add_to_waitlist
to
run the add_to_waitlist
program; using the crate
name to start from the
crate root is like using /
to start from the filesystem root in your shell.
第一次在eat_at_restaurant
中调用add_to_waitlist
函数时,我们使用绝对路径。 add_to_waitlist
函数与eat_at_restaurant
定义在同一个 crate 中,这意味着我们可以使用crate
关键字来启动绝对路径。然后,我们包含每个连续的模块,直到到达add_to_waitlist
为止。你可以想象一个具有相同结构的文件系统:我们指定路径/front_of_house/hosting/add_to_waitlist
来运行add_to_waitlist
程序;使用crate
名称从 crate 根目录启动就像在 shell 中使用/
从文件系统根目录启动一样。
The second time we call add_to_waitlist
in eat_at_restaurant
, we use a
relative path. The path starts with front_of_house
, the name of the module
defined at the same level of the module tree as eat_at_restaurant
. Here the
filesystem equivalent would be using the path
front_of_house/hosting/add_to_waitlist
. Starting with a module name means
that the path is relative.
第二次我们在eat_at_restaurant
中调用add_to_waitlist
时,我们使用相对路径。该路径以front_of_house
开头,它是与eat_at_restaurant
在模块树的同一级别定义的模块名称。这里的文件系统等效项将使用路径front_of_house/hosting/add_to_waitlist
。以模块名称开头意味着路径是相对的。
Choosing whether to use a relative or absolute path is a decision you’ll make
based on your project, and it depends on whether you’re more likely to move
item definition code separately from or together with the code that uses the
item. For example, if we moved the front_of_house
module and the
eat_at_restaurant
function into a module named customer_experience
, we’d
need to update the absolute path to add_to_waitlist
, but the relative path
would still be valid. However, if we moved the eat_at_restaurant
function
separately into a module named dining
, the absolute path to the
add_to_waitlist
call would stay the same, but the relative path would need to
be updated. Our preference in general is to specify absolute paths because it’s
more likely we’ll want to move code definitions and item calls independently of
each other.
选择是使用相对路径还是绝对路径是您根据项目做出的决定,并且取决于您是否更有可能将项目定义代码与使用该项目的代码分开移动或一起移动。例如,如果我们将front_of_house
模块和eat_at_restaurant
函数移动到名为customer_experience
的模块中,我们需要将绝对路径更新为add_to_waitlist
,但相对路径仍然有效。但是,如果我们将eat_at_restaurant
函数单独移动到名为dining
的模块中,则add_to_waitlist
调用的绝对路径将保持不变,但相对路径需要更新。我们通常倾向于指定绝对路径,因为我们更有可能希望彼此独立地移动代码定义和项目调用。
Let’s try to compile Listing 7-3 and find out why it won’t compile yet! The
errors we get are shown in Listing 7-4.
让我们尝试编译清单 7-3,看看为什么它还不能编译!我们得到的错误如清单 7-4 所示。
$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0603]: module `hosting` is private
--> 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
--> src/lib.rs:2:5
|
2 | mod hosting {
| ^^^^^^^^^^^
error[E0603]: module `hosting` is private
--> 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
--> 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
The error messages say that module hosting
is private. In other words, we
have the correct paths for the hosting
module and the add_to_waitlist
function, but Rust won’t let us use them because it doesn’t have access to the
private sections. In Rust, all items (functions, methods, structs, enums,
modules, and constants) are private to parent modules by default. If you want
to make an item like a function or struct private, you put it in a module.
错误消息表明模块hosting
是私有的。换句话说,我们拥有hosting
模块和add_to_waitlist
函数的正确路径,但 Rust 不允许我们使用它们,因为它无权访问私有部分。在 Rust 中,默认情况下,所有项目(函数、方法、结构、枚举、模块和常量)都是父模块私有的。如果您想将函数或结构等项目设为私有,则可以将其放入模块中。
Items in a parent module can’t use the private items inside child modules, but
items in child modules can use the items in their ancestor modules. This is
because child modules wrap and hide their implementation details, but the child
modules can see the context in which they’re defined. To continue with our
metaphor, think of the privacy rules as being like the back office of a
restaurant: what goes on in there is private to restaurant customers, but
office managers can see and do everything in the restaurant they operate.
父模块中的项目不能使用子模块中的私有项目,但子模块中的项目可以使用其祖先模块中的项目。这是因为子模块包装并隐藏其实现细节,但子模块可以看到定义它们的上下文。继续我们的比喻,将隐私规则想象成餐厅的后台:那里发生的事情对餐厅顾客来说是私人的,但办公室经理可以看到并执行他们经营的餐厅中的一切。
Rust chose to have the module system function this way so that hiding inner
implementation details is the default. That way, you know which parts of the
inner code you can change without breaking outer code. However, Rust does give
you the option to expose inner parts of child modules’ code to outer ancestor
modules by using the pub
keyword to make an item public.
Rust 选择以这种方式拥有模块系统功能,因此隐藏内部实现细节是默认的。这样,您就知道可以更改内部代码的哪些部分而不破坏外部代码。然而,Rust 确实为您提供了通过使用pub
关键字公开项目来将子模块代码的内部部分公开给外部祖先模块的选项。
Exposing Paths with the pub
Keyword
使用pub
关键字公开路径
Let’s return to the error in Listing 7-4 that told us the hosting
module is
private. We want the eat_at_restaurant
function in the parent module to have
access to the add_to_waitlist
function in the child module, so we mark the
hosting
module with the pub
keyword, as shown in Listing 7-5.
让我们回到清单 7-4 中的错误,它告诉我们hosting
模块是私有的。我们希望父模块中的eat_at_restaurant
函数能够访问子模块中的add_to_waitlist
函数,因此我们使用pub
关键字标记hosting
模块,如清单 7-5 所示。
Filename: src/lib.rs 文件名:src/lib.rs
mod front_of_house {
pub mod hosting {
fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
Unfortunately, the code in Listing 7-5 still results in compiler errors, as
shown in Listing 7-6.
不幸的是,清单 7-5 中的代码仍然会导致编译器错误,如清单 7-6 所示。
$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0603]: function `add_to_waitlist` is private
--> 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
--> src/lib.rs:3:9
|
3 | fn add_to_waitlist() {}
| ^^^^^^^^^^^^^^^^^^^^
error[E0603]: function `add_to_waitlist` is private
--> src/lib.rs:12:30
|
12 | front_of_house::hosting::add_to_waitlist();
| ^^^^^^^^^^^^^^^ private function
|
note: the function `add_to_waitlist` is defined here
--> 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
What happened? Adding the pub
keyword in front of mod hosting
makes the
module public. With this change, if we can access front_of_house
, we can
access hosting
. But the contents of hosting
are still private; making the
module public doesn’t make its contents public. The pub
keyword on a module
only lets code in its ancestor modules refer to it, not access its inner code.
Because modules are containers, there’s not much we can do by only making the
module public; we need to go further and choose to make one or more of the
items within the module public as well.
发生了什么?在mod hosting
前面添加pub
关键字将使模块公开。通过此更改,如果我们可以访问front_of_house
,我们就可以访问hosting
。但hosting
的内容仍然是私密的;公开模块并不会公开其内容。模块上的pub
关键字仅允许其祖先模块中的代码引用它,而不能访问其内部代码。因为模块是容器,所以仅仅将模块公开我们能做的事情不多;我们需要更进一步,选择将模块中的一项或多项设为公开。
The errors in Listing 7-6 say that the add_to_waitlist
function is private.
The privacy rules apply to structs, enums, functions, and methods as well as
modules.
清单 7-6 中的错误表明add_to_waitlist
函数是私有的。隐私规则适用于结构、枚举、函数、方法以及模块。
Let’s also make the add_to_waitlist
function public by adding the pub
keyword before its definition, as in Listing 7-7.
我们还可以通过在定义之前添加pub
关键字来将add_to_waitlist
函数公开,如清单 7-7 所示。
Filename: src/lib.rs 文件名:src/lib.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
Now the code will compile! To see why adding the pub
keyword lets us use
these paths in eat_at_restaurant
with respect to the privacy rules, let’s look
at the absolute and the relative paths.
现在代码可以编译了!为了了解为什么添加pub
关键字可以让我们在eat_at_restaurant
中使用这些路径以满足隐私规则,让我们看看绝对路径和相对路径。
In the absolute path, we start with crate
, the root of our crate’s module
tree. The front_of_house
module is defined in the crate root. While
front_of_house
isn’t public, because the eat_at_restaurant
function is
defined in the same module as front_of_house
(that is, eat_at_restaurant
and front_of_house
are siblings), we can refer to front_of_house
from
eat_at_restaurant
. Next is the hosting
module marked with pub
. We can
access the parent module of hosting
, so we can access hosting
. Finally, the
add_to_waitlist
function is marked with pub
and we can access its parent
module, so this function call works!
在绝对路径中,我们从crate
开始,它是 crate 模块树的根。 front_of_house
模块在 crate 根中定义。虽然front_of_house
不是公开的,但由于eat_at_restaurant
函数与front_of_house
定义在同一模块中(即eat_at_restaurant
和front_of_house
是兄弟姐妹),因此我们可以从eat_at_restaurant
引用front_of_house
。接下来是标有pub
hosting
模块。我们可以访问hosting
的父模块,这样就可以访问hosting
。最后, add_to_waitlist
函数被标记为pub
,我们可以访问它的父模块,所以这个函数调用有效!
In the relative path, the logic is the same as the absolute path except for the
first step: rather than starting from the crate root, the path starts from
front_of_house
. The front_of_house
module is defined within the same module
as eat_at_restaurant
, so the relative path starting from the module in which
eat_at_restaurant
is defined works. Then, because hosting
and
add_to_waitlist
are marked with pub
, the rest of the path works, and this
function call is valid!
在相对路径中,除了第一步之外,逻辑与绝对路径相同:路径不是从 crate 根开始,而是从front_of_house
开始。 front_of_house
模块与eat_at_restaurant
定义在同一模块中,因此从定义eat_at_restaurant
的模块开始的相对路径有效。然后,因为hosting
和add_to_waitlist
被标记为pub
,所以路径的其余部分有效,并且这个函数调用是有效的!
If you plan on sharing your library crate so other projects can use your code,
your public API is your contract with users of your crate that determines how
they can interact with your code. There are many considerations around managing
changes to your public API to make it easier for people to depend on your
crate. These considerations are out of the scope of this book; if you’re
interested in this topic, see The Rust API Guidelines.
如果您计划共享您的库箱,以便其他项目可以使用您的代码,那么您的公共 API 就是您与箱用户之间的合同,决定了他们如何与您的代码进行交互。为了让人们更容易依赖你的 crate,管理公共 API 的更改需要考虑很多因素。这些考虑因素超出了本书的范围。如果您对此主题感兴趣,请参阅Rust API 指南。
Best Practices for Packages with a Binary and a Library
具有二进制文件和库的包的最佳实践
We mentioned that a package can contain both a src/main.rs binary crate
root as well as a src/lib.rs library crate root, and both crates will have
the package name by default. Typically, packages with this pattern of
containing both a library and a binary crate will have just enough code in the
binary crate to start an executable that calls code within the library crate.
This lets other projects benefit from most of the functionality that the
package provides because the library crate’s code can be shared.
我们提到一个包可以包含src/main.rs二进制 crate 根以及src/lib.rs库 crate 根,并且默认情况下这两个 crate 都将具有包名称。通常,具有包含库和二进制 crate 的这种模式的包在二进制 crate 中将具有足够的代码来启动调用库 crate 中的代码的可执行文件。这使得其他项目可以从该包提供的大部分功能中受益,因为库包的代码可以共享。
The module tree should be defined in src/lib.rs. Then, any public items can
be used in the binary crate by starting paths with the name of the package.
The binary crate becomes a user of the library crate just like a completely
external crate would use the library crate: it can only use the public API.
This helps you design a good API; not only are you the author, you’re also a
client!
模块树应该在src/lib.rs中定义。然后,通过以包的名称开始路径,可以在二进制包中使用任何公共项目。二进制 crate 成为库 crate 的用户,就像完全外部的 crate 使用库 crate 一样:它只能使用公共 API。这可以帮助你设计一个好的API;您不仅是作者,也是客户!
In Chapter 12, we’ll demonstrate this organizational
practice with a command-line program that will contain both a binary crate
and a library crate.
在第 12 章中,我们将使用包含二进制 crate 和库 crate 的命令行程序来演示这种组织实践。
Starting Relative Paths with super
以super
开始相对路径
We can construct relative paths that begin in the parent module, rather than
the current module or the crate root, by using super
at the start of the
path. This is like starting a filesystem path with the ..
syntax. Using
super
allows us to reference an item that we know is in the parent module,
which can make rearranging the module tree easier when the module is closely
related to the parent but the parent might be moved elsewhere in the module
tree someday.
我们可以通过在路径开头使用super
来构造从父模块开始的相对路径,而不是从当前模块或 crate 根开始。这就像使用..
语法启动文件系统路径。使用super
允许我们引用父模块中已知的项,当模块与父模块密切相关但父模块有一天可能会移动到模块树中的其他位置时,这可以使重新排列模块树变得更容易。
Consider the code in Listing 7-8 that models the situation in which a chef
fixes an incorrect order and personally brings it out to the customer. The
function fix_incorrect_order
defined in the back_of_house
module calls the
function deliver_order
defined in the parent module by specifying the path to
deliver_order
, starting with super
.
考虑清单 7-8 中的代码,该代码模拟了厨师修复错误订单并亲自将其呈现给顾客的情况。 back_of_house
模块中定义的函数fix_incorrect_order
通过指定以super
开头的deliver_order
路径来调用父模块中定义的函数deliver_order
。
Filename: src/lib.rs 文件名:src/lib.rs
fn deliver_order() {}
mod back_of_house {
fn fix_incorrect_order() {
cook_order();
super::deliver_order();
}
fn cook_order() {}
}
The fix_incorrect_order
function is in the back_of_house
module, so we can
use super
to go to the parent module of back_of_house
, which in this case
is crate
, the root. From there, we look for deliver_order
and find it.
Success! We think the back_of_house
module and the deliver_order
function
are likely to stay in the same relationship to each other and get moved
together should we decide to reorganize the crate’s module tree. Therefore, we
used super
so we’ll have fewer places to update code in the future if this
code gets moved to a different module.fix_incorrect_order
函数位于back_of_house
模块中,因此我们可以使用super
转到back_of_house
的父模块,在本例中是crate
,即根模块。从那里,我们寻找deliver_order
并找到它。成功!我们认为,如果我们决定重新组织板条箱的模块树, back_of_house
模块和deliver_order
函数可能会保持相同的相互关系,并一起移动。因此,我们使用了super
,这样如果代码被移动到不同的模块,我们将来更新代码的地方就会更少。
Making Structs and Enums Public
公开结构体和枚举
We can also use pub
to designate structs and enums as public, but there are a
few extra details to the usage of pub
with structs and enums. If we use pub
before a struct definition, we make the struct public, but the struct’s fields
will still be private. We can make each field public or not on a case-by-case
basis. In Listing 7-9, we’ve defined a public back_of_house::Breakfast
struct
with a public toast
field but a private seasonal_fruit
field. This models
the case in a restaurant where the customer can pick the type of bread that
comes with a meal, but the chef decides which fruit accompanies the meal based
on what’s in season and in stock. The available fruit changes quickly, so
customers can’t choose the fruit or even see which fruit they’ll get.
我们还可以使用pub
将结构和枚举指定为公共,但是将pub
与结构和枚举一起使用还有一些额外的细节。如果我们在结构体定义之前使用pub
,我们会将结构体设为公共,但结构体的字段仍将是私有的。我们可以根据具体情况公开或不公开每个字段。在清单 7-9 中,我们定义了一个公共back_of_house::Breakfast
结构,其中包含一个公共toast
字段和一个私有seasonal_fruit
字段。这个模型模拟了一家餐厅的情况,顾客可以选择餐食中搭配的面包类型,但厨师会根据时令和库存来决定搭配餐食的水果。可用的水果变化很快,因此顾客无法选择水果,甚至无法看到他们会得到哪种水果。
Filename: src/lib.rs 文件名:src/lib.rs
mod back_of_house {
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
pub fn summer(toast: &str) -> Breakfast {
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peaches"),
}
}
}
}
pub fn eat_at_restaurant() {
// Order a breakfast in the summer with Rye toast
let mut meal = back_of_house::Breakfast::summer("Rye");
// Change our mind about what bread we'd like
meal.toast = String::from("Wheat");
println!("I'd like {} toast please", meal.toast);
// The next line won't compile if we uncomment it; we're not allowed
// to see or modify the seasonal fruit that comes with the meal
// meal.seasonal_fruit = String::from("blueberries");
}
Because the toast
field in the back_of_house::Breakfast
struct is public,
in eat_at_restaurant
we can write and read to the toast
field using dot
notation. Notice that we can’t use the seasonal_fruit
field in
eat_at_restaurant
, because seasonal_fruit
is private. Try uncommenting the
line modifying the seasonal_fruit
field value to see what error you get!
因为back_of_house::Breakfast
结构中的toast
字段是公共的,所以在eat_at_restaurant
中我们可以使用点表示法写入和读取toast
字段。请注意,我们不能在eat_at_restaurant
中使用seasonal_fruit
字段,因为seasonal_fruit
是私有的。尝试取消注释修改seasonal_fruit
字段值的行,看看会得到什么错误!
Also, note that because back_of_house::Breakfast
has a private field, the
struct needs to provide a public associated function that constructs an
instance of Breakfast
(we’ve named it summer
here). If Breakfast
didn’t
have such a function, we couldn’t create an instance of Breakfast
in
eat_at_restaurant
because we couldn’t set the value of the private
seasonal_fruit
field in eat_at_restaurant
.
另请注意,因为back_of_house::Breakfast
有一个私有字段,所以该结构需要提供一个公共关联函数来构造一个Breakfast
实例(我们在这里将其命名为summer
)。如果Breakfast
没有这样的函数,我们就无法在eat_at_restaurant
中创建Breakfast
的实例,因为我们无法在eat_at_restaurant
中设置私有seasonal_fruit
字段的值。
In contrast, if we make an enum public, all of its variants are then public. We
only need the pub
before the enum
keyword, as shown in Listing 7-10.
相反,如果我们公开一个枚举,那么它的所有变体都是公开的。我们只需要在enum
关键字之前加上pub
,如清单 7-10 所示。
Filename: src/lib.rs 文件名:src/lib.rs
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;
}
Because we made the Appetizer
enum public, we can use the Soup
and Salad
variants in eat_at_restaurant
.
因为我们公开了Appetizer
枚举,所以我们可以在eat_at_restaurant
中使用Soup
和Salad
变体。
Enums aren’t very useful unless their variants are public; it would be annoying
to have to annotate all enum variants with pub
in every case, so the default
for enum variants is to be public. Structs are often useful without their
fields being public, so struct fields follow the general rule of everything
being private by default unless annotated with pub
.
枚举不是很有用,除非它们的变体是公共的。在每种情况下都必须用pub
注释所有枚举变体会很烦人,因此枚举变体的默认设置是公共的。结构体在其字段不公开的情况下通常很有用,因此结构体字段遵循默认情况下所有内容都是私有的一般规则,除非用pub
注释。
There’s one more situation involving pub
that we haven’t covered, and that is
our last module system feature: the use
keyword. We’ll cover use
by itself
first, and then we’ll show how to combine pub
and use
.
还有一种涉及pub
情况我们没有涉及,那就是我们的最后一个模块系统功能: use
关键字。我们将首先介绍use
本身,然后我们将展示如何组合pub
和use
。
Bringing Paths into Scope with the use
Keyword
use
关键字将路径纳入范围
Having to write out the paths to call functions can feel inconvenient and
repetitive. In Listing 7-7, whether we chose the absolute or relative path to
the add_to_waitlist
function, every time we wanted to call add_to_waitlist
we had to specify front_of_house
and hosting
too. Fortunately, there’s a
way to simplify this process: we can create a shortcut to a path with the use
keyword once, and then use the shorter name everywhere else in the scope.
必须写出调用函数的路径可能会感觉不方便且重复。在清单7-7中,无论我们选择add_to_waitlist
函数的绝对路径还是相对路径,每次我们想要调用add_to_waitlist
时,我们都必须指定front_of_house
和hosting
。幸运的是,有一种方法可以简化此过程:我们可以使用use
关键字创建一次路径的快捷方式,然后在范围内的其他任何地方使用较短的名称。
In Listing 7-11, we bring the crate::front_of_house::hosting
module into the
scope of the eat_at_restaurant
function so we only have to specify
hosting::add_to_waitlist
to call the add_to_waitlist
function in
eat_at_restaurant
.
在清单 7-11 中,我们将crate::front_of_house::hosting
模块带入eat_at_restaurant
函数的作用域中,因此我们只需指定hosting::add_to_waitlist
即可调用eat_at_restaurant
中的add_to_waitlist
函数。
Filename: src/lib.rs 文件名:src/lib.rs
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();
}
Adding use
and a path in a scope is similar to creating a symbolic link in
the filesystem. By adding use crate::front_of_house::hosting
in the crate
root, hosting
is now a valid name in that scope, just as though the hosting
module had been defined in the crate root. Paths brought into scope with use
also check privacy, like any other paths.
在作用域中添加use
和路径类似于在文件系统中创建符号链接。通过在 crate 根中添加use crate::front_of_house::hosting
, hosting
现在是该范围内的有效名称,就像hosting
模块已在 crate 根中定义一样。与任何其他路径一样,随着use
而进入范围的路径也会检查隐私。
Note that use
only creates the shortcut for the particular scope in which the
use
occurs. Listing 7-12 moves the eat_at_restaurant
function into a new
child module named customer
, which is then a different scope than the use
statement, so the function body won’t compile.
请注意, use
仅为发生use
特定范围创建快捷方式。清单 7-12 将eat_at_restaurant
函数移动到一个名为customer
新子模块中,该子模块与use
语句的作用域不同,因此函数体将无法编译。
Filename: src/lib.rs 文件名:src/lib.rs
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();
}
}
The compiler error shows that the shortcut no longer applies within the
customer
module:
编译器错误表明该快捷方式不再适用于customer
模块:
$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0433]: failed to resolve: use of undeclared crate or module `hosting`
--> 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`
--> 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
Notice there’s also a warning that the use
is no longer used in its scope! To
fix this problem, move the use
within the customer
module too, or reference
the shortcut in the parent module with super::hosting
within the child
customer
module.
请注意,还有一个警告,表明该use
不再在其范围内使用!要解决此问题,请将use
移到customer
模块中,或者在子customer
模块中使用super::hosting
父模块中的快捷方式。
Creating Idiomatic use
Paths
创建惯用的use
路径
In Listing 7-11, you might have wondered why we specified use crate::front_of_house::hosting
and then called hosting::add_to_waitlist
in
eat_at_restaurant
, rather than specifying the use
path all the way out to
the add_to_waitlist
function to achieve the same result, as in Listing 7-13.
在清单 7-11 中,您可能想知道为什么我们指定了use crate::front_of_house::hosting
,然后在eat_at_restaurant
中调用hosting::add_to_waitlist
,而不是一直指定use
路径到add_to_waitlist
函数来实现相同的结果,如清单 7-13 所示。
Filename: src/lib.rs 文件名:src/lib.rs
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();
}
Although both Listing 7-11 and Listing 7-13 accomplish the same task, Listing
7-11 is the idiomatic way to bring a function into scope with use
. Bringing
the function’s parent module into scope with use
means we have to specify the
parent module when calling the function. Specifying the parent module when
calling the function makes it clear that the function isn’t locally defined
while still minimizing repetition of the full path. The code in Listing 7-13 is
unclear as to where add_to_waitlist
is defined.
尽管清单 7-11 和清单 7-13 完成了相同的任务,但清单 7-11 是use
将函数引入作用域的惯用方法。 use
将函数的父模块纳入作用域意味着我们在调用函数时必须指定父模块。在调用函数时指定父模块可以清楚地表明该函数不是本地定义的,同时仍然最大限度地减少完整路径的重复。清单 7-13 中的代码不清楚add_to_waitlist
是在哪里定义的。
On the other hand, when bringing in structs, enums, and other items with use
,
it’s idiomatic to specify the full path. Listing 7-14 shows the idiomatic way
to bring the standard library’s HashMap
struct into the scope of a binary
crate.
另一方面,当use
引入结构体、枚举和其他项时,指定完整路径是惯用的做法。清单 7-14 显示了将标准库的HashMap
结构引入二进制 crate 范围的惯用方法。
Filename: src/main.rs 文件名:src/main.rs
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert(1, 2);
}
There’s no strong reason behind this idiom: it’s just the convention that has
emerged, and folks have gotten used to reading and writing Rust code this way.
这个习惯用法背后没有什么强有力的理由:这只是已经出现的约定,人们已经习惯了以这种方式阅读和编写 Rust 代码。
The exception to this idiom is if we’re bringing two items with the same name
into scope with use
statements, because Rust doesn’t allow that. Listing 7-15
shows how to bring two Result
types into scope that have the same name but
different parent modules, and how to refer to them.
这种习惯用法的例外是,如果我们使用use
语句将两个同名的项带入作用域,因为 Rust 不允许这样做。清单 7-15 显示了如何将两个具有相同名称但不同父模块的Result
类型引入作用域,以及如何引用它们。
Filename: src/lib.rs 文件名:src/lib.rs
As you can see, using the parent modules distinguishes the two Result
types.
If instead we specified use std::fmt::Result
and use std::io::Result
, we’d
have two Result
types in the same scope, and Rust wouldn’t know which one we
meant when we used Result
.
如您所见,使用父模块区分了两种Result
类型。相反,如果我们指定use std::fmt::Result
和use std::io::Result
,我们就会在同一范围内有两种Result
类型,并且 Rust 不会知道当我们使用Result
时我们指的是哪一种。
Providing New Names with the as
Keyword
使用as
关键字提供新名称
There’s another solution to the problem of bringing two types of the same name
into the same scope with use
: after the path, we can specify as
and a new
local name, or alias, for the type. Listing 7-16 shows another way to write
the code in Listing 7-15 by renaming one of the two Result
types using as
.
对于use
将两种同名类型引入同一作用域的问题,还有另一种解决方案:在路径之后,我们可以为该类型指定as
和一个新的本地名称或别名。清单 7-16 显示了编写清单 7-15 中的代码的另一种方法,即使用as
重命名两个Result
类型之一。
Filename: src/lib.rs 文件名:src/lib.rs
In the second use
statement, we chose the new name IoResult
for the
std::io::Result
type, which won’t conflict with the Result
from std::fmt
that we’ve also brought into scope. Listing 7-15 and Listing 7-16 are
considered idiomatic, so the choice is up to you!
在第二个use
语句中,我们为std::io::Result
类型选择了新名称IoResult
,这不会与我们也纳入范围的std::fmt
的Result
冲突。清单 7-15 和清单 7-16 被认为是惯用的,因此选择取决于您!
Re-exporting Names with pub use
pub use
重新导出名称
When we bring a name into scope with the use
keyword, the name available in
the new scope is private. To enable the code that calls our code to refer to
that name as if it had been defined in that code’s scope, we can combine pub
and use
. This technique is called re-exporting because we’re bringing an
item into scope but also making that item available for others to bring into
their scope.
当我们use
关键字将名称引入作用域时,新作用域中可用的名称是私有的。为了使调用我们代码的代码能够引用该名称,就好像它已在该代码的范围内定义一样,我们可以组合pub
和use
。这种技术称为重新导出,因为我们将某个项目纳入范围,同时也使该项目可供其他人纳入其范围。
Listing 7-17 shows the code in Listing 7-11 with use
in the root module
changed to pub use
.
清单 7-17 显示了清单 7-11 中的代码,其中 root 模块中的use
更改为pub use
。
Filename: src/lib.rs 文件名:src/lib.rs
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();
}
Before this change, external code would have to call the add_to_waitlist
function by using the path
restaurant::front_of_house::hosting::add_to_waitlist()
, which also would have
required the front_of_house
module to be marked as pub
. Now that this pub use
has re-exported the hosting
module from the root module, external code
can use the path restaurant::hosting::add_to_waitlist()
instead.
在此更改之前,外部代码必须使用路径restaurant::front_of_house::hosting::add_to_waitlist()
add_to_waitlist
函数,这也需要将front_of_house
模块标记为pub
。现在,这个pub use
已经从根模块重新导出了hosting
模块,外部代码可以使用路径restaurant::hosting::add_to_waitlist()
代替。
Re-exporting is useful when the internal structure of your code is different
from how programmers calling your code would think about the domain. For
example, in this restaurant metaphor, the people running the restaurant think
about “front of house” and “back of house.” But customers visiting a restaurant
probably won’t think about the parts of the restaurant in those terms. With
pub use
, we can write our code with one structure but expose a different
structure. Doing so makes our library well organized for programmers working on
the library and programmers calling the library. We’ll look at another example
of pub use
and how it affects your crate’s documentation in the “Exporting a
Convenient Public API with pub use
” section of
Chapter 14.
当代码的内部结构与调用代码的程序员对域的看法不同时,重新导出非常有用。例如,在这个餐厅比喻中,经营餐厅的人会想到“前台”和“后台”。但光顾餐厅的顾客可能不会从这些方面考虑餐厅的各个部分。通过pub use
,我们可以使用一种结构编写代码,但公开一种不同的结构。这样做可以使我们的库为使用该库的程序员和调用该库的程序员提供良好的组织。我们将在第 14 章的“使用pub use
导出方便的公共 API”忽略部分中查看pub use
的另一个示例以及它如何影响您的 crate 文档。
Using External Packages 使用外部包
In Chapter 2, we programmed a guessing game project that used an external
package called rand
to get random numbers. To use rand
in our project, we
added this line to Cargo.toml:
在第 2 章中,我们编写了一个猜谜游戏项目,该项目使用名为rand
外部包来获取随机数。为了在我们的项目中使用rand
,我们将此行添加到Cargo.toml中:
Filename: Cargo.toml 文件名:Cargo.toml
rand = "0.8.5"
Adding rand
as a dependency in Cargo.toml tells Cargo to download the
rand
package and any dependencies from crates.io and
make rand
available to our project.
在Cargo.toml中添加rand
作为依赖项,告诉 Cargo 从crates.io下载rand
包和任何依赖项,并使rand
可用于我们的项目。
Then, to bring rand
definitions into the scope of our package, we added a
use
line starting with the name of the crate, rand
, and listed the items
we wanted to bring into scope. Recall that in the “Generating a Random
Number” section in Chapter 2, we brought the Rng
trait
into scope and called the rand::thread_rng
function:
然后,为了将rand
定义引入到我们的包的范围内,我们添加了一个以 crate 名称rand
开头的use
行,并列出了我们想要纳入范围的项目。回想一下,在第 2 章的“生成随机数”忽略部分中,我们将Rng
特征引入作用域并调用rand::thread_rng
函数:
Members of the Rust community have made many packages available at
crates.io, and pulling any of them into your package
involves these same steps: listing them in your package’s Cargo.toml file and
using use
to bring items from their crates into scope.
Rust 社区的成员在crates.io上提供了许多包,将它们中的任何一个拉入您的包中都涉及以下相同的步骤:将它们列在包的Cargo.toml文件中,并使用use
将项目从其 crate 引入范围。
Note that the standard std
library is also a crate that’s external to our
package. Because the standard library is shipped with the Rust language, we
don’t need to change Cargo.toml to include std
. But we do need to refer to
it with use
to bring items from there into our package’s scope. For example,
with HashMap
we would use this line:
请注意,标准std
库也是我们包外部的一个板条箱。因为标准库是随 Rust 语言一起提供的,所以我们不需要更改Cargo.toml来包含std
。但我们确实需要引用它并use
它来将项目从那里带入我们的包的范围。例如,对于HashMap
,我们将使用这一行:
This is an absolute path starting with std
, the name of the standard library
crate.
这是一个以std
开头的绝对路径,即标准库包的名称。
Using Nested Paths to Clean Up Large use
Lists
使用嵌套路径清理大型use
列表
If we’re using multiple items defined in the same crate or same module, listing
each item on its own line can take up a lot of vertical space in our files. For
example, these two use
statements we had in the guessing game in Listing 2-4
bring items from std
into scope:
如果我们使用在同一板条箱或同一模块中定义的多个项目,则将每个项目单独列出可能会占用文件中的大量垂直空间。例如,清单 2-4 中的猜谜游戏中的这两个use
语句将std
中的项带入作用域:
Filename: src/main.rs 文件名:src/main.rs
Instead, we can use nested paths to bring the same items into scope in one
line. We do this by specifying the common part of the path, followed by two
colons, and then curly brackets around a list of the parts of the paths that
differ, as shown in Listing 7-18.
相反,我们可以使用嵌套路径将相同的项目放入一行中的范围内。为此,我们指定路径的公共部分,后跟两个冒号,然后用大括号括住路径不同部分的列表,如清单 7-18 所示。
Filename: src/main.rs 文件名:src/main.rs
In bigger programs, bringing many items into scope from the same crate or
module using nested paths can reduce the number of separate use
statements
needed by a lot!
在较大的程序中,使用嵌套路径将同一包或模块中的许多项纳入范围可以大大减少所需的单独use
语句的数量!
We can use a nested path at any level in a path, which is useful when combining
two use
statements that share a subpath. For example, Listing 7-19 shows two
use
statements: one that brings std::io
into scope and one that brings
std::io::Write
into scope.
我们可以在路径中的任何级别使用嵌套路径,这在组合共享子路径的两个use
语句时非常有用。例如,清单 7-19 显示了两种use
语句:一种将std::io
引入作用域,另一种将std::io::Write
引入作用域。
Filename: src/lib.rs 文件名:src/lib.rs
use std::io;
use std::io::Write;
The common part of these two paths is std::io
, and that’s the complete first
path. To merge these two paths into one use
statement, we can use self
in
the nested path, as shown in Listing 7-20.
这两条路径的共同部分是std::io
,这是完整的第一条路径。要将这两个路径合并到一个use
语句中,我们可以在嵌套路径中使用self
,如清单 7-20 所示。
Filename: src/lib.rs 文件名:src/lib.rs
use std::io::{self, Write};
This line brings std::io
and std::io::Write
into scope.
此行将std::io
和std::io::Write
引入作用域。
The Glob Operator 全局运算符
If we want to bring all public items defined in a path into scope, we can
specify that path followed by the *
glob operator:
如果我们想要将路径中定义的所有公共项纳入作用域,我们可以指定该路径,后跟*
glob 运算符:
This use
statement brings all public items defined in std::collections
into
the current scope. Be careful when using the glob operator! Glob can make it
harder to tell what names are in scope and where a name used in your program
was defined.
此use
语句将std::collections
中定义的所有公共项带入当前范围。使用 glob 运算符时要小心! Glob 会使判断哪些名称在范围内以及程序中使用的名称的定义位置变得更加困难。
The glob operator is often used when testing to bring everything under test
into the tests
module; we’ll talk about that in the “How to Write
Tests” section in Chapter 11. The glob operator
is also sometimes used as part of the prelude pattern: see the standard
library documentation
for more information on that pattern.
测试时经常使用 glob 运算符,将所有被测试的内容放入tests
模块中;我们将在第 11 章的“如何编写测试”中讨论这一点。glob 运算符有时也用作前奏模式的一部分:有关该模式的更多信息,请参阅标准库文档ignore。
Separating Modules into Different Files
将模块分成不同的文件
So far, all the examples in this chapter defined multiple modules in one file.
When modules get large, you might want to move their definitions to a separate
file to make the code easier to navigate.
到目前为止,本章中的所有示例都在一个文件中定义了多个模块。当模块变大时,您可能希望将其定义移动到单独的文件中,以使代码更易于导航。
For example, let’s start from the code in Listing 7-17 that had multiple
restaurant modules. We’ll extract modules into files instead of having all the
modules defined in the crate root file. In this case, the crate root file is
src/lib.rs, but this procedure also works with binary crates whose crate root
file is src/main.rs.
例如,让我们从清单 7-17 中具有多个餐厅模块的代码开始。我们将把模块提取到文件中,而不是在 crate 根文件中定义所有模块。在本例中,板条箱根文件为src/lib.rs ,但此过程也适用于板条箱根文件为src/main.rs的二进制板条箱。
First we’ll extract the front_of_house
module to its own file. Remove the
code inside the curly brackets for the front_of_house
module, leaving only
the mod front_of_house;
declaration, so that src/lib.rs contains the code
shown in Listing 7-21. Note that this won’t compile until we create the
src/front_of_house.rs file in Listing 7-22.
首先,我们将front_of_house
模块提取到它自己的文件中。删除front_of_house
模块大括号内的代码,只留下mod front_of_house;
声明,以便src/lib.rs包含清单 7-21 所示的代码。请注意,直到我们创建清单 7-22 中的src/front_of_house.rs文件后,它才会编译。
Filename: src/lib.rs 文件名:src/lib.rs
mod front_of_house;
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
Next, place the code that was in the curly brackets into a new file named
src/front_of_house.rs, as shown in Listing 7-22. The compiler knows to look
in this file because it came across the module declaration in the crate root
with the name front_of_house
.
接下来,将大括号中的代码放入名为src/front_of_house.rs 的新文件中,如清单 7-22 所示。编译器知道要查找此文件,因为它在箱根中遇到了名为front_of_house
的模块声明。
Filename: src/front_of_house.rs
文件名:src/front_of_house.rs
pub mod hosting {
pub fn add_to_waitlist() {}
}
Note that you only need to load a file using a mod
declaration once in your
module tree. Once the compiler knows the file is part of the project (and knows
where in the module tree the code resides because of where you’ve put the mod
statement), other files in your project should refer to the loaded file’s code
using a path to where it was declared, as covered in the “Paths for Referring
to an Item in the Module Tree” section. In other words,
mod
is not an “include” operation that you may have seen in other
programming languages.
请注意,您只需在模块树中使用mod
声明加载一次文件。一旦编译器知道该文件是项目的一部分(并且知道代码在模块树中的位置,因为您放置了mod
语句),项目中的其他文件应该使用以下路径引用加载的文件的代码:它的声明位置,如“引用模块树中项目的路径”忽略部分所述。换句话说, mod
不是您在其他编程语言中看到的“包含”操作。
Next, we’ll extract the hosting
module to its own file. The process is a bit
different because hosting
is a child module of front_of_house
, not of the
root module. We’ll place the file for hosting
in a new directory that will be
named for its ancestors in the module tree, in this case src/front_of_house.
接下来,我们将把hosting
模块提取到它自己的文件中。这个过程有点不同,因为hosting
是front_of_house
的子模块,而不是根模块。我们将把要hosting
文件放置在一个新目录中,该目录将以其在模块树中的祖先命名,在本例中为 src/front_of_house 。
To start moving hosting
, we change src/front_of_house.rs to contain only
the declaration of the hosting
module:
要开始移动hosting
,我们更改src/front_of_house.rs以仅包含hosting
模块的声明:
Filename: src/front_of_house.rs
文件名:src/front_of_house.rs
pub mod hosting;
Then we create a src/front_of_house directory and a hosting.rs file to
contain the definitions made in the hosting
module:
然后我们创建一个src/front_of_house目录和一个hosting.rs文件来包含在hosting
模块中所做的定义:
Filename: src/front_of_house/hosting.rs
文件名:src/front_of_house/hosting.rs
pub fn add_to_waitlist() {}
If we instead put hosting.rs in the src directory, the compiler would
expect the hosting.rs code to be in a hosting
module declared in the crate
root, and not declared as a child of the front_of_house
module. The
compiler’s rules for which files to check for which modules’ code mean the
directories and files more closely match the module tree.
如果我们将Hosting.rs放在src目录中,编译器会期望Hosting.rs代码位于 crate 根中声明的hosting
模块中,而不是声明为front_of_house
模块的子模块。编译器关于哪些文件检查哪些模块代码的规则意味着目录和文件与模块树更加匹配。
Alternate File Paths 备用文件路径
So far we’ve covered the most idiomatic file paths the Rust compiler uses,
but Rust also supports an older style of file path. For a module named
front_of_house
declared in the crate root, the compiler will look for the
module’s code in:
到目前为止,我们已经介绍了 Rust 编译器使用的最惯用的文件路径,但 Rust 还支持旧样式的文件路径。对于在 crate 根中声明的名为front_of_house
的模块,编译器将在以下位置查找该模块的代码:
- src/front_of_house.rs (what we covered)
src/front_of_house.rs (我们涵盖的内容) - src/front_of_house/mod.rs (older style, still supported path)
src/front_of_house/mod.rs (较旧的样式,仍然受支持的路径)
For a module named hosting
that is a submodule of front_of_house
, the
compiler will look for the module’s code in:
对于名为hosting
模块(它是front_of_house
的子模块),编译器将在以下位置查找该模块的代码:
- src/front_of_house/hosting.rs (what we covered)
src/front_of_house/hosting.rs (我们介绍的内容) - src/front_of_house/hosting/mod.rs (older style, still supported path)
src/front_of_house/hosting/mod.rs (较旧的样式,仍然受支持的路径)
If you use both styles for the same module, you’ll get a compiler error.
Using a mix of both styles for different modules in the same project is
allowed, but might be confusing for people navigating your project.
如果您对同一模块使用两种样式,则会出现编译器错误。允许在同一项目中的不同模块中混合使用两种样式,但可能会让浏览项目的人感到困惑。
The main downside to the style that uses files named mod.rs is that your
project can end up with many files named mod.rs, which can get confusing
when you have them open in your editor at the same time.
使用名为mod.rs的文件的样式的主要缺点是,您的项目最终可能会包含许多名为mod.rs的文件,当您同时在编辑器中打开它们时,这可能会造成混乱。
We’ve moved each module’s code to a separate file, and the module tree remains
the same. The function calls in eat_at_restaurant
will work without any
modification, even though the definitions live in different files. This
technique lets you move modules to new files as they grow in size.
我们已将每个模块的代码移至单独的文件中,并且模块树保持不变。 eat_at_restaurant
中的函数调用无需任何修改即可工作,即使定义位于不同的文件中。此技术允许您在模块大小增长时将模块移动到新文件中。
Note that the pub use crate::front_of_house::hosting
statement in
src/lib.rs also hasn’t changed, nor does use
have any impact on what files
are compiled as part of the crate. The mod
keyword declares modules, and Rust
looks in a file with the same name as the module for the code that goes into
that module.
请注意, src/lib.rs中的pub use crate::front_of_house::hosting
语句也没有更改, use
对编译为 crate 一部分的文件也没有任何影响。 mod
关键字声明模块,Rust 在与模块同名的文件中查找进入该模块的代码。
Summary 概括
Rust lets you split a package into multiple crates and a crate into modules so
you can refer to items defined in one module from another module. You can do
this by specifying absolute or relative paths. These paths can be brought into
scope with a use
statement so you can use a shorter path for multiple uses of
the item in that scope. Module code is private by default, but you can make
definitions public by adding the pub
keyword.
Rust 允许您将一个包拆分为多个板条箱,并将一个板条箱拆分为模块,以便您可以从另一个模块引用一个模块中定义的项目。您可以通过指定绝对或相对路径来完成此操作。可以use
语句将这些路径引入范围,以便您可以使用较短的路径在该范围内多次使用该项目。模块代码默认是私有的,但您可以通过添加pub
关键字将定义公开。
In the next chapter, we’ll look at some collection data structures in the
standard library that you can use in your neatly organized code.
在下一章中,我们将介绍标准库中的一些集合数据结构,您可以在组织整齐的代码中使用它们。
Common Collections 常见集合
Rust’s standard library includes a number of very useful data structures called
collections. Most other data types represent one specific value, but
collections can contain multiple values. Unlike the built-in array and tuple
types, the data these collections point to is stored on the heap, which means
the amount of data does not need to be known at compile time and can grow or
shrink as the program runs. Each kind of collection has different capabilities
and costs, and choosing an appropriate one for your current situation is a
skill you’ll develop over time. In this chapter, we’ll discuss three
collections that are used very often in Rust programs:
Rust 的标准库包含许多非常有用的数据结构,称为集合。大多数其他数据类型表示一个特定值,但集合可以包含多个值。与内置数组和元组类型不同,这些集合指向的数据存储在堆上,这意味着数据量不需要在编译时知道,并且可以随着程序运行而增长或收缩。每种类型的集合都有不同的功能和成本,选择适合您当前情况的集合是一项您将随着时间的推移而发展的技能。在本章中,我们将讨论 Rust 程序中经常使用的三个集合:
- A vector allows you to store a variable number of values next to each other.
向量允许您存储彼此相邻的可变数量的值。 - A string is a collection of characters. We’ve mentioned the
String
type previously, but in this chapter we’ll talk about it in depth.
字符串是字符的集合。我们之前已经提到过String
类型,但在本章中我们将深入讨论它。 - A hash map allows you to associate a value with a specific key. It’s a
particular implementation of the more general data structure called a map.
哈希映射允许您将值与特定键相关联。它是称为映射的更通用数据结构的特定实现。
To learn about the other kinds of collections provided by the standard library,
see the documentation.
要了解标准库提供的其他类型的集合,请参阅文档。
We’ll discuss how to create and update vectors, strings, and hash maps, as well
as what makes each special.
我们将讨论如何创建和更新向量、字符串和哈希映射,以及它们的特殊之处。
Storing Lists of Values with Vectors
使用向量存储值列表
The first collection type we’ll look at is Vec<T>
, also known as a vector.
Vectors allow you to store more than one value in a single data structure that
puts all the values next to each other in memory. Vectors can only store values
of the same type. They are useful when you have a list of items, such as the
lines of text in a file or the prices of items in a shopping cart.
我们要查看的第一个集合类型是Vec<T>
,也称为向量。向量允许您在单个数据结构中存储多个值,该数据结构将所有值在内存中彼此相邻。向量只能存储相同类型的值。当您有一个项目列表(例如文件中的文本行或购物车中的项目价格)时,它们非常有用。
Creating a New Vector 创建一个新向量
To create a new empty vector, we call the Vec::new
function, as shown in
Listing 8-1.
为了创建一个新的空向量,我们调用Vec::new
函数,如清单 8-1 所示。
Note that we added a type annotation here. Because we aren’t inserting any
values into this vector, Rust doesn’t know what kind of elements we intend to
store. This is an important point. Vectors are implemented using generics;
we’ll cover how to use generics with your own types in Chapter 10. For now,
know that the Vec<T>
type provided by the standard library can hold any type.
When we create a vector to hold a specific type, we can specify the type within
angle brackets. In Listing 8-1, we’ve told Rust that the Vec<T>
in v
will
hold elements of the i32
type.
请注意,我们在这里添加了类型注释。因为我们没有向该向量插入任何值,所以 Rust 不知道我们打算存储什么类型的元素。这是很重要的一点。向量是使用泛型实现的;我们将在第 10 章中介绍如何将泛型与您自己的类型一起使用。现在,请知道标准库提供的Vec<T>
类型可以保存任何类型。当我们创建一个向量来保存特定类型时,我们可以在尖括号内指定类型。在清单 8-1 中,我们告诉 Rust v
中的Vec<T>
将保存i32
类型的元素。
More often, you’ll create a Vec<T>
with initial values and Rust will infer
the type of value you want to store, so you rarely need to do this type
annotation. Rust conveniently provides the vec!
macro, which will create a
new vector that holds the values you give it. Listing 8-2 creates a new
Vec<i32>
that holds the values 1
, 2
, and 3
. The integer type is i32
because that’s the default integer type, as we discussed in the “Data
Types” section of Chapter 3.
更常见的是,您将创建一个带有初始值的Vec<T>
,Rust 将推断您要存储的值的类型,因此您很少需要执行此类型注释。 Rust 方便地提供了vec!
宏,它将创建一个新的向量来保存您给它的值。清单 8-2 创建了一个新的Vec<i32>
来保存值1
、 2
和3
。整数类型是i32
因为这是默认的整数类型,正如我们在第 3 章的“数据类型”忽略部分中讨论的那样。
Because we’ve given initial i32
values, Rust can infer that the type of v
is Vec<i32>
, and the type annotation isn’t necessary. Next, we’ll look at how
to modify a vector.
因为我们已经给出了初始i32
值,Rust 可以推断出v
的类型是Vec<i32>
,并且类型注释不是必需的。接下来,我们将了解如何修改向量。
Updating a Vector 更新向量
To create a vector and then add elements to it, we can use the push
method,
as shown in Listing 8-3.
要创建一个向量并向其中添加元素,我们可以使用push
方法,如清单8-3所示。
As with any variable, if we want to be able to change its value, we need to
make it mutable using the mut
keyword, as discussed in Chapter 3. The numbers
we place inside are all of type i32
, and Rust infers this from the data, so
we don’t need the Vec<i32>
annotation.
与任何变量一样,如果我们希望能够更改其值,我们需要使用mut
关键字使其可变,如第 3 章中所述。我们放置在其中的数字都是i32
类型,Rust 从数据,所以我们不需要Vec<i32>
注释。
Reading Elements of Vectors
读取向量的元素
There are two ways to reference a value stored in a vector: via indexing or by
using the get
method. In the following examples, we’ve annotated the types of
the values that are returned from these functions for extra clarity.
有两种方法可以引用存储在向量中的值:通过索引或使用get
方法。在以下示例中,为了更加清晰起见,我们注释了从这些函数返回的值的类型。
Listing 8-4 shows both methods of accessing a value in a vector, with indexing
syntax and the get
method.
清单 8-4 显示了访问向量中的值的两种方法,即索引语法和get
方法。
Note a few details here. We use the index value of 2
to get the third element
because vectors are indexed by number, starting at zero. Using &
and []
gives us a reference to the element at the index value. When we use the get
method with the index passed as an argument, we get an Option<&T>
that we can
use with match
.
请注意此处的一些细节。我们使用索引值2
来获取第三个元素,因为向量是按数字索引的,从零开始。使用&
和[]
为我们提供了对索引值处的元素的引用。当我们使用get
方法并将索引作为参数传递时,我们会得到一个Option<&T>
,我们可以将其与match
一起使用。
Rust provides these two ways to reference an element so you can choose how the
program behaves when you try to use an index value outside the range of
existing elements. As an example, let’s see what happens when we have a vector
of five elements and then we try to access an element at index 100 with each
technique, as shown in Listing 8-5.
Rust 提供了这两种引用元素的方法,因此当您尝试使用现有元素范围之外的索引值时,您可以选择程序的行为方式。作为一个例子,让我们看看当我们有一个包含五个元素的向量,然后我们尝试使用每种技术访问索引 100 处的元素时会发生什么,如清单 8-5 所示。
When we run this code, the first []
method will cause the program to panic
because it references a nonexistent element. This method is best used when you
want your program to crash if there’s an attempt to access an element past the
end of the vector.
当我们运行这段代码时,第一个[]
方法将导致程序崩溃,因为它引用了一个不存在的元素。当您希望程序在尝试访问超出向量末尾的元素时崩溃时,最好使用此方法。
When the get
method is passed an index that is outside the vector, it returns
None
without panicking. You would use this method if accessing an element
beyond the range of the vector may happen occasionally under normal
circumstances. Your code will then have logic to handle having either
Some(&element)
or None
, as discussed in Chapter 6. For example, the index
could be coming from a person entering a number. If they accidentally enter a
number that’s too large and the program gets a None
value, you could tell the
user how many items are in the current vector and give them another chance to
enter a valid value. That would be more user-friendly than crashing the program
due to a typo!
当get
方法传递向量外部的索引时,它会返回None
而不会出现恐慌。如果正常情况下偶尔会访问超出向量范围的元素,则可以使用此方法。然后,您的代码将具有处理Some(&element)
或None
逻辑,如第 6 章中所述。例如,索引可能来自输入数字的人。如果他们不小心输入了太大的数字并且程序获得了None
值,您可以告诉用户当前向量中有多少项,并给他们另一次输入有效值的机会。这比由于拼写错误而导致程序崩溃更加用户友好!
When the program has a valid reference, the borrow checker enforces the
ownership and borrowing rules (covered in Chapter 4) to ensure this reference
and any other references to the contents of the vector remain valid. Recall the
rule that states you can’t have mutable and immutable references in the same
scope. That rule applies in Listing 8-6, where we hold an immutable reference
to the first element in a vector and try to add an element to the end. This
program won’t work if we also try to refer to that element later in the
function.
当程序具有有效引用时,借用检查器会强制执行所有权和借用规则(第 4 章中介绍),以确保该引用以及对向量内容的任何其他引用保持有效。回想一下规则,该规则规定同一范围内不能有可变引用和不可变引用。该规则适用于清单 8-6,其中我们保存对向量中第一个元素的不可变引用,并尝试将一个元素添加到末尾。如果我们稍后还尝试在函数中引用该元素,则该程序将无法工作。
Compiling this code will result in this error:
编译此代码将导致以下错误:
$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:6:5
|
4 | let first = &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
The code in Listing 8-6 might look like it should work: why should a reference
to the first element care about changes at the end of the vector? This error is
due to the way vectors work: because vectors put the values next to each other
in memory, adding a new element onto the end of the vector might require
allocating new memory and copying the old elements to the new space, if there
isn’t enough room to put all the elements next to each other where the vector
is currently stored. In that case, the reference to the first element would be
pointing to deallocated memory. The borrowing rules prevent programs from
ending up in that situation.
清单 8-6 中的代码可能看起来应该可以工作:为什么对第一个元素的引用应该关心向量末尾的变化?此错误是由于向量的工作方式造成的:因为向量将值放在内存中彼此相邻的位置,因此在向量末尾添加新元素可能需要分配新内存并将旧元素复制到新空间(如果有)没有足够的空间将当前存储向量的所有元素彼此相邻。在这种情况下,对第一个元素的引用将指向已释放的内存。借用规则可以防止程序陷入这种情况。
Note: For more on the implementation details of the Vec<T>
type, see “The
Rustonomicon”.
注意:有关Vec<T>
类型的实现细节的更多信息,请参阅“The Rustonomicon” 。
Iterating Over the Values in a Vector
迭代向量中的值
To access each element in a vector in turn, we would iterate through all of the
elements rather than use indices to access one at a time. Listing 8-7 shows how
to use a for
loop to get immutable references to each element in a vector of
i32
values and print them.
为了依次访问向量中的每个元素,我们将迭代所有元素,而不是使用索引一次访问一个元素。清单 8-7 展示了如何使用for
循环来获取对i32
值向量中每个元素的不可变引用并打印它们。
We can also iterate over mutable references to each element in a mutable vector
in order to make changes to all the elements. The for
loop in Listing 8-8
will add 50
to each element.
我们还可以迭代对可变向量中每个元素的可变引用,以便对所有元素进行更改。清单 8-8 中的for
循环将为每个元素添加50
。
To change the value that the mutable reference refers to, we have to use the
*
dereference operator to get to the value in i
before we can use the +=
operator. We’ll talk more about the dereference operator in the “Following the
Pointer to the Value with the Dereference Operator”
section of Chapter 15.
要更改可变引用引用的值,我们必须先使用*
取消引用运算符来获取i
中的值,然后才能使用+=
运算符。我们将在第 15 章的“使用解引用运算符跟随指向值的指针”忽略部分中详细讨论解引用运算符。
Iterating over a vector, whether immutably or mutably, is safe because of the
borrow checker’s rules. If we attempted to insert or remove items in the for
loop bodies in Listing 8-7 and Listing 8-8, we would get a compiler error
similar to the one we got with the code in Listing 8-6. The reference to the
vector that the for
loop holds prevents simultaneous modification of the
whole vector.
由于借用检查器的规则,无论是不可变的还是可变的,迭代向量都是安全的。如果我们尝试在清单 8-7 和清单 8-8 中的for
循环体中插入或删除项目,我们将得到一个与清单 8-6 中的代码类似的编译器错误。对for
循环保存的向量的引用可以防止同时修改整个向量。
Using an Enum to Store Multiple Types
使用枚举来存储多种类型
Vectors can only store values that are of the same type. This can be
inconvenient; there are definitely use cases for needing to store a list of
items of different types. Fortunately, the variants of an enum are defined
under the same enum type, so when we need one type to represent elements of
different types, we can define and use an enum!
向量只能存储相同类型的值。这可能会带来不便;肯定存在需要存储不同类型的项目列表的用例。幸运的是,枚举的变体是在同一枚举类型下定义的,因此当我们需要一种类型来表示不同类型的元素时,我们可以定义并使用枚举!
For example, say we want to get values from a row in a spreadsheet in which
some of the columns in the row contain integers, some floating-point numbers,
and some strings. We can define an enum whose variants will hold the different
value types, and all the enum variants will be considered the same type: that
of the enum. Then we can create a vector to hold that enum and so, ultimately,
hold different types. We’ve demonstrated this in Listing 8-9.
例如,假设我们想要从电子表格中的一行获取值,其中该行中的某些列包含整数、一些浮点数和一些字符串。我们可以定义一个枚举,其变体将保存不同的值类型,并且所有枚举变体将被视为同一类型:枚举的类型。然后我们可以创建一个向量来保存该枚举,因此最终可以保存不同的类型。我们在清单 8-9 中演示了这一点。
Rust needs to know what types will be in the vector at compile time so it knows
exactly how much memory on the heap will be needed to store each element. We
must also be explicit about what types are allowed in this vector. If Rust
allowed a vector to hold any type, there would be a chance that one or more of
the types would cause errors with the operations performed on the elements of
the vector. Using an enum plus a match
expression means that Rust will ensure
at compile time that every possible case is handled, as discussed in Chapter 6.
Rust 需要在编译时知道向量中的类型,以便准确地知道堆上需要多少内存来存储每个元素。我们还必须明确该向量中允许的类型。如果 Rust 允许向量保存任何类型,则一种或多种类型可能会导致对向量元素执行的操作出错。使用枚举加上match
表达式意味着 Rust 将确保在编译时处理每种可能的情况,如第 6 章所述。
If you don’t know the exhaustive set of types a program will get at runtime to
store in a vector, the enum technique won’t work. Instead, you can use a trait
object, which we’ll cover in Chapter 17.
如果您不知道程序在运行时将获得并存储在向量中的详尽类型集,则枚举技术将不起作用。相反,您可以使用特征对象,我们将在第 17 章中介绍它。
Now that we’ve discussed some of the most common ways to use vectors, be sure
to review the API documentation for all of the many
useful methods defined on Vec<T>
by the standard library. For example, in
addition to push
, a pop
method removes and returns the last element.
现在我们已经讨论了使用向量的一些最常见方法,请务必查看API 文档,以了解标准库在Vec<T>
上定义的所有有用方法。例如,除了push
之外, pop
方法还会删除并返回最后一个元素。
Dropping a Vector Drops Its Elements
删除向量也会删除其元素
Like any other struct
, a vector is freed when it goes out of scope, as
annotated in Listing 8-10.
与任何其他struct
一样,向量在超出范围时会被释放,如清单 8-10 中所示。
When the vector gets dropped, all of its contents are also dropped, meaning the
integers it holds will be cleaned up. The borrow checker ensures that any
references to contents of a vector are only used while the vector itself is
valid.
当向量被删除时,它的所有内容也会被删除,这意味着它保存的整数将被清除。借用检查器确保对向量内容的任何引用仅在向量本身有效时使用。
Let’s move on to the next collection type: String
!
让我们继续讨论下一个集合类型: String
!
Storing UTF-8 Encoded Text with Strings
使用字符串存储 UTF-8 编码文本
We talked about strings in Chapter 4, but we’ll look at them in more depth now.
New Rustaceans commonly get stuck on strings for a combination of three
reasons: Rust’s propensity for exposing possible errors, strings being a more
complicated data structure than many programmers give them credit for, and
UTF-8. These factors combine in a way that can seem difficult when you’re
coming from other programming languages.
我们在第 4 章中讨论了字符串,但现在我们将更深入地讨论它们。 Rustace 新手通常会因为三个原因而陷入字符串困境:Rust 暴露可能错误的倾向、字符串是一种比许多程序员所认为的更复杂的数据结构,以及 UTF-8。当您来自其他编程语言时,这些因素以一种看似困难的方式结合在一起。
We discuss strings in the context of collections because strings are
implemented as a collection of bytes, plus some methods to provide useful
functionality when those bytes are interpreted as text. In this section, we’ll
talk about the operations on String
that every collection type has, such as
creating, updating, and reading. We’ll also discuss the ways in which String
is different from the other collections, namely how indexing into a String
is
complicated by the differences between how people and computers interpret
String
data.
我们在集合的上下文中讨论字符串,因为字符串是作为字节集合实现的,另外还有一些方法可以在这些字节解释为文本时提供有用的功能。在本节中,我们将讨论每种集合类型对String
的操作,例如创建、更新和读取。我们还将讨论String
与其他集合的不同之处,即由于人和计算机解释String
数据的方式不同,对String
索引变得复杂。
What Is a String? 什么是字符串?
We’ll first define what we mean by the term string. Rust has only one string
type in the core language, which is the string slice str
that is usually seen
in its borrowed form &str
. In Chapter 4, we talked about string slices,
which are references to some UTF-8 encoded string data stored elsewhere. String
literals, for example, are stored in the program’s binary and are therefore
string slices.
我们首先定义术语string的含义。 Rust 在核心语言中只有一种字符串类型,即字符串切片str
,通常以其借用形式&str
出现。在第 4 章中,我们讨论了字符串切片,它是对存储在其他地方的一些 UTF-8 编码字符串数据的引用。例如,字符串文字存储在程序的二进制文件中,因此是字符串切片。
The String
type, which is provided by Rust’s standard library rather than
coded into the core language, is a growable, mutable, owned, UTF-8 encoded
string type. When Rustaceans refer to “strings” in Rust, they might be
referring to either the String
or the string slice &str
types, not just one
of those types. Although this section is largely about String
, both types are
used heavily in Rust’s standard library, and both String
and string slices
are UTF-8 encoded.String
类型由 Rust 的标准库提供,而不是编码到核心语言中,是一种可增长的、可变的、拥有的、UTF-8 编码的字符串类型。当 Rustaceans 在 Rust 中引用“字符串”时,他们可能指的是String
或字符串切片&str
类型,而不仅仅是这些类型之一。尽管本节主要讨论String
,但这两种类型在 Rust 的标准库中都大量使用,并且String
和字符串切片都是 UTF-8 编码的。
Creating a New String 创建一个新字符串
Many of the same operations available with Vec<T>
are available with String
as well because String
is actually implemented as a wrapper around a vector
of bytes with some extra guarantees, restrictions, and capabilities. An example
of a function that works the same way with Vec<T>
and String
is the new
function to create an instance, shown in Listing 8-11.Vec<T>
可用的许多相同操作也可用于String
,因为String
实际上是作为字节向量的包装器实现的,并具有一些额外的保证、限制和功能。与Vec<T>
和String
工作方式相同的函数示例是创建实例的new
函数,如清单 8-11 所示。
This line creates a new, empty string called s
, into which we can then load
data. Often, we’ll have some initial data with which we want to start the
string. For that, we use the to_string
method, which is available on any type
that implements the Display
trait, as string literals do. Listing 8-12 shows
two examples.
此行创建一个名为s
的新空字符串,然后我们可以向其中加载数据。通常,我们会有一些初始数据来开始字符串。为此,我们使用to_string
方法,该方法可用于任何实现Display
特征的类型,就像字符串文字一样。清单 8-12 显示了两个示例。
This code creates a string containing initial contents
.
此代码创建一个包含initial contents
的字符串。
We can also use the function String::from
to create a String
from a string
literal. The code in Listing 8-13 is equivalent to the code in Listing 8-12
that uses to_string
.
我们还可以使用函数String::from
从字符串文字创建String
。清单 8-13 中的代码与清单 8-12 中使用to_string
代码等效。
Because strings are used for so many things, we can use many different generic
APIs for strings, providing us with a lot of options. Some of them can seem
redundant, but they all have their place! In this case, String::from
and
to_string
do the same thing, so which one you choose is a matter of style and
readability.
因为字符串有很多用途,所以我们可以使用许多不同的字符串通用 API,为我们提供了很多选择。其中一些看似多余,但它们都有自己的位置!在本例中, String::from
和to_string
执行相同的操作,因此您选择哪一个取决于样式和可读性。
Remember that strings are UTF-8 encoded, so we can include any properly encoded
data in them, as shown in Listing 8-14.
请记住,字符串是 UTF-8 编码的,因此我们可以在其中包含任何正确编码的数据,如清单 8-14 所示。
All of these are valid String
values.
所有这些都是有效的String
值。
Updating a String 更新字符串
A String
can grow in size and its contents can change, just like the contents
of a Vec<T>
, if you push more data into it. In addition, you can conveniently
use the +
operator or the format!
macro to concatenate String
values.
如果将更多数据放入 String 中,则String
大小可能会增加,并且其内容可能会发生变化,就像Vec<T>
的内容一样。此外,您还可以方便地使用+
运算符或format!
用于连接String
值的宏。
Appending to a String with push_str
and push
使用push_str
和push
附加到字符串
We can grow a String
by using the push_str
method to append a string slice,
as shown in Listing 8-15.
我们可以通过使用push_str
方法追加一个字符串切片来增长一个String
,如清单8-15所示。
After these two lines, s
will contain foobar
. The push_str
method takes a
string slice because we don’t necessarily want to take ownership of the
parameter. For example, in the code in Listing 8-16, we want to be able to use
s2
after appending its contents to s1
.
在这两行之后, s
将包含foobar
。 push_str
方法接受一个字符串切片,因为我们不一定想要获得该参数的所有权。例如,在清单 8-16 的代码中,我们希望在将 s2 的内容附加到s1
后能够使用s2
。
If the push_str
method took ownership of s2
, we wouldn’t be able to print
its value on the last line. However, this code works as we’d expect!
如果push_str
方法获得了s2
的所有权,我们将无法在最后一行打印它的值。然而,这段代码的工作原理正如我们所期望的!
The push
method takes a single character as a parameter and adds it to the
String
. Listing 8-17 adds the letter l to a String
using the push
method.push
方法采用单个字符作为参数并将其添加到String
中。清单 8-17 使用push
方法将字母l添加到String
中。
As a result, s
will contain lol
.
结果, s
将包含lol
。
Concatenation with the +
Operator or the format!
Macro
使用+
运算符或format!
宏
Often, you’ll want to combine two existing strings. One way to do so is to use
the +
operator, as shown in Listing 8-18.
通常,您需要组合两个现有的字符串。一种方法是使用+
运算符,如清单 8-18 所示。
The string s3
will contain Hello, world!
. The reason s1
is no longer
valid after the addition, and the reason we used a reference to s2
, has to do
with the signature of the method that’s called when we use the +
operator.
The +
operator uses the add
method, whose signature looks something like
this:
字符串s3
将包含Hello, world!
。 s1
在添加后不再有效的原因以及我们使用对s2
的引用的原因与我们使用+
运算符时调用的方法的签名有关。 +
运算符使用add
方法,其签名如下所示:
fn add(self, s: &str) -> String {
In the standard library, you’ll see add
defined using generics and associated
types. Here, we’ve substituted in concrete types, which is what happens when we
call this method with String
values. We’ll discuss generics in Chapter 10.
This signature gives us the clues we need in order to understand the tricky
bits of the +
operator.
在标准库中,您将看到使用泛型和关联类型add
定义。在这里,我们替换为具体类型,这就是当我们使用String
值调用此方法时发生的情况。我们将在第 10 章讨论泛型。这个签名为我们提供了理解+
运算符的棘手部分所需的线索。
First, s2
has an &
, meaning that we’re adding a reference of the second
string to the first string. This is because of the s
parameter in the add
function: we can only add a &str
to a String
; we can’t add two String
values together. But wait—the type of &s2
is &String
, not &str
, as
specified in the second parameter to add
. So why does Listing 8-18 compile?
首先, s2
有一个&
,这意味着我们将第二个字符串的引用添加到第一个字符串。这是因为add
函数中的s
参数:我们只能将&str
添加到String
;我们不能将两个String
值相加。但是等等, &s2
的类型是&String
,而不是&str
,如add
第二个参数中指定的那样。那么清单 8-18 为什么可以编译呢?
The reason we’re able to use &s2
in the call to add
is that the compiler
can coerce the &String
argument into a &str
. When we call the add
method, Rust uses a deref coercion, which here turns &s2
into &s2[..]
.
We’ll discuss deref coercion in more depth in Chapter 15. Because add
does
not take ownership of the s
parameter, s2
will still be a valid String
after this operation.
我们能够在add
调用中使用&s2
原因是编译器可以将&String
参数强制转换为&str
。当我们调用add
方法时,Rust 使用deref 强制转换,将&s2
转换为&s2[..]
。我们将在第 15 章中更深入地讨论 deref 强制转换。因为add
不获取s
参数的所有权,所以在此操作之后s2
仍然是一个有效的String
。
Second, we can see in the signature that add
takes ownership of self
because self
does not have an &
. This means s1
in Listing 8-18 will be
moved into the add
call and will no longer be valid after that. So, although
let s3 = s1 + &s2;
looks like it will copy both strings and create a new one,
this statement actually takes ownership of s1
, appends a copy of the contents
of s2
, and then returns ownership of the result. In other words, it looks
like it’s making a lot of copies, but it isn’t; the implementation is more
efficient than copying.
其次,我们可以在签名中看到add
拥有self
的所有权,因为self
没有&
。这意味着清单 8-18 中的s1
将被移至add
调用中,并且此后将不再有效。所以,虽然let s3 = s1 + &s2;
看起来它会复制两个字符串并创建一个新字符串,该语句实际上获取s1
的所有权,附加s2
内容的副本,然后返回结果的所有权。换句话说,看起来它正在制作大量副本,但事实并非如此;实施比复制更有效率。
If we need to concatenate multiple strings, the behavior of the +
operator
gets unwieldy:
如果我们需要连接多个字符串, +
运算符的行为就会变得笨拙:
At this point, s
will be tic-tac-toe
. With all of the +
and "
characters, it’s difficult to see what’s going on. For combining strings in
more complicated ways, we can instead use the format!
macro:
此时, s
将是tic-tac-toe
。对于所有+
和"
字符,很难看出发生了什么。为了以更复杂的方式组合字符串,我们可以使用format!
宏:
This code also sets s
to tic-tac-toe
. The format!
macro works like
println!
, but instead of printing the output to the screen, it returns a
String
with the contents. The version of the code using format!
is much
easier to read, and the code generated by the format!
macro uses references
so that this call doesn’t take ownership of any of its parameters.
此代码还将s
设置为tic-tac-toe
。 format!
宏的工作方式类似于println!
,但它不是将输出打印到屏幕上,而是返回一个包含内容的String
。版本代码使用format!
更容易阅读,而且format!
宏使用引用,因此该调用不会取得其任何参数的所有权。
Indexing into Strings 索引到字符串
In many other programming languages, accessing individual characters in a
string by referencing them by index is a valid and common operation. However,
if you try to access parts of a String
using indexing syntax in Rust, you’ll
get an error. Consider the invalid code in Listing 8-19.
在许多其他编程语言中,通过索引引用字符串中的各个字符来访问它们是有效且常见的操作。但是,如果您尝试在 Rust 中使用索引语法访问String
的一部分,您将收到错误。考虑清单 8-19 中的无效代码。
This code will result in the following error:
此代码将导致以下错误:
$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0277]: the type `str` cannot be indexed by `{integer}`
--> src/main.rs:3:16
|
3 | let h = s1[0];
| ^ string indices are ranges of `usize`
|
= help: the trait `SliceIndex<str>` is not implemented for `{integer}`, which is required by `String: Index<_>`
= note: you can use `.chars().nth()` or `.bytes().nth()`
for more information, see chapter 8 in The Book: <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>
= help: the trait `SliceIndex<[_]>` is implemented for `usize`
= help: for that trait implementation, expected `[_]`, found `str`
= note: required for `String` to implement `Index<{integer}>`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `collections` (bin "collections") due to 1 previous error
The error and the note tell the story: Rust strings don’t support indexing. But
why not? To answer that question, we need to discuss how Rust stores strings in
memory.
错误和注释说明了这一点:Rust 字符串不支持索引。但为什么不呢?为了回答这个问题,我们需要讨论 Rust 如何在内存中存储字符串。
Internal Representation 内部代表
A String
is a wrapper over a Vec<u8>
. Let’s look at some of our properly
encoded UTF-8 example strings from Listing 8-14. First, this one:String
是Vec<u8>
的包装器。让我们看看清单 8-14 中一些正确编码的 UTF-8 示例字符串。首先是这个:
In this case, len
will be 4
, which means the vector storing the string
"Hola"
is 4 bytes long. Each of these letters takes one byte when encoded in
UTF-8. The following line, however, may surprise you (note that this string
begins with the capital Cyrillic letter Ze, not the number 3):
在这种情况下, len
将为4
,这意味着存储字符串"Hola"
的向量有 4 个字节长。当以 UTF-8 编码时,每个字母占用一个字节。然而,下面的行可能会让您感到惊讶(请注意,该字符串以大写西里尔字母Ze开头,而不是数字 3):
If you were asked how long the string is, you might say 12. In fact, Rust’s
answer is 24: that’s the number of bytes it takes to encode “Здравствуйте” in
UTF-8, because each Unicode scalar value in that string takes 2 bytes of
storage. Therefore, an index into the string’s bytes will not always correlate
to a valid Unicode scalar value. To demonstrate, consider this invalid Rust
code:
如果你被问到字符串有多长,你可能会说 12。事实上,Rust 的答案是 24:这是用 UTF-8 编码“Здравствуйте”所需的字节数,因为该字符串中的每个 Unicode 标量值都需要 2字节存储。因此,字符串字节的索引并不总是与有效的 Unicode 标量值相关。为了进行演示,请考虑以下无效的 Rust 代码:
let hello = "Здравствуйте";
let answer = &hello[0];
You already know that answer
will not be З
, the first letter. When encoded
in UTF-8, the first byte of З
is 208
and the second is 151
, so it would
seem that answer
should in fact be 208
, but 208
is not a valid character
on its own. Returning 208
is likely not what a user would want if they asked
for the first letter of this string; however, that’s the only data that Rust
has at byte index 0. Users generally don’t want the byte value returned, even
if the string contains only Latin letters: if &"hello"[0]
were valid code
that returned the byte value, it would return 104
, not h
.
您已经知道answer
不会是第一个字母З
。当以 UTF-8 编码时, З
的第一个字节是208
,第二个字节是151
,因此看起来answer
实际上应该是208
,但208
本身并不是有效字符。如果用户询问该字符串的第一个字母,那么返回208
可能不是用户想要的结果;然而,这是 Rust 在字节索引 0 处拥有的唯一数据。用户通常不希望返回字节值,即使字符串仅包含拉丁字母:如果&"hello"[0]
是返回字节值的有效代码,它将返回104
,而不是h
。
The answer, then, is that to avoid returning an unexpected value and causing
bugs that might not be discovered immediately, Rust doesn’t compile this code
at all and prevents misunderstandings early in the development process.
那么答案是,为了避免返回意外值并导致可能无法立即发现的错误,Rust 根本不编译此代码,并防止在开发过程的早期产生误解。
Bytes and Scalar Values and Grapheme Clusters! Oh My!
字节和标量值以及字素簇!天哪!
Another point about UTF-8 is that there are actually three relevant ways to
look at strings from Rust’s perspective: as bytes, scalar values, and grapheme
clusters (the closest thing to what we would call letters).
关于 UTF-8 的另一点是,从 Rust 的角度来看,实际上有三种相关的方式来看待字符串:字节、标量值和字素簇(最接近我们所说的字母)。
If we look at the Hindi word “नमस्ते” written in the Devanagari script, it is
stored as a vector of u8
values that looks like this:
如果我们看一下用梵文脚本编写的印地语单词“नमस्ते”,它存储为u8
值的向量,如下所示:
[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
224, 165, 135]
That’s 18 bytes and is how computers ultimately store this data. If we look at
them as Unicode scalar values, which are what Rust’s char
type is, those
bytes look like this:
这是 18 个字节,也是计算机最终存储这些数据的方式。如果我们将它们视为 Unicode 标量值(Rust 的char
类型),那么这些字节如下所示:
['न', 'म', 'स', '्', 'त', 'े']
There are six char
values here, but the fourth and sixth are not letters:
they’re diacritics that don’t make sense on their own. Finally, if we look at
them as grapheme clusters, we’d get what a person would call the four letters
that make up the Hindi word:
这里有六个char
值,但第四个和第六个不是字母:它们是本身没有意义的变音符号。最后,如果我们将它们视为字素簇,我们就会得到人们所说的构成印地语单词的四个字母:
["न", "म", "स्", "ते"]
Rust provides different ways of interpreting the raw string data that computers
store so that each program can choose the interpretation it needs, no matter
what human language the data is in.
Rust 提供了不同的方式来解释计算机存储的原始字符串数据,以便每个程序都可以选择它需要的解释,无论数据采用哪种人类语言。
A final reason Rust doesn’t allow us to index into a String
to get a
character is that indexing operations are expected to always take constant time
(O(1)). But it isn’t possible to guarantee that performance with a String
,
because Rust would have to walk through the contents from the beginning to the
index to determine how many valid characters there were.
Rust 不允许我们索引String
来获取字符的最后一个原因是索引操作预计总是需要恒定的时间 (O(1))。但不可能保证String
的性能,因为 Rust 必须从开头到索引遍历内容以确定有多少有效字符。
Slicing Strings 切片字符串
Indexing into a string is often a bad idea because it’s not clear what the
return type of the string-indexing operation should be: a byte value, a
character, a grapheme cluster, or a string slice. If you really need to use
indices to create string slices, therefore, Rust asks you to be more specific.
对字符串进行索引通常是一个坏主意,因为不清楚字符串索引操作的返回类型应该是什么:字节值、字符、字素簇或字符串切片。因此,如果您确实需要使用索引来创建字符串切片,Rust 会要求您更加具体。
Rather than indexing using []
with a single number, you can use []
with a
range to create a string slice containing particular bytes:
您可以使用带有范围的[]
来创建包含特定字节的字符串切片,而不是使用带有单个数字的[]
进行索引:
Here, s
will be a &str
that contains the first four bytes of the string.
Earlier, we mentioned that each of these characters was two bytes, which means
s
will be Зд
.
这里, s
将是一个&str
,包含字符串的前四个字节。之前,我们提到每个字符都是两个字节,这意味着s
将是Зд
。
If we were to try to slice only part of a character’s bytes with something like
&hello[0..1]
, Rust would panic at runtime in the same way as if an invalid
index were accessed in a vector:
如果我们尝试使用&hello[0..1]
之类的内容仅切片字符字节的一部分,Rust 会在运行时出现恐慌,就像在向量中访问无效索引一样:
$ 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
You should use caution when creating string slices with ranges, because doing
so can crash your program.
创建具有范围的字符串切片时应小心谨慎,因为这样做可能会导致程序崩溃。
Methods for Iterating Over Strings
迭代字符串的方法
The best way to operate on pieces of strings is to be explicit about whether
you want characters or bytes. For individual Unicode scalar values, use the
chars
method. Calling chars
on “Зд” separates out and returns two values of
type char
, and you can iterate over the result to access each element:
操作字符串片段的最佳方法是明确您需要字符还是字节。对于单个 Unicode 标量值,请使用chars
方法。在“Зд”上调用chars
会分离并返回两个char
类型的值,您可以迭代结果来访问每个元素:
This code will print the following:
该代码将打印以下内容:
З
д
Alternatively, the bytes
method returns each raw byte, which might be
appropriate for your domain:
或者, bytes
方法返回每个原始字节,这可能适合您的域:
This code will print the four bytes that make up this string:
此代码将打印组成该字符串的四个字节:
208
151
208
180
But be sure to remember that valid Unicode scalar values may be made up of more
than one byte.
但请务必记住,有效的 Unicode 标量值可能由多个字节组成。
Getting grapheme clusters from strings, as with the Devanagari script, is
complex, so this functionality is not provided by the standard library. Crates
are available on crates.io if this is the
functionality you need.
与梵文脚本一样,从字符串获取字素簇很复杂,因此标准库不提供此功能。 crates 可以在crates.io上找到,如果这是您需要的功能,请忽略。
Strings Are Not So Simple
字符串没那么简单
To summarize, strings are complicated. Different programming languages make
different choices about how to present this complexity to the programmer. Rust
has chosen to make the correct handling of String
data the default behavior
for all Rust programs, which means programmers have to put more thought into
handling UTF-8 data up front. This trade-off exposes more of the complexity of
strings than is apparent in other programming languages, but it prevents you
from having to handle errors involving non-ASCII characters later in your
development life cycle.
总而言之,字符串很复杂。不同的编程语言对于如何向程序员呈现这种复杂性做出了不同的选择。 Rust 选择将正确处理String
数据作为所有 Rust 程序的默认行为,这意味着程序员必须预先考虑如何处理 UTF-8 数据。与其他编程语言相比,这种权衡暴露了更多的字符串复杂性,但它使您不必在开发生命周期的后期处理涉及非 ASCII 字符的错误。
The good news is that the standard library offers a lot of functionality built
off the String
and &str
types to help handle these complex situations
correctly. Be sure to check out the documentation for useful methods like
contains
for searching in a string and replace
for substituting parts of a
string with another string.
好消息是,标准库提供了许多基于String
和&str
类型构建的功能,以帮助正确处理这些复杂的情况。请务必查看文档以了解有用的方法,例如用于在字符串中搜索的contains
以及用于用另一个字符串替换字符串的一部分的replace
。
Let’s switch to something a bit less complex: hash maps!
让我们切换到不太复杂的东西:哈希映射!
Storing Keys with Associated Values in Hash Maps
在哈希图中存储键和关联值
The last of our common collections is the hash map. The type HashMap<K, V>
stores a mapping of keys of type K
to values of type V
using a hashing
function, which determines how it places these keys and values into memory.
Many programming languages support this kind of data structure, but they often
use a different name, such as hash, map, object, hash table,
dictionary, or associative array, just to name a few.
我们最后一个常见的集合是哈希图。 HashMap<K, V>
类型使用哈希函数存储K
类型的键到V
类型的值的映射,该映射决定了如何将这些键和值放入内存中。许多编程语言都支持这种数据结构,但它们经常使用不同的名称,例如hash 、 map 、 object 、 hash table 、 dictionary或associative array ,仅举几例。
Hash maps are useful when you want to look up data not by using an index, as
you can with vectors, but by using a key that can be of any type. For example,
in a game, you could keep track of each team’s score in a hash map in which
each key is a team’s name and the values are each team’s score. Given a team
name, you can retrieve its score.
当您想要查找数据时,哈希映射非常有用,而不是像使用向量那样使用索引,而是使用可以是任何类型的键来查找数据。例如,在游戏中,您可以在哈希映射中跟踪每个团队的得分,其中每个键是团队的名称,值是每个团队的得分。给定团队名称,您可以检索其得分。
We’ll go over the basic API of hash maps in this section, but many more goodies
are hiding in the functions defined on HashMap<K, V>
by the standard library.
As always, check the standard library documentation for more information.
我们将在本节中介绍哈希映射的基本 API,但标准库在HashMap<K, V>
上定义的函数中隐藏着更多好东西。与往常一样,请检查标准库文档以获取更多信息。
Creating a New Hash Map
创建新的哈希图
One way to create an empty hash map is to use new
and to add elements with
insert
. In Listing 8-20, we’re keeping track of the scores of two teams whose
names are Blue and Yellow. The Blue team starts with 10 points, and the
Yellow team starts with 50.
创建空哈希映射的一种方法是使用new
并使用insert
添加元素。在清单 8-20 中,我们记录了Blue和Yellow两支球队的得分。蓝队起赛10分,黄队起赛50分。
Note that we need to first use
the HashMap
from the collections portion of
the standard library. Of our three common collections, this one is the least
often used, so it’s not included in the features brought into scope
automatically in the prelude. Hash maps also have less support from the
standard library; there’s no built-in macro to construct them, for example.
请注意,我们需要首先use
标准库集合部分中的HashMap
。在我们的三个常见集合中,这个集合是最不常用的,因此它不包含在序言中自动纳入范围的功能中。标准库对哈希映射的支持也较少;例如,没有内置宏来构造它们。
Just like vectors, hash maps store their data on the heap. This HashMap
has
keys of type String
and values of type i32
. Like vectors, hash maps are
homogeneous: all of the keys must have the same type, and all of the values
must have the same type.
就像向量一样,哈希映射将其数据存储在堆上。此HashMap
具有String
类型的键和i32
类型的值。与向量一样,哈希映射是同质的:所有键必须具有相同的类型,并且所有值必须具有相同的类型。
Accessing Values in a Hash Map
访问哈希图中的值
We can get a value out of the hash map by providing its key to the get
method, as shown in Listing 8-21.
我们可以通过向get
方法提供键来从哈希映射中获取值,如清单 8-21 所示。
Here, score
will have the value that’s associated with the Blue team, and the
result will be 10
. The get
method returns an Option<&V>
; if there’s no
value for that key in the hash map, get
will return None
. This program
handles the Option
by calling copied
to get an Option<i32>
rather than an
Option<&i32>
, then unwrap_or
to set score
to zero if scores
doesn’t
have an entry for the key.
在这里, score
将具有与蓝队关联的值,结果将为10
。 get
方法返回Option<&V>
;如果哈希映射中该键没有值, get
将返回None
。该程序通过调用copied
来处理Option
,以获取Option<i32>
而不是Option<&i32>
,然后unwrap_or
将score
设置为零(如果scores
没有该键的条目)。
We can iterate over each key–value pair in a hash map in a similar manner as we
do with vectors, using a for
loop:
我们可以使用for
循环,以与向量类似的方式迭代哈希映射中的每个键值对:
This code will print each pair in an arbitrary order:
此代码将以任意顺序打印每对:
Yellow: 50
Blue: 10
Hash Maps and Ownership 哈希图和所有权
For types that implement the Copy
trait, like i32
, the values are copied
into the hash map. For owned values like String
, the values will be moved and
the hash map will be the owner of those values, as demonstrated in Listing 8-22.
对于实现Copy
特征的类型(例如i32
,值将被复制到哈希映射中。对于像String
这样的自有值,这些值将被移动,并且哈希映射将成为这些值的所有者,如清单 8-22 所示。
We aren’t able to use the variables field_name
and field_value
after
they’ve been moved into the hash map with the call to insert
.
通过调用insert
将变量field_name
和field_value
移动到哈希映射后,我们无法使用它们。
If we insert references to values into the hash map, the values won’t be moved
into the hash map. The values that the references point to must be valid for at
least as long as the hash map is valid. We’ll talk more about these issues in
the “Validating References with
Lifetimes” section in
Chapter 10.
如果我们将对值的引用插入到哈希映射中,则这些值不会移动到哈希映射中。引用指向的值必须至少在哈希映射有效期间有效。我们将在第 10 章的“使用生命周期验证引用”忽略部分中详细讨论这些问题。
Updating a Hash Map 更新哈希图
Although the number of key and value pairs is growable, each unique key can
only have one value associated with it at a time (but not vice versa: for
example, both the Blue team and the Yellow team could have the value 10
stored in the scores
hash map).
尽管键和值对的数量是可以增长的,但每个唯一键一次只能有一个与其关联的值(反之亦然:例如,蓝队和黄队都可以将值10
存储在scores
哈希图)。
When you want to change the data in a hash map, you have to decide how to
handle the case when a key already has a value assigned. You could replace the
old value with the new value, completely disregarding the old value. You could
keep the old value and ignore the new value, only adding the new value if the
key doesn’t already have a value. Or you could combine the old value and the
new value. Let’s look at how to do each of these!
当您想要更改哈希映射中的数据时,您必须决定如何处理键已分配值的情况。您可以用新值替换旧值,完全忽略旧值。您可以保留旧值并忽略新值,仅在键还没有值时才添加新值。或者您可以将旧值和新值结合起来。让我们看看如何执行这些操作!
Overwriting a Value 覆盖值
If we insert a key and a value into a hash map and then insert that same key
with a different value, the value associated with that key will be replaced.
Even though the code in Listing 8-23 calls insert
twice, the hash map will
only contain one key–value pair because we’re inserting the value for the Blue
team’s key both times.
如果我们将一个键和一个值插入哈希映射,然后插入具有不同值的相同键,则与该键关联的值将被替换。即使清单 8-23 中的代码调用了两次insert
,哈希映射也只会包含一个键值对,因为我们两次都插入了蓝队键的值。
This code will print {"Blue": 25}
. The original value of 10
has been
overwritten.
此代码将打印{"Blue": 25}
。原始值10
已被覆盖。
Adding a Key and Value Only If a Key Isn’t Present
仅当键不存在时才添加键和值
It’s common to check whether a particular key already exists in the hash map
with a value and then to take the following actions: if the key does exist in
the hash map, the existing value should remain the way it is; if the key
doesn’t exist, insert it and a value for it.
检查哈希映射中是否已存在特定键及其值,然后采取以下操作是很常见的:如果哈希映射中确实存在该键,则现有值应保持原样;如果该键不存在,则插入该键及其值。
Hash maps have a special API for this called entry
that takes the key you
want to check as a parameter. The return value of the entry
method is an enum
called Entry
that represents a value that might or might not exist. Let’s say
we want to check whether the key for the Yellow team has a value associated
with it. If it doesn’t, we want to insert the value 50
, and the same for the
Blue team. Using the entry
API, the code looks like Listing 8-24.
哈希映射有一个特殊的 API,称为entry
,它将您要检查的键作为参数。 entry
方法的返回值是一个名为Entry
的枚举,它表示一个可能存在也可能不存在的值。假设我们要检查黄队的密钥是否有与之关联的值。如果没有,我们要插入值50
,蓝队也是如此。使用entry
API,代码如清单 8-24 所示。
The or_insert
method on Entry
is defined to return a mutable reference to
the value for the corresponding Entry
key if that key exists, and if not, it
inserts the parameter as the new value for this key and returns a mutable
reference to the new value. This technique is much cleaner than writing the
logic ourselves and, in addition, plays more nicely with the borrow checker.Entry
上的or_insert
方法被定义为:如果该键存在,则返回对相应Entry
键的值的可变引用;如果不存在,则它将插入参数作为该键的新值,并返回对新值的可变引用。这种技术比我们自己编写逻辑要干净得多,此外,与借用检查器配合得更好。
Running the code in Listing 8-24 will print {"Yellow": 50, "Blue": 10}
. The
first call to entry
will insert the key for the Yellow team with the value
50
because the Yellow team doesn’t have a value already. The second call to
entry
will not change the hash map because the Blue team already has the
value 10
.
运行清单 8-24 中的代码将打印{"Yellow": 50, "Blue": 10}
。第一次调用entry
将插入值为50
黄队密钥,因为黄队还没有值。第二次调用entry
不会更改哈希映射,因为蓝队已经拥有值10
。
Updating a Value Based on the Old Value
根据旧值更新值
Another common use case for hash maps is to look up a key’s value and then
update it based on the old value. For instance, Listing 8-25 shows code that
counts how many times each word appears in some text. We use a hash map with
the words as keys and increment the value to keep track of how many times we’ve
seen that word. If it’s the first time we’ve seen a word, we’ll first insert
the value 0
.
哈希映射的另一个常见用例是查找键的值,然后根据旧值更新它。例如,清单 8-25 显示了计算每个单词在某些文本中出现的次数的代码。我们使用以单词作为键的哈希映射,并增加值以跟踪我们看到该单词的次数。如果这是我们第一次看到一个单词,我们将首先插入值0
。
This code will print {"world": 2, "hello": 1, "wonderful": 1}
. You might see
the same key–value pairs printed in a different order: recall from the
“Accessing Values in a Hash Map” section that
iterating over a hash map happens in an arbitrary order.
此代码将打印{"world": 2, "hello": 1, "wonderful": 1}
。您可能会看到以不同顺序打印的相同键值对:回想一下“访问哈希映射中的值”忽略部分,哈希映射的迭代以任意顺序发生。
The split_whitespace
method returns an iterator over subslices, separated by
whitespace, of the value in text
. The or_insert
method returns a mutable
reference (&mut V
) to the value for the specified key. Here, we store that
mutable reference in the count
variable, so in order to assign to that value,
we must first dereference count
using the asterisk (*
). The mutable
reference goes out of scope at the end of the for
loop, so all of these
changes are safe and allowed by the borrowing rules.split_whitespace
方法返回text
中的值的子切片(以空格分隔)上的迭代器。 or_insert
方法返回对指定键的值的可变引用 ( &mut V
)。在这里,我们将该可变引用存储在count
变量中,因此为了分配给该值,我们必须首先使用星号 ( *
) 取消引用count
。可变引用在for
循环结束时超出范围,因此所有这些更改都是安全的并且是借用规则允许的。
Hashing Functions 哈希函数
By default, HashMap
uses a hashing function called SipHash that can provide
resistance to denial-of-service (DoS) attacks involving hash
tables1. This is not the fastest hashing algorithm
available, but the trade-off for better security that comes with the drop in
performance is worth it. If you profile your code and find that the default
hash function is too slow for your purposes, you can switch to another function
by specifying a different hasher. A hasher is a type that implements the
BuildHasher
trait. We’ll talk about traits and how to implement them in
Chapter 10. You don’t necessarily have to implement
your own hasher from scratch; crates.io
has libraries shared by other Rust users that provide hashers implementing many
common hashing algorithms.
默认情况下, HashMap
使用名为SipHash的哈希函数,该函数可以抵抗涉及哈希表1ignore的拒绝服务 (DoS) 攻击。这不是可用的最快的哈希算法,但为了获得更好的安全性而带来的性能下降是值得的。如果您分析代码并发现默认哈希函数对于您的目的而言太慢,则可以通过指定不同的哈希器来切换到另一个函数。哈希器是一种实现BuildHasher
特征的类型。我们将在第 10 章中讨论特质以及如何实现它们。您不一定需要从头开始实现自己的哈希器; crates.ioignore拥有其他 Rust 用户共享的库,这些库提供了实现许多常见哈希算法的哈希器。
Summary 概括
Vectors, strings, and hash maps will provide a large amount of functionality
necessary in programs when you need to store, access, and modify data. Here are
some exercises you should now be equipped to solve:
当您需要存储、访问和修改数据时,向量、字符串和哈希映射将提供程序中所需的大量功能。以下是您现在应该能够解决的一些练习:
- Given a list of integers, use a vector and return the median (when sorted,
the value in the middle position) and mode (the value that occurs most
often; a hash map will be helpful here) of the list.
给定一个整数列表,使用向量并返回列表的中位数(排序后,中间位置的值)和众数(最常出现的值;哈希映射在这里会很有帮助)。 - Convert strings to pig latin. The first consonant of each word is moved to
the end of the word and ay is added, so first becomes irst-fay. Words
that start with a vowel have hay added to the end instead (apple becomes
apple-hay). Keep in mind the details about UTF-8 encoding!
将字符串转换为 Pig Latin。每个单词的第一个辅音被移到单词的末尾并添加ay ,因此first变为irst-fay 。以元音开头的单词会将hay添加到末尾( apple变为apple-hay )。请记住有关 UTF-8 编码的详细信息! - Using a hash map and vectors, create a text interface to allow a user to add
employee names to a department in a company; for example, “Add Sally to
Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all
people in a department or all people in the company by department, sorted
alphabetically.
使用哈希映射和向量,创建一个文本界面,允许用户将员工姓名添加到公司的某个部门;例如,“将莎莉添加到工程部门”或“将阿米尔添加到销售部门”。然后让用户检索一个部门中所有人员或按部门按字母顺序排序的公司中所有人员的列表。
The standard library API documentation describes methods that vectors, strings,
and hash maps have that will be helpful for these exercises!
标准库 API 文档描述了向量、字符串和哈希映射所具有的方法,这些方法对这些练习很有帮助!
We’re getting into more complex programs in which operations can fail, so it’s
a perfect time to discuss error handling. We’ll do that next!
我们正在研究更复杂的程序,其中操作可能会失败,因此现在是讨论错误处理的最佳时机。我们接下来就这样做!
Error Handling 错误处理
Errors are a fact of life in software, so Rust has a number of features for
handling situations in which something goes wrong. In many cases, Rust requires
you to acknowledge the possibility of an error and take some action before your
code will compile. This requirement makes your program more robust by ensuring
that you’ll discover errors and handle them appropriately before you’ve
deployed your code to production!
错误是软件中不可避免的事实,因此 Rust 有许多功能可以处理出现问题的情况。在许多情况下,Rust 要求您承认错误的可能性并在代码编译之前采取一些操作。此要求确保您在将代码部署到生产环境之前发现错误并适当处理它们,从而使您的程序更加健壮!
Rust groups errors into two major categories: recoverable and unrecoverable
errors. For a recoverable error, such as a file not found error, we most
likely just want to report the problem to the user and retry the operation.
Unrecoverable errors are always symptoms of bugs, such as trying to access a
location beyond the end of an array, and so we want to immediately stop the
program.
Rust 将错误分为两大类:可恢复错误和不可恢复错误。对于可恢复的错误,例如找不到文件错误,我们很可能只想向用户报告问题并重试操作。不可恢复的错误始终是错误的症状,例如尝试访问超出数组末尾的位置,因此我们希望立即停止程序。
Most languages don’t distinguish between these two kinds of errors and handle
both in the same way, using mechanisms such as exceptions. Rust doesn’t have
exceptions. Instead, it has the type Result<T, E>
for recoverable errors and
the panic!
macro that stops execution when the program encounters an
unrecoverable error. This chapter covers calling panic!
first and then talks
about returning Result<T, E>
values. Additionally, we’ll explore
considerations when deciding whether to try to recover from an error or to stop
execution.
大多数语言不区分这两种错误,并使用异常等机制以相同的方式处理这两种错误。 Rust 也不例外。相反,它的类型为Result<T, E>
表示可恢复错误和panic!
当程序遇到不可恢复的错误时停止执行的宏。本章介绍了调用panic!
先讲返回Result<T, E>
值。此外,我们将探讨在决定是尝试从错误中恢复还是停止执行时的注意事项。
Unrecoverable Errors with panic!
不可恢复的错误并伴有panic!
Sometimes bad things happen in your code, and there’s nothing you can do about
it. In these cases, Rust has the panic!
macro. There are two ways to cause a
panic in practice: by taking an action that causes our code to panic (such as
accessing an array past the end) or by explicitly calling the panic!
macro.
In both cases, we cause a panic in our program. By default, these panics will
print a failure message, unwind, clean up the stack, and quit. Via an
environment variable, you can also have Rust display the call stack when a
panic occurs to make it easier to track down the source of the panic.
有时你的代码中会发生不好的事情,而你却无能为力。在这些情况下,Rust 就会panic!
宏。在实践中,有两种方法会导致恐慌:采取导致代码恐慌的操作(例如访问超出末尾的数组)或显式调用panic!
宏。在这两种情况下,我们都会在程序中引起恐慌。默认情况下,这些恐慌将打印一条失败消息、展开、清理堆栈并退出。通过环境变量,您还可以让 Rust 在发生恐慌时显示调用堆栈,以便更轻松地追踪恐慌的来源。
Unwinding the Stack or Aborting in Response to a Panic
展开堆栈或中止以响应紧急情况
By default, when a panic occurs the program starts unwinding, which means
Rust walks back up the stack and cleans up the data from each function it
encounters. However, walking back and cleaning up is a lot of work. Rust,
therefore, allows you to choose the alternative of immediately aborting,
which ends the program without cleaning up.
默认情况下,当发生恐慌时,程序开始展开,这意味着 Rust 会回溯堆栈并清理它遇到的每个函数中的数据。然而,走回来清理工作量很大。因此,Rust 允许您选择立即中止的替代方案,这会结束程序而不进行清理。
Memory that the program was using will then need to be cleaned up by the
operating system. If in your project you need to make the resultant binary as
small as possible, you can switch from unwinding to aborting upon a panic by
adding panic = 'abort'
to the appropriate [profile]
sections in your
Cargo.toml file. For example, if you want to abort on panic in release mode,
add this:
然后,操作系统需要清理程序正在使用的内存。如果在您的项目中,您需要使生成的二进制文件尽可能小,您可以通过将panic = 'abort'
添加到Cargo.toml文件中相应的[profile]
部分,从展开切换到中止。例如,如果您想在发布模式下发生恐慌时中止,请添加以下内容:
[profile.release]
panic = 'abort'
Let’s try calling panic!
in a simple program:
让我们尝试调用panic!
在一个简单的程序中:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
panic!("crash and burn");
}
When you run the program, you’ll see something like this:
当你运行该程序时,你会看到类似这样的内容:
$ 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
The call to panic!
causes the error message contained in the last two lines.
The first line shows our panic message and the place in our source code where
the panic occurred: src/main.rs:2:5 indicates that it’s the second line,
fifth character of our src/main.rs file.
呼吁panic!
导致最后两行中包含错误消息。第一行显示我们的恐慌消息以及源代码中发生恐慌的位置: src/main.rs:2:5表示它是src/main.rs文件的第二行、第五个字符。
In this case, the line indicated is part of our code, and if we go to that
line, we see the panic!
macro call. In other cases, the panic!
call might
be in code that our code calls, and the filename and line number reported by
the error message will be someone else’s code where the panic!
macro is
called, not the line of our code that eventually led to the panic!
call.
在这种情况下,指示的行是我们代码的一部分,如果我们转到该行,我们会看到panic!
宏调用。在其他情况下, panic!
call 可能是我们的代码调用的代码,而错误信息报告的文件名和行号将是别人的代码,这里就panic!
调用了宏,而不是最终导致panic!
称呼。
We can use the backtrace of the functions the panic!
call came from to figure
out the part of our code that is causing the problem. To understand how to use
a panic!
backtrace, let’s look at another example and see what it’s like when
a panic!
call comes from a library because of a bug in our code instead of
from our code calling the macro directly. Listing 9-1 has some code that
attempts to access an index in a vector beyond the range of valid indexes.
我们可以使用函数的回溯来panic!
调用是为了找出导致问题的代码部分。了解如何使用panic!
backtrace,我们再看一个例子,看看发生panic!
由于代码中的错误,调用来自库,而不是直接调用宏的代码。清单 9-1 有一些代码尝试访问向量中超出有效索引范围的索引。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let v = vec![1, 2, 3];
v[99];
}
Here, we’re attempting to access the 100th element of our vector (which is at
index 99 because indexing starts at zero), but the vector has only three
elements. In this situation, Rust will panic. Using []
is supposed to return
an element, but if you pass an invalid index, there’s no element that Rust
could return here that would be correct.
在这里,我们尝试访问向量的第 100 个元素(位于索引 99,因为索引从零开始),但该向量只有三个元素。在这种情况下,Rust 会恐慌。使用[]
应该返回一个元素,但是如果你传递一个无效的索引,Rust 就不会在这里返回正确的元素。
In C, attempting to read beyond the end of a data structure is undefined
behavior. You might get whatever is at the location in memory that would
correspond to that element in the data structure, even though the memory
doesn’t belong to that structure. This is called a buffer overread and can
lead to security vulnerabilities if an attacker is able to manipulate the index
in such a way as to read data they shouldn’t be allowed to that is stored after
the data structure.
在 C 中,尝试读取超出数据结构末尾的内容是未定义的行为。您可能会获得内存中与数据结构中的该元素对应的位置的任何内容,即使内存不属于该结构。这称为缓冲区过度读取,如果攻击者能够以某种方式操纵索引以读取他们不应该被允许存储在数据结构之后的数据,则可能会导致安全漏洞。
To protect your program from this sort of vulnerability, if you try to read an
element at an index that doesn’t exist, Rust will stop execution and refuse to
continue. Let’s try it and see:
为了保护您的程序免受此类漏洞的影响,如果您尝试读取不存在的索引处的元素,Rust 将停止执行并拒绝继续。让我们尝试一下看看:
$ 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
This error points at line 4 of our main.rs where we attempt to access index
99
of the vector in v
.
此错误指向main.rs的第 4 行,我们在其中尝试访问v
中向量的索引99
。
The note:
line tells us that we can set the RUST_BACKTRACE
environment
variable to get a backtrace of exactly what happened to cause the error. A
backtrace is a list of all the functions that have been called to get to this
point. Backtraces in Rust work as they do in other languages: the key to
reading the backtrace is to start from the top and read until you see files you
wrote. That’s the spot where the problem originated. The lines above that spot
are code that your code has called; the lines below are code that called your
code. These before-and-after lines might include core Rust code, standard
library code, or crates that you’re using. Let’s try getting a backtrace by
setting the RUST_BACKTRACE
environment variable to any value except 0
.
Listing 9-2 shows output similar to what you’ll see.note:
行告诉我们可以设置RUST_BACKTRACE
环境变量来获取导致错误的确切原因的回溯。回溯是为达到这一点而调用的所有函数的列表。 Rust 中的回溯就像在其他语言中一样工作:读取回溯的关键是从顶部开始读取,直到看到您编写的文件。这就是问题的根源。该点上方的行是您的代码调用的代码;下面的行是调用您的代码的代码。这些前后行可能包括核心 Rust 代码、标准库代码或您正在使用的 crate。让我们尝试通过将RUST_BACKTRACE
环境变量设置为除0
之外的任何值来获取回溯。清单 9-2 显示的输出与您将看到的类似。
$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at src/main.rs:4:6:
index out of bounds: the len is 3 but the index is 99
stack backtrace:
0: rust_begin_unwind
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/std/src/panicking.rs:645:5
1: core::panicking::panic_fmt
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/panicking.rs:72:14
2: core::panicking::panic_bounds_check
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/panicking.rs:208:5
3: <usize as core::slice::index::SliceIndex<[T]>>::index
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/slice/index.rs:255:10
4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/slice/index.rs:18:9
5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/alloc/src/vec/mod.rs:2770:9
6: panic::main
at ./src/main.rs:4:6
7: core::ops::function::FnOnce::call_once
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/ops/function.rs:250:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
That’s a lot of output! The exact output you see might be different depending
on your operating system and Rust version. In order to get backtraces with this
information, debug symbols must be enabled. Debug symbols are enabled by
default when using cargo build
or cargo run
without the --release
flag,
as we have here.
这输出量真大啊!您看到的确切输出可能会有所不同,具体取决于您的操作系统和 Rust 版本。为了获得包含此信息的回溯,必须启用调试符号。当使用没有--release
标志的cargo build
或cargo run
时,默认启用调试符号,就像我们在这里一样。
In the output in Listing 9-2, line 6 of the backtrace points to the line in our
project that’s causing the problem: line 4 of src/main.rs. If we don’t want
our program to panic, we should start our investigation at the location pointed
to by the first line mentioning a file we wrote. In Listing 9-1, where we
deliberately wrote code that would panic, the way to fix the panic is to not
request an element beyond the range of the vector indexes. When your code
panics in the future, you’ll need to figure out what action the code is taking
with what values to cause the panic and what the code should do instead.
在清单 9-2 的输出中,回溯的第 6 行指向我们项目中导致问题的行: src/main.rs的第 4 行。如果我们不希望我们的程序出现恐慌,我们应该从第一行提到我们编写的文件所指向的位置开始我们的调查。在清单 9-1 中,我们故意编写了会发生恐慌的代码,解决恐慌的方法是不请求超出向量索引范围的元素。当您的代码将来发生恐慌时,您需要弄清楚代码正在采取什么操作以及哪些值会导致恐慌,以及代码应该做什么。
We’ll come back to panic!
and when we should and should not use panic!
to
handle error conditions in the “To panic!
or Not to
panic!
” section later in this
chapter. Next, we’ll look at how to recover from an error using Result
.
我们会再次陷入panic!
以及什么时候我们应该和不应该使用panic!
处理“ panic!
或者不要panic!
”忽略本章后面的部分。接下来,我们将了解如何使用Result
从错误中恢复。
Recoverable Errors with Result
可恢复的错误及其Result
Most errors aren’t serious enough to require the program to stop entirely.
Sometimes when a function fails it’s for a reason that you can easily interpret
and respond to. For example, if you try to open a file and that operation fails
because the file doesn’t exist, you might want to create the file instead of
terminating the process.
大多数错误并没有严重到需要程序完全停止的程度。有时,当某个功能失败时,其原因是您可以轻松解释和响应的。例如,如果您尝试打开一个文件,但由于该文件不存在而导致该操作失败,您可能需要创建该文件而不是终止该进程。
Recall from “Handling Potential Failure with Result
” in Chapter 2 that the Result
enum is defined as having two
variants, Ok
and Err
, as follows:
回想一下第 2 章中的“用Result
处理潜在失败”, Result
枚举被定义为具有两个变体Ok
和Err
,如下所示:
The T
and E
are generic type parameters: we’ll discuss generics in more
detail in Chapter 10. What you need to know right now is that T
represents
the type of the value that will be returned in a success case within the Ok
variant, and E
represents the type of the error that will be returned in a
failure case within the Err
variant. Because Result
has these generic type
parameters, we can use the Result
type and the functions defined on it in
many different situations where the success value and error value we want to
return may differ.T
和E
是泛型类型参数:我们将在第 10 章中更详细地讨论泛型。您现在需要知道的是T
表示Ok
变体中成功案例中将返回的值的类型, E
表示Err
变体中失败情况下将返回的错误类型。由于Result
具有这些泛型类型参数,因此我们可以在许多不同的情况下使用Result
类型及其定义的函数,在这些情况下,我们想要返回的成功值和错误值可能不同。
Let’s call a function that returns a Result
value because the function could
fail. In Listing 9-3 we try to open a file.
让我们调用一个返回Result
值的函数,因为该函数可能会失败。在清单 9-3 中,我们尝试打开一个文件。
Filename: src/main.rs 文件名:src/main.rs
use std::fs::File;
fn main() {
let greeting_file_result = File::open("hello.txt");
}
The return type of File::open
is a Result<T, E>
. The generic parameter T
has been filled in by the implementation of File::open
with the type of the
success value, std::fs::File
, which is a file handle. The type of E
used in
the error value is std::io::Error
. This return type means the call to
File::open
might succeed and return a file handle that we can read from or
write to. The function call also might fail: for example, the file might not
exist, or we might not have permission to access the file. The File::open
function needs to have a way to tell us whether it succeeded or failed and at
the same time give us either the file handle or error information. This
information is exactly what the Result
enum conveys.File::open
的返回类型是Result<T, E>
。通用参数T
已由File::open
实现填充为成功值std::fs::File
类型,它是一个文件句柄。错误值中使用的E
类型是std::io::Error
。此返回类型意味着对File::open
调用可能会成功并返回一个我们可以读取或写入的文件句柄。函数调用也可能失败:例如,文件可能不存在,或者我们可能没有访问该文件的权限。 File::open
函数需要有一种方法来告诉我们它是成功还是失败,同时为我们提供文件句柄或错误信息。此信息正是Result
枚举所传达的信息。
In the case where File::open
succeeds, the value in the variable
greeting_file_result
will be an instance of Ok
that contains a file handle.
In the case where it fails, the value in greeting_file_result
will be an
instance of Err
that contains more information about the kind of error that
occurred.
如果File::open
成功,变量greeting_file_result
中的值将是包含文件句柄的Ok
实例。如果失败, greeting_file_result
中的值将是Err
的实例,其中包含有关所发生错误类型的更多信息。
We need to add to the code in Listing 9-3 to take different actions depending
on the value File::open
returns. Listing 9-4 shows one way to handle the
Result
using a basic tool, the match
expression that we discussed in
Chapter 6.
我们需要添加到清单 9-3 中的代码,以根据File::open
返回的值采取不同的操作。清单 9-4 显示了使用基本工具(我们在第 6 章中讨论的match
表达式)处理Result
一种方法。
Filename: src/main.rs 文件名:src/main.rs
use std::fs::File;
fn main() {
let greeting_file_result = File::open("hello.txt");
let greeting_file = match greeting_file_result {
Ok(file) => file,
Err(error) => panic!("Problem opening the file: {error:?}"),
};
}
Note that, like the Option
enum, the Result
enum and its variants have been
brought into scope by the prelude, so we don’t need to specify Result::
before the Ok
and Err
variants in the match
arms.
请注意,与Option
枚举一样, Result
枚举及其变体已被 prelude 纳入范围,因此我们不需要在match
臂中的Ok
和Err
变体之前指定Result::
When the result is Ok
, this code will return the inner file
value out of
the Ok
variant, and we then assign that file handle value to the variable
greeting_file
. After the match
, we can use the file handle for reading or
writing.
当结果为Ok
时,此代码将从Ok
变体中返回内部file
值,然后我们将该文件句柄值分配给变量greeting_file
。 match
后,我们可以使用文件句柄进行读取或写入。
The other arm of the match
handles the case where we get an Err
value from
File::open
. In this example, we’ve chosen to call the panic!
macro. If
there’s no file named hello.txt in our current directory and we run this
code, we’ll see the following output from the panic!
macro:match
的另一部分处理我们从File::open
获取Err
值的情况。在此示例中,我们选择调用panic!
宏。如果当前目录中没有名为hello.txt的文件,并且运行此代码,我们将看到panic!
宏:
$ 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
As usual, this output tells us exactly what has gone wrong.
像往常一样,这个输出准确地告诉我们出了什么问题。
Matching on Different Errors
匹配不同的错误
The code in Listing 9-4 will panic!
no matter why File::open
failed.
However, we want to take different actions for different failure reasons. If
File::open
failed because the file doesn’t exist, we want to create the file
and return the handle to the new file. If File::open
failed for any other
reason—for example, because we didn’t have permission to open the file—we still
want the code to panic!
in the same way it did in Listing 9-4. For this, we
add an inner match
expression, shown in Listing 9-5.
清单 9-4 中的代码将会出现panic!
不管为什么File::open
失败。然而,我们希望针对不同的失败原因采取不同的行动。如果File::open
由于文件不存在而失败,我们要创建该文件并将句柄返回到新文件。如果File::open
由于任何其他原因失败(例如,因为我们没有打开文件的权限),我们仍然希望代码出现panic!
与清单 9-4 中的操作相同。为此,我们添加一个内部match
表达式,如清单 9-5 所示。
Filename: src/main.rs 文件名:src/main.rs
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) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Problem creating the file: {e:?}"),
},
other_error => {
panic!("Problem opening the file: {other_error:?}");
}
},
};
}
The type of the value that File::open
returns inside the Err
variant is
io::Error
, which is a struct provided by the standard library. This struct
has a method kind
that we can call to get an io::ErrorKind
value. The enum
io::ErrorKind
is provided by the standard library and has variants
representing the different kinds of errors that might result from an io
operation. The variant we want to use is ErrorKind::NotFound
, which indicates
the file we’re trying to open doesn’t exist yet. So we match on
greeting_file_result
, but we also have an inner match on error.kind()
.File::open
在Err
变体中返回的值的类型是io::Error
,它是标准库提供的结构体。这个结构体有一个方法kind
,我们可以调用它来获取io::ErrorKind
值。枚举io::ErrorKind
由标准库提供,并具有表示io
操作可能导致的不同类型错误的变体。我们要使用的变体是ErrorKind::NotFound
,它表示我们尝试打开的文件尚不存在。所以我们在greeting_file_result
上进行匹配,但我们也在error.kind()
上进行了内部匹配。
The condition we want to check in the inner match is whether the value returned
by error.kind()
is the NotFound
variant of the ErrorKind
enum. If it is,
we try to create the file with File::create
. However, because File::create
could also fail, we need a second arm in the inner match
expression. When the
file can’t be created, a different error message is printed. The second arm of
the outer match
stays the same, so the program panics on any error besides
the missing file error.
我们要在内部匹配中检查的条件是error.kind()
返回的值是否是ErrorKind
枚举的NotFound
变体。如果是,我们尝试使用File::create
文件。但是,由于File::create
也可能失败,因此我们需要在内部match
表达式中添加第二个分支。当无法创建文件时,会打印不同的错误消息。外部match
的第二个分支保持不变,因此除了丢失文件错误之外,程序会因任何错误而发生恐慌。
Alternatives to Using match
with Result<T, E>
使用结果match
的替代方法Result<T, E>
That’s a lot of match
! The match
expression is very useful but also very
much a primitive. In Chapter 13, you’ll learn about closures, which are used
with many of the methods defined on Result<T, E>
. These methods can be more
concise than using match
when handling Result<T, E>
values in your code.
这是很多match
! match
表达式非常有用,但也非常原始。在第 13 章中,您将了解闭包,它与Result<T, E>
上定义的许多方法一起使用。在处理代码中的Result<T, E>
值时,这些方法比使用match
更简洁。
For example, here’s another way to write the same logic as shown in Listing
9-5, this time using closures and the unwrap_or_else
method:
例如,下面是编写与清单 9-5 所示相同逻辑的另一种方法,这次使用闭包和unwrap_or_else
方法:
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:?}");
}
});
}
Although this code has the same behavior as Listing 9-5, it doesn’t contain
any match
expressions and is cleaner to read. Come back to this example
after you’ve read Chapter 13, and look up the unwrap_or_else
method in the
standard library documentation. Many more of these methods can clean up huge
nested match
expressions when you’re dealing with errors.
尽管此代码与清单 9-5 具有相同的行为,但它不包含任何match
表达式,并且读起来更清晰。读完第 13 章后,回到这个示例,并在标准库文档中查找unwrap_or_else
方法。当您处理错误时,更多这些方法可以清理巨大的嵌套match
表达式。
Shortcuts for Panic on Error: unwrap
and expect
Panic on Error 的快捷方式: unwrap
并expect
Using match
works well enough, but it can be a bit verbose and doesn’t always
communicate intent well. The Result<T, E>
type has many helper methods
defined on it to do various, more specific tasks. The unwrap
method is a
shortcut method implemented just like the match
expression we wrote in
Listing 9-4. If the Result
value is the Ok
variant, unwrap
will return
the value inside the Ok
. If the Result
is the Err
variant, unwrap
will
call the panic!
macro for us. Here is an example of unwrap
in action:
使用match
效果很好,但它可能有点冗长,并且并不总是能很好地传达意图。 Result<T, E>
类型定义了许多辅助方法来执行各种更具体的任务。 unwrap
方法是一个快捷方法,其实现就像我们在清单 9-4 中编写的match
表达式一样。如果Result
值是Ok
变体,则unwrap
将返回Ok
内的值。如果Result
是Err
变体, unwrap
将引发panic!
对我们来说宏。以下是unwrap
操作的示例:
Filename: src/main.rs 文件名:src/main.rs
use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt").unwrap();
}
If we run this code without a hello.txt file, we’ll see an error message from
the panic!
call that the unwrap
method makes:
如果我们在没有hello.txt文件的情况下运行此代码,我们将看到一条来自panic!
调用unwrap
方法进行的操作:
thread 'main' panicked at src/main.rs:4:49:
called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }
Similarly, the expect
method lets us also choose the panic!
error message.
Using expect
instead of unwrap
and providing good error messages can convey
your intent and make tracking down the source of a panic easier. The syntax of
expect
looks like this:
同样, expect
方法也让我们选择panic!
错误信息。使用expect
而不是unwrap
并提供良好的错误消息可以传达您的意图并使追踪恐慌的根源变得更加容易。 expect
的语法如下所示:
Filename: src/main.rs 文件名:src/main.rs
use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt")
.expect("hello.txt should be included in this project");
}
We use expect
in the same way as unwrap
: to return the file handle or call
the panic!
macro. The error message used by expect
in its call to panic!
will be the parameter that we pass to expect
, rather than the default
panic!
message that unwrap
uses. Here’s what it looks like:
我们使用expect
方式与unwrap
相同:返回文件句柄或调用panic!
宏。 expect
在调用panic!
将是我们传递给expect
的参数,而不是默认的panic!
unwrap
使用的消息。它看起来是这样的:
thread 'main' panicked at src/main.rs:5:10:
hello.txt should be included in this project: Os { code: 2, kind: NotFound, message: "No such file or directory" }
In production-quality code, most Rustaceans choose expect
rather than
unwrap
and give more context about why the operation is expected to always
succeed. That way, if your assumptions are ever proven wrong, you have more
information to use in debugging.
在生产质量代码中,大多数 Rustaceans 选择expect
而不是unwrap
并提供更多关于为什么操作总是成功的背景信息。这样,如果您的假设被证明是错误的,您就有更多信息可用于调试。
Propagating Errors 传播错误
When a function’s implementation calls something that might fail, instead of
handling the error within the function itself you can return the error to the
calling code so that it can decide what to do. This is known as propagating
the error and gives more control to the calling code, where there might be more
information or logic that dictates how the error should be handled than what
you have available in the context of your code.
当函数的实现调用可能失败的内容时,您可以将错误返回给调用代码,以便它可以决定要做什么,而不是在函数本身内处理错误。这称为传播错误,并为调用代码提供更多控制,其中可能有比代码上下文中可用的信息或逻辑更多的信息或逻辑来指示应如何处理错误。
For example, Listing 9-6 shows a function that reads a username from a file. If
the file doesn’t exist or can’t be read, this function will return those errors
to the code that called the function.
例如,清单 9-6 显示了一个从文件中读取用户名的函数。如果文件不存在或无法读取,该函数会将这些错误返回给调用该函数的代码。
Filename: src/main.rs 文件名:src/main.rs
This function can be written in a much shorter way, but we’re going to start by
doing a lot of it manually in order to explore error handling; at the end,
we’ll show the shorter way. Let’s look at the return type of the function
first: Result<String, io::Error>
. This means the function is returning a
value of the type Result<T, E>
, where the generic parameter T
has been
filled in with the concrete type String
and the generic type E
has been
filled in with the concrete type io::Error
.
这个函数可以用更短的方式编写,但我们将首先手动执行大量操作,以探索错误处理;最后,我们将展示更短的方法。我们先看一下函数的返回类型: Result<String, io::Error>
。这意味着该函数返回类型为Result<T, E>
的值,其中通用参数T
已使用具体类型String
填充,通用类型E
已使用具体类型io::Error
。
If this function succeeds without any problems, the code that calls this
function will receive an Ok
value that holds a String
—the username
that
this function read from the file. If this function encounters any problems, the
calling code will receive an Err
value that holds an instance of io::Error
that contains more information about what the problems were. We chose
io::Error
as the return type of this function because that happens to be the
type of the error value returned from both of the operations we’re calling in
this function’s body that might fail: the File::open
function and the
read_to_string
method.
如果此函数成功且没有任何问题,则调用此函数的代码将收到一个包含String
的Ok
值,即此函数从文件中读取的username
。如果此函数遇到任何问题,调用代码将收到一个Err
值,该值包含io::Error
的实例,其中包含有关问题所在的更多信息。我们选择io::Error
作为该函数的返回类型,因为它恰好是我们在此函数体内调用的两个可能失败的操作返回的错误值的类型: File::open
函数和read_to_string
方法。
The body of the function starts by calling the File::open
function. Then we
handle the Result
value with a match
similar to the match
in Listing 9-4.
If File::open
succeeds, the file handle in the pattern variable file
becomes the value in the mutable variable username_file
and the function
continues. In the Err
case, instead of calling panic!
, we use the return
keyword to return early out of the function entirely and pass the error value
from File::open
, now in the pattern variable e
, back to the calling code as
this function’s error value.
函数体首先调用File::open
函数。然后我们使用类似于清单 9-4 中match
match
来处理Result
值。如果File::open
成功,模式变量file
中的文件句柄将成为可变变量username_file
中的值,并且函数继续。在Err
情况下,不要调用panic!
,我们使用return
关键字完全从函数中返回,并将来自File::open
错误值(现在位于模式变量e
中)传递回调用代码作为该函数的错误值。
So, if we have a file handle in username_file
, the function then creates a
new String
in variable username
and calls the read_to_string
method on
the file handle in username_file
to read the contents of the file into
username
. The read_to_string
method also returns a Result
because it
might fail, even though File::open
succeeded. So we need another match
to
handle that Result
: if read_to_string
succeeds, then our function has
succeeded, and we return the username from the file that’s now in username
wrapped in an Ok
. If read_to_string
fails, we return the error value in the
same way that we returned the error value in the match
that handled the
return value of File::open
. However, we don’t need to explicitly say
return
, because this is the last expression in the function.
因此,如果我们在username_file
中有一个文件句柄,则该函数会在变量username
中创建一个新String
,并在username_file
中的文件句柄上调用read_to_string
方法,以将文件内容读取到username
中。 read_to_string
方法还会返回Result
因为即使File::open
成功,它也可能会失败。因此,我们需要另一个match
来处理该Result
:如果read_to_string
成功,那么我们的函数就成功了,并且我们从文件中返回用户名,该文件现在位于用Ok
包装的username
中。如果read_to_string
失败,我们将按照处理File::open
返回值的match
中返回错误值的方式返回错误值。但是,我们不需要显式地说return
,因为这是函数中的最后一个表达式。
The code that calls this code will then handle getting either an Ok
value
that contains a username or an Err
value that contains an io::Error
. It’s
up to the calling code to decide what to do with those values. If the calling
code gets an Err
value, it could call panic!
and crash the program, use a
default username, or look up the username from somewhere other than a file, for
example. We don’t have enough information on what the calling code is actually
trying to do, so we propagate all the success or error information upward for
it to handle appropriately.
然后,调用此代码的代码将处理获取包含用户名的Ok
值或包含io::Error
Err
值。由调用代码决定如何处理这些值。如果调用代码获得Err
值,它可能会调用panic!
例如,使程序崩溃,使用默认用户名,或者从文件以外的其他地方查找用户名。我们没有足够的信息来了解调用代码实际尝试执行的操作,因此我们向上传播所有成功或错误信息,以便其正确处理。
This pattern of propagating errors is so common in Rust that Rust provides the
question mark operator ?
to make this easier.
这种传播错误的模式在 Rust 中非常常见,以至于 Rust 提供了问号运算符?
让这变得更容易。
A Shortcut for Propagating Errors: the ?
Operator
传播错误的捷径: ?
操作员
Listing 9-7 shows an implementation of read_username_from_file
that has the
same functionality as in Listing 9-6, but this implementation uses the ?
operator.
清单 9-7 显示了read_username_from_file
的实现,其功能与清单 9-6 相同,但该实现使用?
操作员。
Filename: src/main.rs 文件名:src/main.rs
The ?
placed after a Result
value is defined to work in almost the same way
as the match
expressions we defined to handle the Result
values in Listing
9-6. If the value of the Result
is an Ok
, the value inside the Ok
will
get returned from this expression, and the program will continue. If the value
is an Err
, the Err
will be returned from the whole function as if we had
used the return
keyword so the error value gets propagated to the calling
code.
这?
放置在定义Result
值之后,其工作方式与我们定义的用于处理清单 9-6 中的Result
值的match
表达式几乎相同。如果Result
的值为Ok
,则将从该表达式返回Ok
内的值,并且程序将继续。如果该值为Err
,则Err
将从整个函数返回,就像我们使用了return
关键字一样,因此错误值会传播到调用代码。
There is a difference between what the match
expression from Listing 9-6 does
and what the ?
operator does: error values that have the ?
operator called
on them go through the from
function, defined in the From
trait in the
standard library, which is used to convert values from one type into another.
When the ?
operator calls the from
function, the error type received is
converted into the error type defined in the return type of the current
function. This is useful when a function returns one error type to represent
all the ways a function might fail, even if parts might fail for many different
reasons.
清单 9-6 中的match
表达式的作用与?
的作用是有区别的。运算符的作用:具有?
错误值对它们调用的运算符会经过标准库中From
特征中定义的from
函数,该函数用于将值从一种类型转换为另一种类型。什么时候?
运算符调用from
函数,将接收到的错误类型转换为当前函数的返回类型中定义的错误类型。当函数返回一种错误类型来表示函数可能失败的所有方式时(即使某些部分可能由于多种不同原因而失败),这非常有用。
For example, we could change the read_username_from_file
function in Listing
9-7 to return a custom error type named OurError
that we define. If we also
define impl From<io::Error> for OurError
to construct an instance of
OurError
from an io::Error
, then the ?
operator calls in the body of
read_username_from_file
will call from
and convert the error types without
needing to add any more code to the function.
例如,我们可以更改清单 9-7 中的read_username_from_file
函数,以返回我们定义的名为OurError
自定义错误类型。如果我们还impl From<io::Error> for OurError
从io::Error
构造OurError
的实例,那么?
read_username_from_file
主体中的运算符调用将调用from
并转换错误类型,而无需向函数添加任何更多代码。
In the context of Listing 9-7, the ?
at the end of the File::open
call will
return the value inside an Ok
to the variable username_file
. If an error
occurs, the ?
operator will return early out of the whole function and give
any Err
value to the calling code. The same thing applies to the ?
at the
end of the read_to_string
call.
在清单 9-7 的上下文中, ?
File::open
调用结束时会将Ok
内的值返回给变量username_file
。如果发生错误,则?
运算符将从整个函数中提前返回,并向调用代码提供任何Err
值。同样的事情也适用于?
在read_to_string
调用结束时。
The ?
operator eliminates a lot of boilerplate and makes this function’s
implementation simpler. We could even shorten this code further by chaining
method calls immediately after the ?
, as shown in Listing 9-8.
这?
运算符消除了大量样板代码,并使该函数的实现更加简单。我们甚至可以通过在?
之后立即链接方法调用来进一步缩短此代码。 ,如清单 9-8 所示。
Filename: src/main.rs 文件名:src/main.rs
We’ve moved the creation of the new String
in username
to the beginning of
the function; that part hasn’t changed. Instead of creating a variable
username_file
, we’ve chained the call to read_to_string
directly onto the
result of File::open("hello.txt")?
. We still have a ?
at the end of the
read_to_string
call, and we still return an Ok
value containing username
when both File::open
and read_to_string
succeed rather than returning
errors. The functionality is again the same as in Listing 9-6 and Listing 9-7;
this is just a different, more ergonomic way to write it.
我们已将username
中新String
的创建移至函数的开头;那部分没有改变。我们没有创建变量username_file
,而是直接将对read_to_string
的调用链接到File::open("hello.txt")?
的结果上。 。我们还有一个?
在read_to_string
调用结束时,当File::open
和read_to_string
都成功时,我们仍然返回包含username
的Ok
值,而不是返回错误。功能与清单 9-6 和清单 9-7 相同;这只是一种不同的、更符合人体工程学的书写方式。
Listing 9-9 shows a way to make this even shorter using fs::read_to_string
.
清单 9-9 展示了一种使用fs::read_to_string
使其更短的方法。
Filename: src/main.rs 文件名:src/main.rs
Reading a file into a string is a fairly common operation, so the standard
library provides the convenient fs::read_to_string
function that opens the
file, creates a new String
, reads the contents of the file, puts the contents
into that String
, and returns it. Of course, using fs::read_to_string
doesn’t give us the opportunity to explain all the error handling, so we did it
the longer way first.
将文件读入字符串是一个相当常见的操作,因此标准库提供了方便的fs::read_to_string
函数,该函数打开文件,创建一个新的String
,读取文件的内容,将内容放入该String
中,然后返回它。当然,使用fs::read_to_string
并不能让我们有机会解释所有错误处理,因此我们首先采用更长的方式。
Where The ?
Operator Can Be Used
哪里的?
可以使用运算符
The ?
operator can only be used in functions whose return type is compatible
with the value the ?
is used on. This is because the ?
operator is defined
to perform an early return of a value out of the function, in the same manner
as the match
expression we defined in Listing 9-6. In Listing 9-6, the
match
was using a Result
value, and the early return arm returned an
Err(e)
value. The return type of the function has to be a Result
so that
it’s compatible with this return
.
这?
运算符只能用在返回类型与?
值兼容的函数中。用于.这是因为?
运算符被定义为执行从函数中提前返回值的操作,其方式与我们在清单 9-6 中定义的match
表达式相同。在清单 9-6 中, match
使用Result
值,早期返回臂返回Err(e)
值。函数的返回类型必须是Result
,以便与此return
兼容。
In Listing 9-10, let’s look at the error we’ll get if we use the ?
operator
in a main
function with a return type that is incompatible with the type of
the value we use ?
on.
在清单 9-10 中,让我们看一下如果使用?
将会出现的错误。 main
函数中的运算符的返回类型与我们使用的值的类型不兼容?
在。
Filename: src/main.rs 文件名:src/main.rs
use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt")?;
}
This code opens a file, which might fail. The ?
operator follows the Result
value returned by File::open
, but this main
function has the return type of
()
, not Result
. When we compile this code, we get the following error
message:
此代码打开一个文件,这可能会失败。这?
运算符遵循File::open
返回的Result
值,但此main
函数的返回类型为()
而不是Result
。当我们编译这段代码时,我们收到以下错误消息:
$ 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`)
--> 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<Result<Infallible, std::io::Error>>` is not implemented for `()`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `error-handling` (bin "error-handling") due to 1 previous error
This error points out that we’re only allowed to use the ?
operator in a
function that returns Result
, Option
, or another type that implements
FromResidual
.
此错误指出我们只允许使用?
返回Result
、 Option
或实现FromResidual
的其他类型的函数中的运算符。
To fix the error, you have two choices. One choice is to change the return type
of your function to be compatible with the value you’re using the ?
operator
on as long as you have no restrictions preventing that. The other choice is to
use a match
or one of the Result<T, E>
methods to handle the Result<T, E>
in whatever way is appropriate.
要修复该错误,您有两种选择。一种选择是更改函数的返回类型以与您正在使用?
的值兼容。只要您没有任何限制,就可以使用运算符。另一种选择是使用match
或Result<T, E>
方法之一以任何适当的方式处理Result<T, E>
。
The error message also mentioned that ?
can be used with Option<T>
values
as well. As with using ?
on Result
, you can only use ?
on Option
in a
function that returns an Option
. The behavior of the ?
operator when called
on an Option<T>
is similar to its behavior when called on a Result<T, E>
:
if the value is None
, the None
will be returned early from the function at
that point. If the value is Some
, the value inside the Some
is the
resultant value of the expression, and the function continues. Listing 9-11 has
an example of a function that finds the last character of the first line in the
given text.
错误消息还提到了?
也可以与Option<T>
值一起使用。与使用?
在Result
上,你只能使用?
返回Option
的函数中的Option
。的行为?
在Option<T>
上调用时的操作符与在Result<T, E>
上调用时的行为类似:如果值为None
,则None
将在此时从函数中提前返回。如果值为Some
, Some
内的值是表达式的结果值,并且函数继续。清单 9-11 有一个函数示例,该函数查找给定文本中第一行的最后一个字符。
This function returns Option<char>
because it’s possible that there is a
character there, but it’s also possible that there isn’t. This code takes the
text
string slice argument and calls the lines
method on it, which returns
an iterator over the lines in the string. Because this function wants to
examine the first line, it calls next
on the iterator to get the first value
from the iterator. If text
is the empty string, this call to next
will
return None
, in which case we use ?
to stop and return None
from
last_char_of_first_line
. If text
is not the empty string, next
will
return a Some
value containing a string slice of the first line in text
.
此函数返回Option<char>
因为那里可能有一个字符,但也可能没有。此代码采用text
字符串切片参数并对其调用lines
方法,该方法返回字符串中各行的迭代器。因为该函数想要检查第一行,所以它调用迭代器的next
以从迭代器获取第一个值。如果text
是空字符串,则对next
的调用将返回None
,在这种情况下我们使用?
停止并从last_char_of_first_line
返回None
。如果text
不是空字符串, next
将返回一个Some
值,其中包含text
第一行的字符串切片。
The ?
extracts the string slice, and we can call chars
on that string slice
to get an iterator of its characters. We’re interested in the last character in
this first line, so we call last
to return the last item in the iterator.
This is an Option
because it’s possible that the first line is the empty
string; for example, if text
starts with a blank line but has characters on
other lines, as in "\nhi"
. However, if there is a last character on the first
line, it will be returned in the Some
variant. The ?
operator in the middle
gives us a concise way to express this logic, allowing us to implement the
function in one line. If we couldn’t use the ?
operator on Option
, we’d
have to implement this logic using more method calls or a match
expression.
这?
提取字符串切片,我们可以在该字符串切片上调用chars
来获取其字符的迭代器。我们对第一行的最后一个字符感兴趣,因此我们调用last
来返回迭代器中的最后一项。这是一个Option
因为第一行可能是空字符串;例如,如果text
以空行开头,但其他行上有字符,如"\nhi"
。但是,如果第一行有最后一个字符,它将在Some
变体中返回。这?
中间的运算符为我们提供了一种简洁的方式来表达这个逻辑,使我们能够在一行中实现该功能。如果我们不能使用?
Option
上的运算符,我们必须使用更多方法调用或match
表达式来实现此逻辑。
Note that you can use the ?
operator on a Result
in a function that returns
Result
, and you can use the ?
operator on an Option
in a function that
returns Option
, but you can’t mix and match. The ?
operator won’t
automatically convert a Result
to an Option
or vice versa; in those cases,
you can use methods like the ok
method on Result
or the ok_or
method on
Option
to do the conversion explicitly.
请注意,您可以使用?
返回Result
的函数中Result
运算符,您可以使用?
返回Option
的函数中Option
运算符,但不能混合和匹配。这?
运算符不会自动将Result
转换为Option
,反之亦然;在这些情况下,您可以使用Result
上的ok
方法或Option
上的ok_or
方法等方法来显式执行转换。
So far, all the main
functions we’ve used return ()
. The main
function is
special because it’s the entry point and exit point of an executable program,
and there are restrictions on what its return type can be for the program to
behave as expected.
到目前为止,我们使用的所有main
函数都是 return ()
。 main
函数很特殊,因为它是可执行程序的入口点和出口点,并且其返回类型对于程序按预期运行有限制。
Luckily, main
can also return a Result<(), E>
. Listing 9-12 has the code
from Listing 9-10, but we’ve changed the return type of main
to be
Result<(), Box<dyn Error>>
and added a return value Ok(())
to the end. This
code will now compile.
幸运的是, main
还可以返回Result<(), E>
。清单 9-12 包含清单 9-10 中的代码,但我们将main
的返回类型更改为Result<(), Box<dyn Error>>
并添加了一个返回值Ok(())
结束。现在将编译此代码。
Filename: src/main.rs 文件名:src/main.rs
use std::error::Error;
use std::fs::File;
fn main() -> Result<(), Box<dyn Error>> {
let greeting_file = File::open("hello.txt")?;
Ok(())
}
The Box<dyn Error>
type is a trait object, which we’ll talk about in the
“Using Trait Objects that Allow for Values of Different
Types” section in Chapter 17. For now, you can
read Box<dyn Error>
to mean “any kind of error.” Using ?
on a Result
value in a main
function with the error type Box<dyn Error>
is allowed
because it allows any Err
value to be returned early. Even though the body of
this main
function will only ever return errors of type std::io::Error
, by
specifying Box<dyn Error>
, this signature will continue to be correct even if
more code that returns other errors is added to the body of main
.Box<dyn Error>
类型是一个特征对象,我们将在第 17 章的“使用允许不同类型值的特征对象”忽略部分中讨论它。现在,您可以阅读Box<dyn Error>
表示“任何类型的错误”。使用?
允许在错误类型为Box<dyn Error>
main
函数中的Result
值上使用,因为它允许提前返回任何Err
值。即使此main
函数的主体只会返回std::io::Error
类型的错误,但通过指定Box<dyn Error>
,即使添加更多返回其他错误的代码,此签名也将继续正确main
的主体。
When a main
function returns a Result<(), E>
, the executable will exit with
a value of 0
if main
returns Ok(())
and will exit with a nonzero value if
main
returns an Err
value. Executables written in C return integers when
they exit: programs that exit successfully return the integer 0
, and programs
that error return some integer other than 0
. Rust also returns integers from
executables to be compatible with this convention.
当main
函数返回Result<(), E>
时,如果main
返回Ok(())
则可执行文件将以0
值退出;如果main
返回Err
值,则可执行文件将以非零值退出。用 C 编写的可执行文件在退出时返回整数:成功退出的程序返回整数0
,出错的程序返回0
以外的某个整数。 Rust 还从可执行文件返回整数以与此约定兼容。
The main
function may return any types that implement the
std::process::Termination
trait, which contains
a function report
that returns an ExitCode
. Consult the standard library
documentation for more information on implementing the Termination
trait for
your own types.main
函数可以返回任何实现std::process::Termination
特征ignore 的类型,其中包含返回ExitCode
的函数report
。有关为您自己的类型实现Termination
特征的更多信息,请参阅标准库文档。
Now that we’ve discussed the details of calling panic!
or returning Result
,
let’s return to the topic of how to decide which is appropriate to use in which
cases.
现在我们已经讨论了调用panic!
或者返回Result
,让我们回到如何决定哪种情况适合使用的主题。
To panic!
or Not to panic!
panic!
或者不要panic!
So how do you decide when you should call panic!
and when you should return
Result
? When code panics, there’s no way to recover. You could call panic!
for any error situation, whether there’s a possible way to recover or not, but
then you’re making the decision that a situation is unrecoverable on behalf of
the calling code. When you choose to return a Result
value, you give the
calling code options. The calling code could choose to attempt to recover in a
way that’s appropriate for its situation, or it could decide that an Err
value in this case is unrecoverable, so it can call panic!
and turn your
recoverable error into an unrecoverable one. Therefore, returning Result
is a
good default choice when you’re defining a function that might fail.
那么你如何决定何时应该调用panic!
什么时候应该返回Result
?当代码发生混乱时,无法恢复。你可以称之为panic!
对于任何错误情况,无论是否有可能的方法来恢复,但随后您将代表调用代码做出无法恢复的情况的决定。当您选择返回Result
值时,您为调用代码提供了选项。调用代码可以选择尝试以适合其情况的方式进行恢复,或者它可以决定这种情况下的Err
值是不可恢复的,因此它可以调用panic!
并将您的可恢复错误变成不可恢复错误。因此,当您定义可能失败的函数时,返回Result
是一个不错的默认选择。
In situations such as examples, prototype code, and tests, it’s more
appropriate to write code that panics instead of returning a Result
. Let’s
explore why, then discuss situations in which the compiler can’t tell that
failure is impossible, but you as a human can. The chapter will conclude with
some general guidelines on how to decide whether to panic in library code.
在示例、原型代码和测试等情况下,编写发生恐慌的代码比返回Result
更合适。让我们探讨一下原因,然后讨论编译器无法判断失败是不可能的情况,但你作为一个人可以。本章最后将提供一些关于如何决定是否在库代码中出现恐慌的一般准则。
Examples, Prototype Code, and Tests
示例、原型代码和测试
When you’re writing an example to illustrate some concept, also including
robust error-handling code can make the example less clear. In examples, it’s
understood that a call to a method like unwrap
that could panic is meant as a
placeholder for the way you’d want your application to handle errors, which can
differ based on what the rest of your code is doing.
当您编写示例来说明某些概念时,还包含强大的错误处理代码可能会使示例不太清晰。在示例中,可以理解的是,对像unwrap
这样可能会发生恐慌的方法的调用意味着作为您希望应用程序处理错误的方式的占位符,这可能会根据其余代码正在执行的操作而有所不同。
Similarly, the unwrap
and expect
methods are very handy when prototyping,
before you’re ready to decide how to handle errors. They leave clear markers in
your code for when you’re ready to make your program more robust.
同样,在您准备好决定如何处理错误之前, unwrap
和expect
方法在原型设计时非常方便。它们会在您的代码中留下清晰的标记,以便您准备好使您的程序更加健壮。
If a method call fails in a test, you’d want the whole test to fail, even if
that method isn’t the functionality under test. Because panic!
is how a test
is marked as a failure, calling unwrap
or expect
is exactly what should
happen.
如果测试中的方法调用失败,您会希望整个测试失败,即使该方法不是正在测试的功能。因为panic!
是测试被标记为失败的方式,调用unwrap
或expect
正是应该发生的事情。
Cases in Which You Have More Information Than the Compiler
您拥有比编译器更多信息的情况
It would also be appropriate to call unwrap
or expect
when you have some
other logic that ensures the Result
will have an Ok
value, but the logic
isn’t something the compiler understands. You’ll still have a Result
value
that you need to handle: whatever operation you’re calling still has the
possibility of failing in general, even though it’s logically impossible in
your particular situation. If you can ensure by manually inspecting the code
that you’ll never have an Err
variant, it’s perfectly acceptable to call
unwrap
, and even better to document the reason you think you’ll never have an
Err
variant in the expect
text. Here’s an example:
当您有一些其他逻辑确保Result
将具有Ok
值时,调用unwrap
或expect
也是合适的,但编译器无法理解这些逻辑。您仍然需要处理一个Result
值:您调用的任何操作通常仍然有可能失败,即使在您的特定情况下逻辑上这是不可能的。如果您可以通过手动检查代码来确保永远不会出现Err
变体,那么调用unwrap
是完全可以接受的,甚至更好地在expect
文本中记录您认为永远不会出现Err
变体的原因。这是一个例子:
We’re creating an IpAddr
instance by parsing a hardcoded string. We can see
that 127.0.0.1
is a valid IP address, so it’s acceptable to use expect
here. However, having a hardcoded, valid string doesn’t change the return type
of the parse
method: we still get a Result
value, and the compiler will
still make us handle the Result
as if the Err
variant is a possibility
because the compiler isn’t smart enough to see that this string is always a
valid IP address. If the IP address string came from a user rather than being
hardcoded into the program and therefore did have a possibility of failure,
we’d definitely want to handle the Result
in a more robust way instead.
Mentioning the assumption that this IP address is hardcoded will prompt us to
change expect
to better error-handling code if, in the future, we need to get
the IP address from some other source instead.
我们通过解析硬编码字符串来创建IpAddr
实例。我们可以看到127.0.0.1
是一个有效的IP地址,所以这里使用expect
是可以接受的。然而,拥有一个硬编码的、有效的字符串并不会改变parse
方法的返回类型:我们仍然得到一个Result
值,并且编译器仍然会让我们处理Result
,就好像Err
变体是可能的一样,因为编译器不会它足够聪明,可以看出该字符串始终是有效的 IP 地址。如果 IP 地址字符串来自用户而不是硬编码到程序中,因此确实有失败的可能性,我们肯定希望以更稳健的方式处理Result
。如果将来我们需要从其他来源获取 IP 地址,提及此 IP 地址是硬编码的假设将促使我们更改expect
以更好的错误处理代码。
Guidelines for Error Handling
错误处理指南
It’s advisable to have your code panic when it’s possible that your code could
end up in a bad state. In this context, a bad state is when some assumption,
guarantee, contract, or invariant has been broken, such as when invalid values,
contradictory values, or missing values are passed to your code—plus one or
more of the following:
当您的代码可能最终处于错误状态时,建议让您的代码出现恐慌。在这种情况下,坏状态是指某些假设、保证、契约或不变量被破坏,例如当无效值、矛盾值或缺失值传递到代码时,加上以下一项或多项:
- The bad state is something that is unexpected, as opposed to something that
will likely happen occasionally, like a user entering data in the wrong
format.
不良状态是指意外的情况,而不是偶尔发生的情况,例如用户以错误的格式输入数据。 - Your code after this point needs to rely on not being in this bad state,
rather than checking for the problem at every step.
此后您的代码需要依赖于不处于这种糟糕的状态,而不是在每一步都检查问题。 - There’s not a good way to encode this information in the types you use. We’ll
work through an example of what we mean in the “Encoding States and Behavior
as Types” section of Chapter 17.
没有一种好方法可以用您使用的类型来编码这些信息。我们将通过一个例子来解释第 17 章“将状态和行为编码为类型”忽略部分的含义。
If someone calls your code and passes in values that don’t make sense, it’s
best to return an error if you can so the user of the library can decide what
they want to do in that case. However, in cases where continuing could be
insecure or harmful, the best choice might be to call panic!
and alert the
person using your library to the bug in their code so they can fix it during
development. Similarly, panic!
is often appropriate if you’re calling
external code that is out of your control and it returns an invalid state that
you have no way of fixing.
如果有人调用您的代码并传入没有意义的值,则最好返回错误(如果可以),以便库的用户可以决定在这种情况下他们想要做什么。然而,如果继续可能不安全或有害,最好的选择可能是panic!
并提醒使用您库的人注意其代码中的错误,以便他们可以在开发过程中修复它。同样, panic!
如果您调用不受您控制的外部代码并且它返回您无法修复的无效状态,则通常是合适的。
However, when failure is expected, it’s more appropriate to return a Result
than to make a panic!
call. Examples include a parser being given malformed
data or an HTTP request returning a status that indicates you have hit a rate
limit. In these cases, returning a Result
indicates that failure is an
expected possibility that the calling code must decide how to handle.
然而,当预计会失败时,返回Result
比引发panic!
称呼。示例包括向解析器提供格式错误的数据或返回指示已达到速率限制的状态的 HTTP 请求。在这些情况下,返回Result
表明失败是一种预期的可能性,调用代码必须决定如何处理。
When your code performs an operation that could put a user at risk if it’s
called using invalid values, your code should verify the values are valid first
and panic if the values aren’t valid. This is mostly for safety reasons:
attempting to operate on invalid data can expose your code to vulnerabilities.
This is the main reason the standard library will call panic!
if you attempt
an out-of-bounds memory access: trying to access memory that doesn’t belong to
the current data structure is a common security problem. Functions often have
contracts: their behavior is only guaranteed if the inputs meet particular
requirements. Panicking when the contract is violated makes sense because a
contract violation always indicates a caller-side bug, and it’s not a kind of
error you want the calling code to have to explicitly handle. In fact, there’s
no reasonable way for calling code to recover; the calling programmers need
to fix the code. Contracts for a function, especially when a violation will
cause a panic, should be explained in the API documentation for the function.
当您的代码执行的操作如果使用无效值调用时可能会给用户带来风险,您的代码应该首先验证这些值是否有效,如果这些值无效则发生恐慌。这主要是出于安全原因:尝试对无效数据进行操作可能会使您的代码面临漏洞。这是标准库会调用panic!
如果尝试越界内存访问:尝试访问不属于当前数据结构的内存是一个常见的安全问题。函数通常有契约:只有当输入满足特定要求时,它们的行为才能得到保证。当违反合同时出现恐慌是有道理的,因为违反合同总是表明调用方存在错误,并且这不是您希望调用代码必须显式处理的错误。事实上,没有合理的方法来调用代码进行恢复;调用程序员需要修复代码。函数的契约,尤其是当违规会导致恐慌时,应该在函数的 API 文档中进行解释。
However, having lots of error checks in all of your functions would be verbose
and annoying. Fortunately, you can use Rust’s type system (and thus the type
checking done by the compiler) to do many of the checks for you. If your
function has a particular type as a parameter, you can proceed with your code’s
logic knowing that the compiler has already ensured you have a valid value. For
example, if you have a type rather than an Option
, your program expects to
have something rather than nothing. Your code then doesn’t have to handle
two cases for the Some
and None
variants: it will only have one case for
definitely having a value. Code trying to pass nothing to your function won’t
even compile, so your function doesn’t have to check for that case at runtime.
Another example is using an unsigned integer type such as u32
, which ensures
the parameter is never negative.
然而,在所有函数中进行大量错误检查将是冗长且烦人的。幸运的是,您可以使用 Rust 的类型系统(以及编译器完成的类型检查)来为您完成许多检查。如果您的函数具有特定类型作为参数,则您可以继续执行代码逻辑,因为编译器已确保您具有有效值。例如,如果您有一个类型而不是一个Option
,那么您的程序期望有一些东西而不是没有。然后,您的代码不必处理Some
和None
变体的两种情况:它只会有一种肯定具有值的情况。尝试向函数传递任何内容的代码甚至不会编译,因此您的函数不必在运行时检查这种情况。另一个示例是使用无符号整数类型(例如u32
,这可确保参数永远不会为负数。
Creating Custom Types for Validation
创建用于验证的自定义类型
Let’s take the idea of using Rust’s type system to ensure we have a valid value
one step further and look at creating a custom type for validation. Recall the
guessing game in Chapter 2 in which our code asked the user to guess a number
between 1 and 100. We never validated that the user’s guess was between those
numbers before checking it against our secret number; we only validated that
the guess was positive. In this case, the consequences were not very dire: our
output of “Too high” or “Too low” would still be correct. But it would be a
useful enhancement to guide the user toward valid guesses and have different
behavior when the user guesses a number that’s out of range versus when the
user types, for example, letters instead.
让我们进一步考虑使用 Rust 的类型系统来确保我们有一个有效的值,并考虑创建一个用于验证的自定义类型。回想一下第 2 章中的猜谜游戏,其中我们的代码要求用户猜测 1 到 100 之间的一个数字。在与我们的秘密数字进行检查之前,我们从未验证过用户的猜测是否在这些数字之间。我们只是验证了猜测是肯定的。在这种情况下,后果并不是非常可怕:我们的“太高”或“太低”输出仍然是正确的。但这将是一个有用的增强功能,可以引导用户进行有效的猜测,并且当用户猜测超出范围的数字时与用户键入字母(例如,字母)时具有不同的行为。
One way to do this would be to parse the guess as an i32
instead of only a
u32
to allow potentially negative numbers, and then add a check for the
number being in range, like so:
一种方法是将猜测解析为i32
而不是仅u32
以允许潜在的负数,然后添加对范围内数字的检查,如下所示:
Filename: src/main.rs 文件名:src/main.rs
The if
expression checks whether our value is out of range, tells the user
about the problem, and calls continue
to start the next iteration of the loop
and ask for another guess. After the if
expression, we can proceed with the
comparisons between guess
and the secret number knowing that guess
is
between 1 and 100.if
表达式检查我们的值是否超出范围,告诉用户问题,然后调用continue
开始循环的下一次迭代并要求再次猜测。在if
表达式之后,我们可以继续比较guess
和秘密数字,知道guess
在 1 到 100 之间。
However, this is not an ideal solution: if it were absolutely critical that the
program only operated on values between 1 and 100, and it had many functions
with this requirement, having a check like this in every function would be
tedious (and might impact performance).
然而,这不是一个理想的解决方案:如果程序仅对 1 到 100 之间的值进行操作是绝对关键的,并且它有许多满足此要求的函数,那么在每个函数中进行这样的检查将是乏味的(并且可能会影响表现)。
Instead, we can make a new type and put the validations in a function to create
an instance of the type rather than repeating the validations everywhere. That
way, it’s safe for functions to use the new type in their signatures and
confidently use the values they receive. Listing 9-13 shows one way to define a
Guess
type that will only create an instance of Guess
if the new
function
receives a value between 1 and 100.
相反,我们可以创建一个新类型并将验证放入函数中以创建该类型的实例,而不是在各处重复验证。这样,函数就可以安全地在其签名中使用新类型并自信地使用它们收到的值。清单 9-13 显示了定义Guess
类型的一种方法,该方法仅在new
函数接收到 1 到 100 之间的值时才会创建Guess
实例。
Filename: src/lib.rs 文件名:src/lib.rs
First we define a struct named Guess
that has a field named value
that
holds an i32
. This is where the number will be stored.
首先,我们定义一个名为Guess
结构体,它有一个名为value
字段,其中包含i32
。这是号码将被存储的地方。
Then we implement an associated function named new
on Guess
that creates
instances of Guess
values. The new
function is defined to have one
parameter named value
of type i32
and to return a Guess
. The code in the
body of the new
function tests value
to make sure it’s between 1 and 100.
If value
doesn’t pass this test, we make a panic!
call, which will alert
the programmer who is writing the calling code that they have a bug they need
to fix, because creating a Guess
with a value
outside this range would
violate the contract that Guess::new
is relying on. The conditions in which
Guess::new
might panic should be discussed in its public-facing API
documentation; we’ll cover documentation conventions indicating the possibility
of a panic!
in the API documentation that you create in Chapter 14. If
value
does pass the test, we create a new Guess
with its value
field set
to the value
parameter and return the Guess
.
然后我们在Guess
上实现一个名为new
关联函数,用于创建Guess
值的实例。 new
函数被定义为具有一个名为i32
类型的value
的参数并返回Guess
。 new
函数主体中的代码测试value
以确保它在 1 到 100 之间。如果value
没有通过此测试,我们会发生panic!
调用,这将提醒正在编写调用代码的程序员,他们有一个需要修复的错误,因为创建具有超出此范围的value
Guess
将违反Guess::new
所依赖的约定。 Guess::new
可能出现恐慌的情况应该在其面向公众的 API 文档中讨论;我们将介绍表明panic!
在第 14 章创建的 API 文档中。如果value
确实通过了测试,我们将创建一个新的Guess
,并将其value
字段设置为value
参数并返回Guess
。
Next, we implement a method named value
that borrows self
, doesn’t have any
other parameters, and returns an i32
. This kind of method is sometimes called
a getter because its purpose is to get some data from its fields and return
it. This public method is necessary because the value
field of the Guess
struct is private. It’s important that the value
field be private so code
using the Guess
struct is not allowed to set value
directly: code outside
the module must use the Guess::new
function to create an instance of
Guess
, thereby ensuring there’s no way for a Guess
to have a value
that
hasn’t been checked by the conditions in the Guess::new
function.
接下来,我们实现一个名为value
方法,该方法借用self
,没有任何其他参数,并返回i32
。这种方法有时称为getter,因为它的目的是从其字段中获取一些数据并返回它。这个公共方法是必要的,因为Guess
结构的value
字段是私有的。 value
字段必须是私有的,这一点很重要,因此使用Guess
结构的代码不允许直接设置value
:模块外部的代码必须使用Guess::new
函数来创建Guess
的实例,从而确保Guess
无法直接设置值。具有未经Guess::new
函数中的条件检查的value
。
A function that has a parameter or returns only numbers between 1 and 100 could
then declare in its signature that it takes or returns a Guess
rather than an
i32
and wouldn’t need to do any additional checks in its body.
具有参数或仅返回 1 到 100 之间数字的函数可以在其签名中声明它接受或返回Guess
而不是i32
,并且不需要在其主体中进行任何额外的检查。
Summary 概括
Rust’s error-handling features are designed to help you write more robust code.
The panic!
macro signals that your program is in a state it can’t handle and
lets you tell the process to stop instead of trying to proceed with invalid or
incorrect values. The Result
enum uses Rust’s type system to indicate that
operations might fail in a way that your code could recover from. You can use
Result
to tell code that calls your code that it needs to handle potential
success or failure as well. Using panic!
and Result
in the appropriate
situations will make your code more reliable in the face of inevitable problems.
Rust 的错误处理功能旨在帮助您编写更健壮的代码。 panic!
宏表示您的程序处于无法处理的状态,并让您告诉进程停止,而不是尝试使用无效或不正确的值继续。 Result
枚举使用 Rust 的类型系统来指示操作可能会失败,但您的代码可以从中恢复。您可以使用Result
告诉调用您的代码的代码,它也需要处理潜在的成功或失败。使用panic!
在适当的情况下Result
将使您的代码在面对不可避免的问题时更加可靠。
Now that you’ve seen useful ways that the standard library uses generics with
the Option
and Result
enums, we’ll talk about how generics work and how you
can use them in your code.
现在您已经了解了标准库通过Option
和Result
枚举使用泛型的有用方法,我们将讨论泛型的工作原理以及如何在代码中使用它们。
Generic Types, Traits, and Lifetimes
通用类型、特征和生命周期
Every programming language has tools for effectively handling the duplication
of concepts. In Rust, one such tool is generics: abstract stand-ins for
concrete types or other properties. We can express the behavior of generics or
how they relate to other generics without knowing what will be in their place
when compiling and running the code.
每种编程语言都有可以有效处理概念重复的工具。在 Rust 中,这样的工具之一就是泛型:具体类型或其他属性的抽象替代品。我们可以表达泛型的行为或它们与其他泛型的关系,而无需知道编译和运行代码时它们的位置是什么。
Functions can take parameters of some generic type, instead of a concrete type
like i32
or String
, in the same way they take parameters with unknown
values to run the same code on multiple concrete values. In fact, we’ve already
used generics in Chapter 6 with Option<T>
, in Chapter 8 with Vec<T>
and
HashMap<K, V>
, and in Chapter 9 with Result<T, E>
. In this chapter, you’ll
explore how to define your own types, functions, and methods with generics!
函数可以采用某种泛型类型的参数,而不是像i32
或String
这样的具体类型,就像它们采用未知值的参数在多个具体值上运行相同的代码一样。事实上,我们已经在第 6 章中使用了泛型Option<T>
,在第 8 章中使用了Vec<T>
和HashMap<K, V>
,在第 9 章中使用了Result<T, E>
。在本章中,您将探索如何使用泛型定义自己的类型、函数和方法!
First we’ll review how to extract a function to reduce code duplication. We’ll
then use the same technique to make a generic function from two functions that
differ only in the types of their parameters. We’ll also explain how to use
generic types in struct and enum definitions.
首先,我们将回顾如何提取函数以减少代码重复。然后,我们将使用相同的技术从两个仅参数类型不同的函数创建一个通用函数。我们还将解释如何在结构和枚举定义中使用泛型类型。
Then you’ll learn how to use traits to define behavior in a generic way. You
can combine traits with generic types to constrain a generic type to accept
only those types that have a particular behavior, as opposed to just any type.
然后您将学习如何使用特征以通用方式定义行为。您可以将特征与泛型类型结合起来,以限制泛型类型仅接受具有特定行为的类型,而不是仅接受任何类型。
Finally, we’ll discuss lifetimes: a variety of generics that give the
compiler information about how references relate to each other. Lifetimes allow
us to give the compiler enough information about borrowed values so that it can
ensure references will be valid in more situations than it could without our
help.
最后,我们将讨论生命周期:各种泛型,它们为编译器提供有关引用如何相互关联的信息。生命周期允许我们为编译器提供有关借用值的足够信息,以便它可以确保引用在更多情况下比没有我们的帮助时有效。
Removing Duplication by Extracting a Function
通过提取函数来删除重复项
Generics allow us to replace specific types with a placeholder that represents
multiple types to remove code duplication. Before diving into generics syntax,
let’s first look at how to remove duplication in a way that doesn’t involve
generic types by extracting a function that replaces specific values with a
placeholder that represents multiple values. Then we’ll apply the same
technique to extract a generic function! By looking at how to recognize
duplicated code you can extract into a function, you’ll start to recognize
duplicated code that can use generics.
泛型允许我们用代表多种类型的占位符替换特定类型,以消除代码重复。在深入研究泛型语法之前,我们首先看看如何通过提取一个函数来以不涉及泛型类型的方式删除重复,该函数用表示多个值的占位符替换特定值。然后我们将应用相同的技术来提取通用函数!通过了解如何识别可以提取到函数中的重复代码,您将开始识别可以使用泛型的重复代码。
We’ll begin with the short program in Listing 10-1 that finds the largest
number in a list.
我们将从清单 10-1 中的短程序开始,该程序查找列表中的最大数字。
Filename: src/main.rs 文件名:src/main.rs
We store a list of integers in the variable number_list
and place a reference
to the first number in the list in a variable named largest
. We then iterate
through all the numbers in the list, and if the current number is greater than
the number stored in largest
, we replace the reference in that variable.
However, if the current number is less than or equal to the largest number seen
so far, the variable doesn’t change, and the code moves on to the next number
in the list. After considering all the numbers in the list, largest
should
refer to the largest number, which in this case is 100.
我们将整数列表存储在变量number_list
中,并将对列表中第一个数字的引用放置在名为largest
变量中。然后,我们迭代列表中的所有数字,如果当前数字大于largest
中存储的数字,则替换该变量中的引用。但是,如果当前数字小于或等于迄今为止看到的最大数字,则变量不会更改,并且代码将移至列表中的下一个数字。考虑完列表中的所有数字后, largest
应指最大的数字,在本例中为 100。
We’ve now been tasked with finding the largest number in two different lists of
numbers. To do so, we can choose to duplicate the code in Listing 10-1 and use
the same logic at two different places in the program, as shown in Listing 10-2.
我们现在的任务是在两个不同的数字列表中找到最大的数字。为此,我们可以选择复制清单 10-1 中的代码,并在程序中的两个不同位置使用相同的逻辑,如清单 10-2 所示。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let mut largest = &number_list[0];
for number in &number_list {
if number > largest {
largest = number;
}
}
println!("The largest number is {largest}");
let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];
let mut largest = &number_list[0];
for number in &number_list {
if number > largest {
largest = number;
}
}
println!("The largest number is {largest}");
}
Although this code works, duplicating code is tedious and error prone. We also
have to remember to update the code in multiple places when we want to change
it.
尽管此代码有效,但复制代码非常乏味且容易出错。当我们想要更改代码时,我们还必须记住在多个地方更新代码。
To eliminate this duplication, we’ll create an abstraction by defining a
function that operates on any list of integers passed in a parameter. This
solution makes our code clearer and lets us express the concept of finding the
largest number in a list abstractly.
为了消除这种重复,我们将通过定义一个函数来创建一个抽象,该函数对参数中传递的任何整数列表进行操作。这个解决方案使我们的代码更加清晰,并让我们抽象地表达了在列表中查找最大数字的概念。
In Listing 10-3, we extract the code that finds the largest number into a
function named largest
. Then we call the function to find the largest number
in the two lists from Listing 10-2. We could also use the function on any other
list of i32
values we might have in the future.
在清单 10-3 中,我们将查找最大数字的代码提取到名为largest
函数中。然后我们调用该函数来查找清单 10-2 中两个列表中的最大数字。我们还可以在将来可能拥有的任何其他i32
值列表上使用该函数。
Filename: src/main.rs 文件名:src/main.rs
The largest
function has a parameter called list
, which represents any
concrete slice of i32
values we might pass into the function. As a result,
when we call the function, the code runs on the specific values that we pass
in.largest
函数有一个名为list
的参数,它代表我们可能传递给函数的i32
值的任何具体切片。因此,当我们调用该函数时,代码会根据我们传入的特定值运行。
In summary, here are the steps we took to change the code from Listing 10-2 to
Listing 10-3:
总之,我们将代码从清单 10-2 更改为清单 10-3 所采取的步骤如下:
- Identify duplicate code. 识别重复代码。
- Extract the duplicate code into the body of the function, and specify the
inputs and return values of that code in the function signature.
将重复代码提取到函数体中,并在函数签名中指定该代码的输入和返回值。 - Update the two instances of duplicated code to call the function instead.
更新重复代码的两个实例以改为调用该函数。
Next, we’ll use these same steps with generics to reduce code duplication. In
the same way that the function body can operate on an abstract list
instead
of specific values, generics allow code to operate on abstract types.
接下来,我们将使用这些相同的步骤与泛型来减少代码重复。就像函数体可以对抽象list
而不是特定值进行操作一样,泛型允许代码对抽象类型进行操作。
For example, say we had two functions: one that finds the largest item in a
slice of i32
values and one that finds the largest item in a slice of char
values. How would we eliminate that duplication? Let’s find out!
例如,假设我们有两个函数:一个函数查找i32
值切片中的最大项目,另一个函数查找char
值切片中的最大项目。我们如何消除这种重复?让我们来看看吧!
Generic Data Types 通用数据类型
We use generics to create definitions for items like function signatures or
structs, which we can then use with many different concrete data types. Let’s
first look at how to define functions, structs, enums, and methods using
generics. Then we’ll discuss how generics affect code performance.
我们使用泛型来创建函数签名或结构等项目的定义,然后我们可以将其与许多不同的具体数据类型一起使用。我们首先看看如何使用泛型定义函数、结构体、枚举和方法。然后我们将讨论泛型如何影响代码性能。
In Function Definitions 在函数定义中
When defining a function that uses generics, we place the generics in the
signature of the function where we would usually specify the data types of the
parameters and return value. Doing so makes our code more flexible and provides
more functionality to callers of our function while preventing code duplication.
当定义使用泛型的函数时,我们将泛型放在函数的签名中,我们通常会在其中指定参数和返回值的数据类型。这样做使我们的代码更加灵活,并为函数的调用者提供更多功能,同时防止代码重复。
Continuing with our largest
function, Listing 10-4 shows two functions that
both find the largest value in a slice. We’ll then combine these into a single
function that uses generics.
继续我们的largest
函数,清单 10-4 显示了两个函数,它们都找到切片中的最大值。然后,我们将它们组合成一个使用泛型的函数。
Filename: src/main.rs 文件名:src/main.rs
The largest_i32
function is the one we extracted in Listing 10-3 that finds
the largest i32
in a slice. The largest_char
function finds the largest
char
in a slice. The function bodies have the same code, so let’s eliminate
the duplication by introducing a generic type parameter in a single function.largest_i32
函数是我们在清单 10-3 中提取的函数,用于查找切片中最大的i32
。 largest_char
函数查找切片中最大的char
。函数体具有相同的代码,因此让我们通过在单个函数中引入泛型类型参数来消除重复。
To parameterize the types in a new single function, we need to name the type
parameter, just as we do for the value parameters to a function. You can use
any identifier as a type parameter name. But we’ll use T
because, by
convention, type parameter names in Rust are short, often just one letter, and
Rust’s type-naming convention is UpperCamelCase. Short for type, T
is the
default choice of most Rust programmers.
要参数化新的单个函数中的类型,我们需要命名类型参数,就像我们为函数的值参数所做的那样。您可以使用任何标识符作为类型参数名称。但我们将使用T
,因为按照惯例,Rust 中的类型参数名称很短,通常只有一个字母,并且 Rust 的类型命名约定是 UpperCamelCase。 T
是type的缩写,是大多数 Rust 程序员的默认选择。
When we use a parameter in the body of the function, we have to declare the
parameter name in the signature so the compiler knows what that name means.
Similarly, when we use a type parameter name in a function signature, we have
to declare the type parameter name before we use it. To define the generic
largest
function, we place type name declarations inside angle brackets,
<>
, between the name of the function and the parameter list, like this:
当我们在函数体中使用参数时,我们必须在签名中声明参数名称,以便编译器知道该名称的含义。同样,当我们在函数签名中使用类型参数名称时,我们必须在使用它之前声明类型参数名称。为了定义通用largest
函数,我们将类型名称声明放在函数名称和参数列表之间的尖括号<>
内,如下所示:
fn largest<T>(list: &[T]) -> &T {
We read this definition as: the function largest
is generic over some type
T
. This function has one parameter named list
, which is a slice of values
of type T
. The largest
function will return a reference to a value of the
same type T
.
我们将这个定义解读为:函数largest
对于某种类型T
是泛型的。该函数有一个名为list
的参数,它是T
类型值的切片。 largest
函数将返回对相同类型T
的值的引用。
Listing 10-5 shows the combined largest
function definition using the generic
data type in its signature. The listing also shows how we can call the function
with either a slice of i32
values or char
values. Note that this code won’t
compile yet, but we’ll fix it later in this chapter.
清单 10-5 显示了在其签名中使用通用数据类型的组合largest
函数定义。该清单还显示了如何使用i32
值或char
值的切片来调用该函数。请注意,这段代码还无法编译,但我们将在本章稍后修复它。
Filename: src/main.rs 文件名:src/main.rs
fn largest<T>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&number_list);
println!("The largest number is {result}");
let char_list = vec!['y', 'm', 'a', 'q'];
let result = largest(&char_list);
println!("The largest char is {result}");
}
If we compile this code right now, we’ll get this error:
如果我们现在编译这段代码,我们会得到这个错误:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0369]: binary operation `>` cannot be applied to type `&T`
--> src/main.rs:5:17
|
5 | if item > largest {
| ---- ^ ------- &T
| |
| &T
|
help: consider restricting type parameter `T`
|
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T {
| ++++++++++++++++++++++
For more information about this error, try `rustc --explain E0369`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
The help text mentions std::cmp::PartialOrd
, which is a trait, and we’re
going to talk about traits in the next section. For now, know that this error
states that the body of largest
won’t work for all possible types that T
could be. Because we want to compare values of type T
in the body, we can
only use types whose values can be ordered. To enable comparisons, the standard
library has the std::cmp::PartialOrd
trait that you can implement on types
(see Appendix C for more on this trait). By following the help text’s
suggestion, we restrict the types valid for T
to only those that implement
PartialOrd
and this example will compile, because the standard library
implements PartialOrd
on both i32
and char
.
帮助文本提到了std::cmp::PartialOrd
,这是一个Trait ,我们将在下一节中讨论 Trait 。现在,请知道此错误表明largest
的主体不适用于T
可能的所有可能类型。因为我们要比较主体中类型T
的值,所以我们只能使用值可以排序的类型。为了启用比较,标准库具有std::cmp::PartialOrd
特征,您可以在类型上实现该特征(有关此特征的更多信息,请参阅附录 C)。通过遵循帮助文本的建议,我们将对T
有效的类型限制为仅实现PartialOrd
类型,并且此示例将编译,因为标准库在i32
和char
上实现了PartialOrd
。
In Struct Definitions 在结构体定义中
We can also define structs to use a generic type parameter in one or more
fields using the <>
syntax. Listing 10-6 defines a Point<T>
struct to hold
x
and y
coordinate values of any type.
我们还可以使用<>
语法定义结构体,以在一个或多个字段中使用泛型类型参数。清单 10-6 定义了一个Point<T>
结构来保存任何类型的x
和y
坐标值。
Filename: src/main.rs 文件名:src/main.rs
struct Point<T> {
x: T,
y: T,
}
fn main() {
let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };
}
The syntax for using generics in struct definitions is similar to that used in
function definitions. First we declare the name of the type parameter inside
angle brackets just after the name of the struct. Then we use the generic
type in the struct definition where we would otherwise specify concrete data
types.
在结构定义中使用泛型的语法与在函数定义中使用的语法类似。首先,我们在结构名称后面的尖括号内声明类型参数的名称。然后,我们在结构定义中使用泛型类型,否则我们将指定具体的数据类型。
Note that because we’ve used only one generic type to define Point<T>
, this
definition says that the Point<T>
struct is generic over some type T
, and
the fields x
and y
are both that same type, whatever that type may be. If
we create an instance of a Point<T>
that has values of different types, as in
Listing 10-7, our code won’t compile.
请注意,因为我们仅使用一种泛型类型来定义Point<T>
,所以该定义表示Point<T>
结构对于某种类型T
是泛型的,并且字段x
和y
都是相同的类型,无论是什么类型那种类型可能是。如果我们创建一个具有不同类型值的Point<T>
实例(如清单 10-7 所示),我们的代码将无法编译。
Filename: src/main.rs 文件名:src/main.rs
struct Point<T> {
x: T,
y: T,
}
fn main() {
let wont_work = Point { x: 5, y: 4.0 };
}
In this example, when we assign the integer value 5
to x
, we let the
compiler know that the generic type T
will be an integer for this instance of
Point<T>
. Then when we specify 4.0
for y
, which we’ve defined to have the
same type as x
, we’ll get a type mismatch error like this:
在此示例中,当我们将整数值5
分配给x
时,我们让编译器知道泛型类型T
将是Point<T>
此实例的整数。然后,当我们为y
指定4.0
(我们已将其定义为与x
具有相同类型)时,我们将收到如下类型不匹配错误:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0308]: mismatched types
--> 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
To define a Point
struct where x
and y
are both generics but could have
different types, we can use multiple generic type parameters. For example, in
Listing 10-8, we change the definition of Point
to be generic over types T
and U
where x
is of type T
and y
is of type U
.
要定义一个Point
结构,其中x
和y
都是泛型但可以具有不同的类型,我们可以使用多个泛型类型参数。例如,在清单 10-8 中,我们将Point
的定义更改为T
和U
类型的泛型,其中x
为T
类型, y
为U
类型。
Filename: src/main.rs 文件名:src/main.rs
struct Point<T, U> {
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 };
}
Now all the instances of Point
shown are allowed! You can use as many generic
type parameters in a definition as you want, but using more than a few makes
your code hard to read. If you’re finding you need lots of generic types in
your code, it could indicate that your code needs restructuring into smaller
pieces.
现在显示的所有Point
实例都是允许的!您可以在定义中使用任意数量的泛型类型参数,但使用过多会使您的代码难以阅读。如果您发现代码中需要大量泛型类型,则可能表明您的代码需要重组为更小的部分。
In Enum Definitions 在枚举定义中
As we did with structs, we can define enums to hold generic data types in their
variants. Let’s take another look at the Option<T>
enum that the standard
library provides, which we used in Chapter 6:
正如我们对结构所做的那样,我们可以定义枚举来保存其变体中的通用数据类型。让我们再看一下标准库提供的Option<T>
枚举,我们在第 6 章中使用了它:
This definition should now make more sense to you. As you can see, the
Option<T>
enum is generic over type T
and has two variants: Some
, which
holds one value of type T
, and a None
variant that doesn’t hold any value.
By using the Option<T>
enum, we can express the abstract concept of an
optional value, and because Option<T>
is generic, we can use this abstraction
no matter what the type of the optional value is.
这个定义现在对您来说应该更有意义了。正如您所看到的, Option<T>
枚举是T
类型的泛型,并且有两个变体: Some
,它保存一个T
类型的值,以及None
变体,不保存任何值。通过使用Option<T>
枚举,我们可以表达可选值的抽象概念,并且由于Option<T>
是通用的,所以无论可选值的类型是什么,我们都可以使用这个抽象。
Enums can use multiple generic types as well. The definition of the Result
enum that we used in Chapter 9 is one example:
枚举也可以使用多种泛型类型。我们在第 9 章中使用的Result
枚举的定义就是一个例子:
The Result
enum is generic over two types, T
and E
, and has two variants:
Ok
, which holds a value of type T
, and Err
, which holds a value of type
E
. This definition makes it convenient to use the Result
enum anywhere we
have an operation that might succeed (return a value of some type T
) or fail
(return an error of some type E
). In fact, this is what we used to open a
file in Listing 9-3, where T
was filled in with the type std::fs::File
when
the file was opened successfully and E
was filled in with the type
std::io::Error
when there were problems opening the file.Result
枚举对于T
和E
两种类型是通用的,并且有两个变体: Ok
(保存T
类型的值)和Err
(保存E
类型的值)。此定义使得在任何可能成功(返回某种类型T
的值)或失败(返回某种类型E
的错误)的操作的任何地方都可以方便地使用Result
枚举。事实上,这就是清单 9-3 中我们用来打开文件的方式,其中当文件打开成功时T
填充为std::fs::File
类型, E
填充为std::io::Error
。
When you recognize situations in your code with multiple struct or enum
definitions that differ only in the types of the values they hold, you can
avoid duplication by using generic types instead.
当您认识到代码中具有多个结构或枚举定义的情况仅在它们所保存的值的类型不同时,您可以通过使用泛型类型来避免重复。
In Method Definitions 在方法定义中
We can implement methods on structs and enums (as we did in Chapter 5) and use
generic types in their definitions too. Listing 10-9 shows the Point<T>
struct we defined in Listing 10-6 with a method named x
implemented on it.
我们可以在结构和枚举上实现方法(就像我们在第 5 章中所做的那样),并在它们的定义中使用泛型类型。清单 10-9 显示了我们在清单 10-6 中定义的Point<T>
结构体,并在其上实现了一个名为x
方法。
Filename: src/main.rs 文件名:src/main.rs
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}
fn main() {
let p = Point { x: 5, y: 10 };
println!("p.x = {}", p.x());
}
Here, we’ve defined a method named x
on Point<T>
that returns a reference
to the data in the field x
.
在这里,我们在Point<T>
上定义了一个名为x
的方法,该方法返回对字段x
中数据的引用。
Note that we have to declare T
just after impl
so we can use T
to specify
that we’re implementing methods on the type Point<T>
. By declaring T
as a
generic type after impl
, Rust can identify that the type in the angle
brackets in Point
is a generic type rather than a concrete type. We could
have chosen a different name for this generic parameter than the generic
parameter declared in the struct definition, but using the same name is
conventional. Methods written within an impl
that declares the generic type
will be defined on any instance of the type, no matter what concrete type ends
up substituting for the generic type.
请注意,我们必须在impl
之后声明T
,以便我们可以使用T
来指定我们正在类型Point<T>
上实现方法。通过在impl
之后将T
声明为泛型类型,Rust 可以识别Point
中尖括号中的类型是泛型类型而不是具体类型。我们可以为此泛型参数选择与结构定义中声明的泛型参数不同的名称,但使用相同的名称是常规做法。在声明泛型类型的impl
中编写的方法将在该类型的任何实例上定义,无论最终替换泛型类型的具体类型是什么。
We can also specify constraints on generic types when defining methods on the
type. We could, for example, implement methods only on Point<f32>
instances
rather than on Point<T>
instances with any generic type. In Listing 10-10 we
use the concrete type f32
, meaning we don’t declare any types after impl
.
我们还可以在类型上定义方法时指定泛型类型的约束。例如,我们可以仅在Point<f32>
实例上实现方法,而不是在任何泛型类型的Point<T>
实例上实现方法。在清单 10-10 中,我们使用具体类型f32
,这意味着我们在impl
之后不声明任何类型。
Filename: src/main.rs 文件名:src/main.rs
This code means the type Point<f32>
will have a distance_from_origin
method; other instances of Point<T>
where T
is not of type f32
will not
have this method defined. The method measures how far our point is from the
point at coordinates (0.0, 0.0) and uses mathematical operations that are
available only for floating-point types.
此代码意味着类型Point<f32>
将具有distance_from_origin
方法; Point<T>
的其他实例(其中T
不是f32
类型)将不会定义此方法。该方法测量我们的点距坐标 (0.0, 0.0) 处的点的距离,并使用仅适用于浮点类型的数学运算。
Generic type parameters in a struct definition aren’t always the same as those
you use in that same struct’s method signatures. Listing 10-11 uses the generic
types X1
and Y1
for the Point
struct and X2
Y2
for the mixup
method
signature to make the example clearer. The method creates a new Point
instance with the x
value from the self
Point
(of type X1
) and the y
value from the passed-in Point
(of type Y2
).
结构定义中的泛型类型参数并不总是与在同一结构的方法签名中使用的参数相同。清单 10-11 使用泛型类型X1
和Y1
作为Point
结构,使用X2
Y2
作为mixup
方法签名,以使示例更加清晰。该方法使用来自self
Point
(类型为X1
)的x
值和来自传入Point
(类型为Y2
)的y
值创建一个新的Point
实例。
Filename: src/main.rs 文件名:src/main.rs
struct Point<X1, Y1> {
x: X1,
y: Y1,
}
impl<X1, Y1> Point<X1, Y1> {
fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> {
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);
}
In main
, we’ve defined a Point
that has an i32
for x
(with value 5
)
and an f64
for y
(with value 10.4
). The p2
variable is a Point
struct
that has a string slice for x
(with value "Hello"
) and a char
for y
(with value c
). Calling mixup
on p1
with the argument p2
gives us p3
,
which will have an i32
for x
because x
came from p1
. The p3
variable
will have a char
for y
because y
came from p2
. The println!
macro
call will print p3.x = 5, p3.y = c
.
在main
中,我们定义了一个Point
,它的x
为i32
(值为5
), y
为f64
(值为10.4
)。 p2
变量是一个Point
结构,它具有x
的字符串切片(值为"Hello"
)和y
的char
(值为c
)。使用参数p2
在p1
上调用mixup
会得到p3
,其中x
将会有一个i32
,因为x
来自p1
。 p3
变量将有一个y
char
,因为y
来自p2
。 println!
宏调用将打印p3.x = 5, p3.y = c
。
The purpose of this example is to demonstrate a situation in which some generic
parameters are declared with impl
and some are declared with the method
definition. Here, the generic parameters X1
and Y1
are declared after
impl
because they go with the struct definition. The generic parameters X2
and Y2
are declared after fn mixup
because they’re only relevant to the
method.
此示例的目的是演示一些泛型参数使用impl
声明而另一些泛型参数使用方法定义声明的情况。这里,通用参数X1
和Y1
在impl
之后声明,因为它们与结构定义一致。泛型参数X2
和Y2
在fn mixup
之后声明,因为它们仅与方法相关。
Performance of Code Using Generics
使用泛型的代码性能
You might be wondering whether there is a runtime cost when using generic type
parameters. The good news is that using generic types won’t make your program
run any slower than it would with concrete types.
您可能想知道使用泛型类型参数时是否存在运行时成本。好消息是,使用泛型类型不会使程序运行速度比使用具体类型慢。
Rust accomplishes this by performing monomorphization of the code using
generics at compile time. Monomorphization is the process of turning generic
code into specific code by filling in the concrete types that are used when
compiled. In this process, the compiler does the opposite of the steps we used
to create the generic function in Listing 10-5: the compiler looks at all the
places where generic code is called and generates code for the concrete types
the generic code is called with.
Rust 通过在编译时使用泛型执行代码的单态化来实现这一点。单态化是通过填充编译时使用的具体类型将通用代码转换为特定代码的过程。在此过程中,编译器执行与清单 10-5 中创建泛型函数相反的步骤:编译器查看调用泛型代码的所有位置,并为调用泛型代码的具体类型生成代码。
Let’s look at how this works by using the standard library’s generic
Option<T>
enum:
让我们通过使用标准库的通用Option<T>
枚举来看看它是如何工作的:
When Rust compiles this code, it performs monomorphization. During that
process, the compiler reads the values that have been used in Option<T>
instances and identifies two kinds of Option<T>
: one is i32
and the other
is f64
. As such, it expands the generic definition of Option<T>
into two
definitions specialized to i32
and f64
, thereby replacing the generic
definition with the specific ones.
当 Rust 编译此代码时,它会执行单态化。在此过程中,编译器读取Option<T>
实例中使用的值并识别两种Option<T>
:一种是i32
,另一种是f64
。因此,它将Option<T>
的通用定义扩展为专门用于i32
和f64
的两个定义,从而用特定定义替换通用定义。
The monomorphized version of the code looks similar to the following (the
compiler uses different names than what we’re using here for illustration):
代码的单态版本类似于以下内容(编译器使用的名称与我们此处用于说明的名称不同):
Filename: src/main.rs 文件名:src/main.rs
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);
}
The generic Option<T>
is replaced with the specific definitions created by
the compiler. Because Rust compiles generic code into code that specifies the
type in each instance, we pay no runtime cost for using generics. When the code
runs, it performs just as it would if we had duplicated each definition by
hand. The process of monomorphization makes Rust’s generics extremely efficient
at runtime.
通用Option<T>
将替换为编译器创建的特定定义。因为 Rust 将泛型代码编译为指定每个实例中的类型的代码,所以我们无需为使用泛型支付运行时成本。当代码运行时,它的执行效果就像我们手动复制每个定义一样。单态化过程使得 Rust 的泛型在运行时非常高效。
Traits: Defining Shared Behavior
特征:定义共同行为
A trait defines the functionality a particular type has and can share with
other types. We can use traits to define shared behavior in an abstract way. We
can use trait bounds to specify that a generic type can be any type that has
certain behavior.
特征定义了特定类型具有的功能并且可以与其他类型共享。我们可以使用特征以抽象的方式定义共享行为。我们可以使用特征边界来指定泛型类型可以是具有特定行为的任何类型。
Note: Traits are similar to a feature often called interfaces in other
languages, although with some differences.
注意:特征与其他语言中通常称为接口的功能类似,但也有一些差异。
Defining a Trait 定义特质
A type’s behavior consists of the methods we can call on that type. Different
types share the same behavior if we can call the same methods on all of those
types. Trait definitions are a way to group method signatures together to
define a set of behaviors necessary to accomplish some purpose.
类型的行为由我们可以在该类型上调用的方法组成。如果我们可以对所有这些类型调用相同的方法,那么不同的类型就会共享相同的行为。特征定义是将方法签名分组在一起以定义实现某些目的所需的一组行为的方法。
For example, let’s say we have multiple structs that hold various kinds and
amounts of text: a NewsArticle
struct that holds a news story filed in a
particular location and a Tweet
that can have, at most, 280 characters along
with metadata that indicates whether it was a new tweet, a retweet, or a reply
to another tweet.
例如,假设我们有多个结构体来保存各种类型和数量的文本:一个NewsArticle
结构体保存在特定位置归档的新闻故事,以及一条最多可以包含 280 个字符的推Tweet
以及指示是否是一条新推文、一条转发或对另一条推文的回复。
We want to make a media aggregator library crate named aggregator
that can
display summaries of data that might be stored in a NewsArticle
or Tweet
instance. To do this, we need a summary from each type, and we’ll request that
summary by calling a summarize
method on an instance. Listing 10-12 shows the
definition of a public Summary
trait that expresses this behavior.
我们想要创建一个名为aggregator
媒体聚合器库 crate,它可以显示可能存储在NewsArticle
或Tweet
实例中的数据摘要。为此,我们需要每种类型的摘要,并且我们将通过调用实例上的summarize
方法来请求该摘要。清单 10-12 显示了表达此行为的公共Summary
特征的定义。
Filename: src/lib.rs 文件名:src/lib.rs
pub trait Summary {
fn summarize(&self) -> String;
}
Here, we declare a trait using the trait
keyword and then the trait’s name,
which is Summary
in this case. We also declare the trait as pub
so that
crates depending on this crate can make use of this trait too, as we’ll see in
a few examples. Inside the curly brackets, we declare the method signatures
that describe the behaviors of the types that implement this trait, which in
this case is fn summarize(&self) -> String
.
在这里,我们使用trait
关键字声明一个特征,然后使用该特征的名称,在本例中为Summary
。我们还将该特征声明为pub
,以便依赖于该箱子的箱子也可以使用该特征,正如我们将在几个示例中看到的那样。在大括号内,我们声明了描述实现此特征的类型的行为的方法签名,在本例中为fn summarize(&self) -> String
。
After the method signature, instead of providing an implementation within curly
brackets, we use a semicolon. Each type implementing this trait must provide
its own custom behavior for the body of the method. The compiler will enforce
that any type that has the Summary
trait will have the method summarize
defined with this signature exactly.
在方法签名之后,我们不使用大括号内提供实现,而是使用分号。实现此特征的每种类型都必须为方法体提供自己的自定义行为。编译器将强制任何具有Summary
特征的类型都将使用此签名准确定义的方法summarize
。
A trait can have multiple methods in its body: the method signatures are listed
one per line, and each line ends in a semicolon.
特征可以在其主体中包含多个方法:每行列出一个方法签名,并且每行以分号结尾。
Implementing a Trait on a Type
在类型上实现特征
Now that we’ve defined the desired signatures of the Summary
trait’s methods,
we can implement it on the types in our media aggregator. Listing 10-13 shows
an implementation of the Summary
trait on the NewsArticle
struct that uses
the headline, the author, and the location to create the return value of
summarize
. For the Tweet
struct, we define summarize
as the username
followed by the entire text of the tweet, assuming that the tweet content is
already limited to 280 characters.
现在我们已经定义了Summary
特征方法的所需签名,我们可以在媒体聚合器中的类型上实现它。清单 10-13 显示了NewsArticle
结构上Summary
特征的实现,它使用标题、作者和位置来创建summarize
的返回值。对于Tweet
结构,我们将summarize
定义为用户名后跟推文的整个文本,假设推文内容已限制为 280 个字符。
Filename: src/lib.rs 文件名:src/lib.rs
Implementing a trait on a type is similar to implementing regular methods. The
difference is that after impl
, we put the trait name we want to implement,
then use the for
keyword, and then specify the name of the type we want to
implement the trait for. Within the impl
block, we put the method signatures
that the trait definition has defined. Instead of adding a semicolon after each
signature, we use curly brackets and fill in the method body with the specific
behavior that we want the methods of the trait to have for the particular type.
在类型上实现特征与实现常规方法类似。不同之处在于,在impl
之后,我们放置要实现的特征名称,然后使用for
关键字,然后指定要为其实现特征的类型的名称。在impl
块中,我们放置了特征定义所定义的方法签名。我们不是在每个签名后添加分号,而是使用大括号并使用我们希望特征方法对于特定类型具有的特定行为填充方法体。
Now that the library has implemented the Summary
trait on NewsArticle
and
Tweet
, users of the crate can call the trait methods on instances of
NewsArticle
and Tweet
in the same way we call regular methods. The only
difference is that the user must bring the trait into scope as well as the
types. Here’s an example of how a binary crate could use our aggregator
library crate:
现在,库已经在NewsArticle
和Tweet
上实现了Summary
特征,板条箱的用户可以以与我们调用常规方法相同的方式在NewsArticle
和Tweet
实例上调用特征方法。唯一的区别是用户必须将特征以及类型纳入范围。以下是二进制板条箱如何使用我们的aggregator
库板条箱的示例:
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());
}
This code prints 1 new tweet: horse_ebooks: of course, as you probably already know, people
.
此代码打印1 new tweet: horse_ebooks: of course, as you probably already know, people
。
Other crates that depend on the aggregator
crate can also bring the Summary
trait into scope to implement Summary
on their own types. One restriction to
note is that we can implement a trait on a type only if either the trait or the
type, or both, are local to our crate. For example, we can implement standard
library traits like Display
on a custom type like Tweet
as part of our
aggregator
crate functionality because the type Tweet
is local to our
aggregator
crate. We can also implement Summary
on Vec<T>
in our
aggregator
crate because the trait Summary
is local to our aggregator
crate.
依赖于aggregator
crate 的其他 crate 也可以将Summary
特征纳入范围,以在自己的类型上实现Summary
。需要注意的一个限制是,只有当特征或类型或两者都属于我们的板条箱本地时,我们才能在类型上实现特征。例如,我们可以在自定义类型(如Tweet
上实现标准库特征(如Display
,作为aggregator
箱功能的一部分,因为类型Tweet
是aggregator
箱的本地类型。我们还可以在aggregator
箱中的Vec<T>
上实现Summary
,因为特征Summary
是aggregator
箱的本地特征。
But we can’t implement external traits on external types. For example, we can’t
implement the Display
trait on Vec<T>
within our aggregator
crate because
Display
and Vec<T>
are both defined in the standard library and aren’t
local to our aggregator
crate. This restriction is part of a property called
coherence, and more specifically the orphan rule, so named because the
parent type is not present. This rule ensures that other people’s code can’t
break your code and vice versa. Without the rule, two crates could implement
the same trait for the same type, and Rust wouldn’t know which implementation
to use.
但我们无法在外部类型上实现外部特征。例如,我们无法在aggregator
箱内的Vec<T>
上实现Display
特征,因为Display
和Vec<T>
都是在标准库中定义的,并且不是aggregator
箱的本地资源。此限制是称为coherence的属性的一部分,更具体地说是孤儿规则,如此命名是因为父类型不存在。该规则确保其他人的代码不会破坏您的代码,反之亦然。如果没有规则,两个板条箱可以为同一类型实现相同的特征,而 Rust 不知道要使用哪个实现。
Default Implementations 默认实现
Sometimes it’s useful to have default behavior for some or all of the methods
in a trait instead of requiring implementations for all methods on every type.
Then, as we implement the trait on a particular type, we can keep or override
each method’s default behavior.
有时,为特征中的部分或全部方法提供默认行为而不是要求每种类型上的所有方法都实现是很有用的。然后,当我们在特定类型上实现该特征时,我们可以保留或覆盖每个方法的默认行为。
In Listing 10-14, we specify a default string for the summarize
method of the
Summary
trait instead of only defining the method signature, as we did in
Listing 10-12.
在清单10-14中,我们为Summary
特征的summarize
方法指定了一个默认字符串,而不是像清单10-12中那样只定义方法签名。
Filename: src/lib.rs 文件名:src/lib.rs
To use a default implementation to summarize instances of NewsArticle
, we
specify an empty impl
block with impl Summary for NewsArticle {}
.
要使用默认实现来汇总NewsArticle
的实例,我们使用impl Summary for NewsArticle {}
指定一个空的impl
块。
Even though we’re no longer defining the summarize
method on NewsArticle
directly, we’ve provided a default implementation and specified that
NewsArticle
implements the Summary
trait. As a result, we can still call
the summarize
method on an instance of NewsArticle
, like this:
尽管我们不再直接在NewsArticle
上定义summarize
方法,但我们提供了默认实现并指定NewsArticle
实现Summary
特征。因此,我们仍然可以在NewsArticle
实例上调用summarize
方法,如下所示:
This code prints New article available! (Read more...)
.
此代码打印New article available! (Read more...)
。
Creating a default implementation doesn’t require us to change anything about
the implementation of Summary
on Tweet
in Listing 10-13. The reason is that
the syntax for overriding a default implementation is the same as the syntax
for implementing a trait method that doesn’t have a default implementation.
创建默认实现不需要我们对清单 10-13 中的Summary
on Tweet
实现进行任何更改。原因是覆盖默认实现的语法与实现没有默认实现的特征方法的语法相同。
Default implementations can call other methods in the same trait, even if those
other methods don’t have a default implementation. In this way, a trait can
provide a lot of useful functionality and only require implementors to specify
a small part of it. For example, we could define the Summary
trait to have a
summarize_author
method whose implementation is required, and then define a
summarize
method that has a default implementation that calls the
summarize_author
method:
默认实现可以调用同一特征中的其他方法,即使这些其他方法没有默认实现。通过这种方式,一个特征可以提供很多有用的功能,并且只需要实现者指定其中的一小部分。例如,我们可以定义Summary
特征以具有需要实现的summarize_author
方法,然后定义一个具有调用summarize_author
方法的默认实现的summarize
方法:
To use this version of Summary
, we only need to define summarize_author
when we implement the trait on a type:
要使用这个版本的Summary
,我们只需要在类型上实现特征时定义summarize_author
:
After we define summarize_author
, we can call summarize
on instances of the
Tweet
struct, and the default implementation of summarize
will call the
definition of summarize_author
that we’ve provided. Because we’ve implemented
summarize_author
, the Summary
trait has given us the behavior of the
summarize
method without requiring us to write any more code. Here’s what
that looks like:
定义summarize_author
之后,我们可以在Tweet
结构体的实例上调用summarize
,并且summarize
的默认实现将调用我们提供的summarize_author
的定义。因为我们已经实现了summarize_author
,所以Summary
特征为我们提供了summarize
方法的行为,而无需我们编写更多代码。看起来是这样的:
This code prints 1 new tweet: (Read more from @horse_ebooks...)
.
此代码打印1 new tweet: (Read more from @horse_ebooks...)
。
Note that it isn’t possible to call the default implementation from an
overriding implementation of that same method.
请注意,不可能从同一方法的重写实现调用默认实现。
Traits as Parameters 作为参数的特征
Now that you know how to define and implement traits, we can explore how to use
traits to define functions that accept many different types. We’ll use the
Summary
trait we implemented on the NewsArticle
and Tweet
types in
Listing 10-13 to define a notify
function that calls the summarize
method
on its item
parameter, which is of some type that implements the Summary
trait. To do this, we use the impl Trait
syntax, like this:
现在您已经知道如何定义和实现特征,我们可以探索如何使用特征来定义接受许多不同类型的函数。我们将使用在清单 10-13 中的NewsArticle
和Tweet
类型上实现的Summary
特征来定义一个notify
函数,该函数在其item
参数上调用summarize
方法,该参数是实现Summary
特征的某种类型。为此,我们使用impl Trait
语法,如下所示:
Instead of a concrete type for the item
parameter, we specify the impl
keyword and the trait name. This parameter accepts any type that implements the
specified trait. In the body of notify
, we can call any methods on item
that come from the Summary
trait, such as summarize
. We can call notify
and pass in any instance of NewsArticle
or Tweet
. Code that calls the
function with any other type, such as a String
or an i32
, won’t compile
because those types don’t implement Summary
.
我们指定impl
关键字和特征名称,而不是item
参数的具体类型。此参数接受实现指定特征的任何类型。在notify
的主体中,我们可以调用来自Summary
特征的item
上的任何方法,例如summarize
。我们可以调用notify
并传入NewsArticle
或Tweet
的任何实例。使用任何其他类型(例如String
或i32
)调用该函数的代码将无法编译,因为这些类型未实现Summary
。
Trait Bound Syntax 特征绑定语法
The impl Trait
syntax works for straightforward cases but is actually syntax
sugar for a longer form known as a trait bound; it looks like this:impl Trait
语法适用于简单的情况,但实际上是称为特征绑定的较长形式的语法糖;它看起来像这样:
pub fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
This longer form is equivalent to the example in the previous section but is
more verbose. We place trait bounds with the declaration of the generic type
parameter after a colon and inside angle brackets.
这种较长的形式相当于上一节中的示例,但更冗长。我们将特征边界与泛型类型参数的声明放在冒号后面和尖括号内。
The impl Trait
syntax is convenient and makes for more concise code in simple
cases, while the fuller trait bound syntax can express more complexity in other
cases. For example, we can have two parameters that implement Summary
. Doing
so with the impl Trait
syntax looks like this:impl Trait
语法很方便,可以在简单情况下使代码更简洁,而更完整的特征绑定语法可以在其他情况下表达更复杂的情况。例如,我们可以有两个实现Summary
的参数。使用impl Trait
语法执行此操作如下所示:
pub fn notify(item1: &impl Summary, item2: &impl Summary) {
Using impl Trait
is appropriate if we want this function to allow item1
and
item2
to have different types (as long as both types implement Summary
). If
we want to force both parameters to have the same type, however, we must use a
trait bound, like this:
如果我们希望此函数允许item1
和item2
具有不同的类型(只要这两种类型都实现Summary
),那么使用impl Trait
是合适的。但是,如果我们想强制两个参数具有相同的类型,则必须使用特征绑定,如下所示:
pub fn notify<T: Summary>(item1: &T, item2: &T) {
The generic type T
specified as the type of the item1
and item2
parameters constrains the function such that the concrete type of the value
passed as an argument for item1
and item2
must be the same.
指定为item1
和item2
参数类型的泛型类型T
会限制该函数,使得作为item1
和item2
参数传递的值的具体类型必须相同。
Specifying Multiple Trait Bounds with the +
Syntax
使用+
语法指定多个特征边界
We can also specify more than one trait bound. Say we wanted notify
to use
display formatting as well as summarize
on item
: we specify in the notify
definition that item
must implement both Display
and Summary
. We can do
so using the +
syntax:
我们还可以指定多个特征界限。假设我们希望notify
使用显示格式以及对item
summarize
:我们在notify
定义中指定item
必须同时实现Display
和Summary
。我们可以使用+
语法来做到这一点:
pub fn notify(item: &(impl Summary + Display)) {
The +
syntax is also valid with trait bounds on generic types:+
语法对于泛型类型的特征边界也有效:
pub fn notify<T: Summary + Display>(item: &T) {
With the two trait bounds specified, the body of notify
can call summarize
and use {}
to format item
.
指定两个特征边界后, notify
的主体可以调用summarize
并使用{}
来格式化item
。
Clearer Trait Bounds with where
Clauses
更清晰的 Trait 与where
子句的界限
Using too many trait bounds has its downsides. Each generic has its own trait
bounds, so functions with multiple generic type parameters can contain lots of
trait bound information between the function’s name and its parameter list,
making the function signature hard to read. For this reason, Rust has alternate
syntax for specifying trait bounds inside a where
clause after the function
signature. So, instead of writing this:
使用太多的特征界限有其缺点。每个泛型都有自己的特征界限,因此具有多个泛型类型参数的函数可以在函数名称与其参数列表之间包含大量特征界限信息,从而使函数签名难以阅读。因此,Rust 有替代语法用于在函数签名后的where
子句内指定特征边界。所以,不要这样写:
fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {
we can use a where
clause, like this:
我们可以使用where
子句,如下所示:
This function’s signature is less cluttered: the function name, parameter list,
and return type are close together, similar to a function without lots of trait
bounds.
该函数的签名不太混乱:函数名称、参数列表和返回类型紧密结合在一起,类似于没有大量特征边界的函数。
Returning Types That Implement Traits
返回实现特征的类型
We can also use the impl Trait
syntax in the return position to return a
value of some type that implements a trait, as shown here:
我们还可以在返回位置使用impl Trait
语法来返回实现特征的某种类型的值,如下所示:
By using impl Summary
for the return type, we specify that the
returns_summarizable
function returns some type that implements the Summary
trait without naming the concrete type. In this case, returns_summarizable
returns a Tweet
, but the code calling this function doesn’t need to know that.
通过使用impl Summary
作为返回类型,我们指定returns_summarizable
函数返回某种实现Summary
特征的类型,而无需命名具体类型。在这种情况下, returns_summarizable
返回一条Tweet
,但调用此函数的代码不需要知道这一点。
The ability to specify a return type only by the trait it implements is
especially useful in the context of closures and iterators, which we cover in
Chapter 13. Closures and iterators create types that only the compiler knows or
types that are very long to specify. The impl Trait
syntax lets you concisely
specify that a function returns some type that implements the Iterator
trait
without needing to write out a very long type.
仅通过其实现的特征来指定返回类型的能力在闭包和迭代器的上下文中特别有用,我们将在第 13 章中介绍这一点。闭包和迭代器创建只有编译器知道的类型或需要很长的类型。 impl Trait
语法可让您简洁地指定函数返回某种实现Iterator
特征的类型,而无需写出非常长的类型。
However, you can only use impl Trait
if you’re returning a single type. For
example, this code that returns either a NewsArticle
or a Tweet
with the
return type specified as impl Summary
wouldn’t work:
但是,如果您返回单一类型,则只能使用impl Trait
。例如,返回NewsArticle
或Tweet
(返回类型指定为impl Summary
的代码将不起作用:
Returning either a NewsArticle
or a Tweet
isn’t allowed due to restrictions
around how the impl Trait
syntax is implemented in the compiler. We’ll cover
how to write a function with this behavior in the “Using Trait Objects That
Allow for Values of Different
Types” section of Chapter 17.
由于编译器中如何实现impl Trait
语法的限制,不允许返回NewsArticle
或Tweet
。我们将在第 17 章的“使用允许不同类型值的特征对象”忽略部分中介绍如何编写具有这种行为的函数。
Using Trait Bounds to Conditionally Implement Methods
使用特征界限有条件地实现方法
By using a trait bound with an impl
block that uses generic type parameters,
we can implement methods conditionally for types that implement the specified
traits. For example, the type Pair<T>
in Listing 10-15 always implements the
new
function to return a new instance of Pair<T>
(recall from the
“Defining Methods” section of Chapter 5 that Self
is a type alias for the type of the impl
block, which in this case is
Pair<T>
). But in the next impl
block, Pair<T>
only implements the
cmp_display
method if its inner type T
implements the PartialOrd
trait
that enables comparison and the Display
trait that enables printing.
通过使用与使用泛型类型参数的impl
块绑定的特征,我们可以有条件地为实现指定特征的类型实现方法。例如,清单 10-15 中的类型Pair<T>
总是实现new
函数来返回Pair<T>
的新实例(回想一下第 5 章的“定义方法”忽略部分, Self
是一个类型别名) impl
块的类型,在本例中为Pair<T>
)。但在下一个impl
块中,如果 Pair<T> 的内部类型T
实现了启用比较的PartialOrd
特征和启用打印的Display
特征,则Pair<T>
仅实现cmp_display
方法。
Filename: src/lib.rs 文件名:src/lib.rs
use std::fmt::Display;
struct Pair<T> {
x: T,
y: T,
}
impl<T> Pair<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
impl<T: Display + PartialOrd> Pair<T> {
fn cmp_display(&self) {
if self.x >= self.y {
println!("The largest member is x = {}", self.x);
} else {
println!("The largest member is y = {}", self.y);
}
}
}
We can also conditionally implement a trait for any type that implements
another trait. Implementations of a trait on any type that satisfies the trait
bounds are called blanket implementations and are used extensively in the
Rust standard library. For example, the standard library implements the
ToString
trait on any type that implements the Display
trait. The impl
block in the standard library looks similar to this code:
我们还可以有条件地为任何实现另一个特征的类型实现一个特征。满足特征边界的任何类型上特征的实现称为毯子实现,并在 Rust 标准库中广泛使用。例如,标准库在任何实现Display
特征的类型上实现ToString
特征。标准库中的impl
块看起来类似于以下代码:
impl<T: Display> ToString for T {
// --snip--
}
Because the standard library has this blanket implementation, we can call the
to_string
method defined by the ToString
trait on any type that implements
the Display
trait. For example, we can turn integers into their corresponding
String
values like this because integers implement Display
:
由于标准库具有此一揽子实现,因此我们可以在实现Display
特征的任何类型上调用由ToString
特征定义的to_string
方法。例如,我们可以将整数转换为相应的String
值,如下所示,因为整数实现了Display
:
Blanket implementations appear in the documentation for the trait in the
“Implementors” section.
一揽子实现出现在“实现者”部分中该特征的文档中。
Traits and trait bounds let us write code that uses generic type parameters to
reduce duplication but also specify to the compiler that we want the generic
type to have particular behavior. The compiler can then use the trait bound
information to check that all the concrete types used with our code provide the
correct behavior. In dynamically typed languages, we would get an error at
runtime if we called a method on a type which didn’t define the method. But
Rust moves these errors to compile time so we’re forced to fix the problems
before our code is even able to run. Additionally, we don’t have to write code
that checks for behavior at runtime because we’ve already checked at compile
time. Doing so improves performance without having to give up the flexibility
of generics.
特征和特征边界让我们可以编写使用泛型类型参数来减少重复的代码,同时也向编译器指定我们希望泛型类型具有特定的行为。然后,编译器可以使用特征绑定信息来检查与我们的代码一起使用的所有具体类型是否提供了正确的行为。在动态类型语言中,如果我们调用未定义该方法的类型的方法,则会在运行时收到错误。但 Rust 将这些错误移至编译时,因此我们被迫在代码运行之前修复这些问题。此外,我们不必编写在运行时检查行为的代码,因为我们已经在编译时进行了检查。这样做可以提高性能,而不必放弃泛型的灵活性。
Validating References with Lifetimes
验证引用的生命周期
Lifetimes are another kind of generic that we’ve already been using. Rather
than ensuring that a type has the behavior we want, lifetimes ensure that
references are valid as long as we need them to be.
生命周期是我们已经使用过的另一种泛型。生命周期不是确保类型具有我们想要的行为,而是确保引用在我们需要的时间内有效。
One detail we didn’t discuss in the “References and
Borrowing” section in Chapter 4 is
that every reference in Rust has a lifetime, which is the scope for which
that reference is valid. Most of the time, lifetimes are implicit and inferred,
just like most of the time, types are inferred. We must annotate types only
when multiple types are possible. In a similar way, we must annotate lifetimes
when the lifetimes of references could be related in a few different ways. Rust
requires us to annotate the relationships using generic lifetime parameters to
ensure the actual references used at runtime will definitely be valid.
我们在第 4 章的“引用和借用”忽略部分中没有讨论的一个细节是 Rust 中的每个引用都有一个生命周期,即该引用有效的范围。大多数时候,生命周期是隐式的和推断的,就像大多数时候类型是推断的一样。仅当可能有多种类型时,我们才必须注释类型。以类似的方式,当引用的生命周期可以通过几种不同的方式关联时,我们必须注释生命周期。 Rust 要求我们使用通用生命周期参数来注释关系,以确保运行时使用的实际引用肯定是有效的。
Annotating lifetimes is not a concept most other programming languages have, so
this is going to feel unfamiliar. Although we won’t cover lifetimes in their
entirety in this chapter, we’ll discuss common ways you might encounter
lifetime syntax so you can get comfortable with the concept.
注释生命周期并不是大多数其他编程语言所具有的概念,因此这会让人感到陌生。尽管我们不会在本章中完整地介绍生命周期,但我们将讨论您可能遇到生命周期语法的常见方式,以便您能够熟悉这个概念。
Preventing Dangling References with Lifetimes
通过生命周期防止悬空引用
The main aim of lifetimes is to prevent dangling references, which cause a
program to reference data other than the data it’s intended to reference.
Consider the program in Listing 10-16, which has an outer scope and an inner
scope.
生命周期的主要目的是防止悬空引用,悬空引用会导致程序引用其打算引用的数据之外的数据。考虑清单 10-16 中的程序,它有一个外部作用域和一个内部作用域。
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("r: {r}");
}
Note: The examples in Listing 10-16, 10-17, and 10-23 declare variables
without giving them an initial value, so the variable name exists in the outer
scope. At first glance, this might appear to be in conflict with Rust’s having
no null values. However, if we try to use a variable before giving it a value,
we’ll get a compile-time error, which shows that Rust indeed does not allow
null values.
注意:清单 10-16、10-17 和 10-23 中的示例声明变量时没有赋予它们初始值,因此变量名存在于外部作用域中。乍一看,这似乎与 Rust 没有空值相冲突。然而,如果我们在给变量赋值之前尝试使用它,我们会得到一个编译时错误,这表明 Rust 确实不允许空值。
The outer scope declares a variable named r
with no initial value, and the
inner scope declares a variable named x
with the initial value of 5
. Inside
the inner scope, we attempt to set the value of r
as a reference to x
. Then
the inner scope ends, and we attempt to print the value in r
. This code won’t
compile because the value that r
is referring to has gone out of scope before
we try to use it. Here is the error message:
外部作用域声明一个名为r
的变量,没有初始值,内部作用域声明一个名为x
的变量,初始值为5
。在内部作用域内,我们尝试将r
的值设置为对x
的引用。然后内部作用域结束,我们尝试打印r
中的值。该代码无法编译,因为在我们尝试使用r
所引用的值之前它已经超出了范围。这是错误消息:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `x` does not live long enough
--> src/main.rs:6:13
|
5 | let x = 5;
| - binding `x` declared here
6 | r = &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
The error message says that the variable x
“does not live long enough.” The
reason is that x
will be out of scope when the inner scope ends on line 7.
But r
is still valid for the outer scope; because its scope is larger, we say
that it “lives longer.” If Rust allowed this code to work, r
would be
referencing memory that was deallocated when x
went out of scope, and
anything we tried to do with r
wouldn’t work correctly. So how does Rust
determine that this code is invalid? It uses a borrow checker.
错误消息表明变量x
“生存时间不够长”。原因是当内部作用域在第 7 行结束时, x
将超出作用域。但r
对于外部作用域仍然有效;因为它的范围更大,所以我们说它“寿命更长”。如果 Rust 允许此代码工作, r
将引用当x
超出范围时释放的内存,并且我们尝试对r
执行的任何操作都将无法正常工作。那么 Rust 是如何判断这段代码无效的呢?它使用借用检查器。
The Borrow Checker 借用检查器
The Rust compiler has a borrow checker that compares scopes to determine
whether all borrows are valid. Listing 10-17 shows the same code as Listing
10-16 but with annotations showing the lifetimes of the variables.
Rust 编译器有一个借用检查器,可以比较范围以确定所有借用是否有效。清单 10-17 显示了与清单 10-16 相同的代码,但带有显示变量生命周期的注释。
fn main() {
let r; // ---------+-- 'a
// |
{ // |
let x = 5; // -+-- 'b |
r = &x; // | |
} // -+ |
// |
println!("r: {r}"); // |
} // ---------+
Here, we’ve annotated the lifetime of r
with 'a
and the lifetime of x
with 'b
. As you can see, the inner 'b
block is much smaller than the outer
'a
lifetime block. At compile time, Rust compares the size of the two
lifetimes and sees that r
has a lifetime of 'a
but that it refers to memory
with a lifetime of 'b
. The program is rejected because 'b
is shorter than
'a
: the subject of the reference doesn’t live as long as the reference.
在这里,我们用'a
注释r
的生命周期,用'b
注释x
的生命周期。正如您所看到的,内部'b
块比外部'a
生命周期块小得多。在编译时,Rust 比较两个生命周期的大小,发现r
的生命周期为'a
,但它引用的内存的生命周期为'b
。该程序被拒绝,因为'b
比'a
短:引用的主题没有引用那么长。
Listing 10-18 fixes the code so it doesn’t have a dangling reference and it
compiles without any errors.
清单 10-18 修复了代码,因此它没有悬空引用,并且编译时没有任何错误。
fn main() {
let x = 5; // ----------+-- 'b
// |
let r = &x; // --+-- 'a |
// | |
println!("r: {r}"); // | |
// --+ |
} // ----------+
Here, x
has the lifetime 'b
, which in this case is larger than 'a
. This
means r
can reference x
because Rust knows that the reference in r
will
always be valid while x
is valid.
此处, x
的生命周期为'b
,在本例中大于'a
。这意味着r
可以引用x
因为 Rust 知道当x
有效时, r
中的引用将始终有效。
Now that you know what the lifetimes of references are and how Rust analyzes
lifetimes to ensure references will always be valid, let’s explore generic
lifetimes of parameters and return values in the context of functions.
现在您已经了解了引用的生命周期是什么以及 Rust 如何分析生命周期以确保引用始终有效,让我们在函数上下文中探索参数和返回值的通用生命周期。
Generic Lifetimes in Functions
函数中的通用生命周期
We’ll write a function that returns the longer of two string slices. This
function will take two string slices and return a single string slice. After
we’ve implemented the longest
function, the code in Listing 10-19 should
print The longest string is abcd
.
我们将编写一个函数,返回两个字符串切片中较长的一个。该函数将采用两个字符串切片并返回一个字符串切片。在我们实现了longest
函数之后,清单 10-19 中的代码应该打印The longest string is abcd
。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {result}");
}
Note that we want the function to take string slices, which are references,
rather than strings, because we don’t want the longest
function to take
ownership of its parameters. Refer to the “String Slices as
Parameters” section in Chapter 4
for more discussion about why the parameters we use in Listing 10-19 are the
ones we want.
请注意,我们希望函数采用字符串切片,它们是引用,而不是字符串,因为我们不希望longest
函数获得其参数的所有权。请参阅第 4 章中的“字符串切片作为参数”忽略部分,以获取有关为什么清单 10-19 中使用的参数是我们想要的参数的更多讨论。
If we try to implement the longest
function as shown in Listing 10-20, it
won’t compile.
如果我们尝试实现如清单 10-20 所示的longest
函数,它将无法编译。
Filename: src/main.rs 文件名:src/main.rs
Instead, we get the following error that talks about lifetimes:
相反,我们收到以下有关生命周期的错误:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0106]: missing lifetime specifier
--> src/main.rs:9:33
|
9 | fn longest(x: &str, y: &str) -> &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<'a>(x: &'a str, y: &'a str) -> &'a str {
| ++++ ++ ++ ++
error: lifetime may not live long enough
--> src/main.rs:11:9
|
9 | fn longest(x: &str, y: &str) -> &str {
| - let's call the lifetime of this reference `'1`
10 | if x.len() > y.len() {
11 | x
| ^ returning this value requires that `'1` must outlive `'static`
error: lifetime may not live long enough
--> src/main.rs:13:9
|
9 | fn longest(x: &str, y: &str) -> &str {
| - let's call the lifetime of this reference `'2`
...
13 | y
| ^ returning this value requires that `'2` must outlive `'static`
For more information about this error, try `rustc --explain E0106`.
error: could not compile `chapter10` (bin "chapter10") due to 3 previous errors
The help text reveals that the return type needs a generic lifetime parameter
on it because Rust can’t tell whether the reference being returned refers to
x
or y
. Actually, we don’t know either, because the if
block in the body
of this function returns a reference to x
and the else
block returns a
reference to y
!
帮助文本显示返回类型需要一个通用的生命周期参数,因为 Rust 无法判断返回的引用是引用x
还是y
。实际上,我们也不知道,因为该函数体内的if
块返回对x
的引用,而else
块返回对y
的引用!
When we’re defining this function, we don’t know the concrete values that will
be passed into this function, so we don’t know whether the if
case or the
else
case will execute. We also don’t know the concrete lifetimes of the
references that will be passed in, so we can’t look at the scopes as we did in
Listings 10-17 and 10-18 to determine whether the reference we return will
always be valid. The borrow checker can’t determine this either, because it
doesn’t know how the lifetimes of x
and y
relate to the lifetime of the
return value. To fix this error, we’ll add generic lifetime parameters that
define the relationship between the references so the borrow checker can
perform its analysis.
当我们定义这个函数时,我们不知道将传递给这个函数的具体值,因此我们不知道是否会执行if
情况或else
情况。我们也不知道将传入的引用的具体生命周期,因此我们无法像清单 10-17 和 10-18 中那样查看范围来确定我们返回的引用是否始终有效。借用检查器也无法确定这一点,因为它不知道x
和y
的生命周期与返回值的生命周期有何关系。为了修复此错误,我们将添加定义引用之间关系的通用生命周期参数,以便借用检查器可以执行其分析。
Lifetime Annotation Syntax
生命周期注释语法
Lifetime annotations don’t change how long any of the references live. Rather,
they describe the relationships of the lifetimes of multiple references to each
other without affecting the lifetimes. Just as functions can accept any type
when the signature specifies a generic type parameter, functions can accept
references with any lifetime by specifying a generic lifetime parameter.
生命周期注释不会改变任何引用的生存时间。相反,它们描述了多个引用的生命周期相互之间的关系,而不影响生命周期。正如当签名指定泛型类型参数时函数可以接受任何类型一样,函数可以通过指定泛型生存期参数来接受具有任何生存期的引用。
Lifetime annotations have a slightly unusual syntax: the names of lifetime
parameters must start with an apostrophe ('
) and are usually all lowercase
and very short, like generic types. Most people use the name 'a
for the first
lifetime annotation. We place lifetime parameter annotations after the &
of a
reference, using a space to separate the annotation from the reference’s type.
生命周期注释的语法有点不寻常:生命周期参数的名称必须以撇号( '
)开头,并且通常都是小写且非常短,就像泛型类型一样。大多数人使用名称'a
作为第一个生命周期注释。我们将生命周期参数注释放在引用的&
之后,使用空格将注释与引用的类型分开。
Here are some examples: a reference to an i32
without a lifetime parameter, a
reference to an i32
that has a lifetime parameter named 'a
, and a mutable
reference to an i32
that also has the lifetime 'a
.
以下是一些示例:对没有生命周期参数的i32
的引用、对具有名为'a
生命周期参数的i32
的引用,以及对也具有生命周期'a
的i32
的可变引用。
&i32 // a reference
&'a i32 // a reference with an explicit lifetime
&'a mut i32 // a mutable reference with an explicit lifetime
One lifetime annotation by itself doesn’t have much meaning because the
annotations are meant to tell Rust how generic lifetime parameters of multiple
references relate to each other. Let’s examine how the lifetime annotations
relate to each other in the context of the longest
function.
一个生命周期注释本身并没有多大意义,因为注释的目的是告诉 Rust 多个引用的通用生命周期参数如何相互关联。让我们检查一下生命周期注释在longest
函数的上下文中如何相互关联。
Lifetime Annotations in Function Signatures
函数签名中的生命周期注释
To use lifetime annotations in function signatures, we need to declare the
generic lifetime parameters inside angle brackets between the function name
and the parameter list, just as we did with generic type parameters.
要在函数签名中使用生命周期注释,我们需要在函数名称和参数列表之间的尖括号内声明通用生命周期参数,就像我们对通用类型参数所做的那样。
We want the signature to express the following constraint: the returned
reference will be valid as long as both the parameters are valid. This is the
relationship between lifetimes of the parameters and the return value. We’ll
name the lifetime 'a
and then add it to each reference, as shown in Listing
10-21.
我们希望签名表达以下约束:只要两个参数都有效,返回的引用就有效。这就是参数的生命周期和返回值之间的关系。我们将生命周期命名为'a
,然后将其添加到每个引用中,如清单 10-21 所示。
Filename: src/main.rs 文件名:src/main.rs
This code should compile and produce the result we want when we use it with the
main
function in Listing 10-19.
当我们将这段代码与清单 10-19 中的main
函数一起使用时,它应该可以编译并产生我们想要的结果。
The function signature now tells Rust that for some lifetime 'a
, the function
takes two parameters, both of which are string slices that live at least as
long as lifetime 'a
. The function signature also tells Rust that the string
slice returned from the function will live at least as long as lifetime 'a
.
In practice, it means that the lifetime of the reference returned by the
longest
function is the same as the smaller of the lifetimes of the values
referred to by the function arguments. These relationships are what we want
Rust to use when analyzing this code.
函数签名现在告诉 Rust,对于某个生命周期'a
,该函数采用两个参数,这两个参数都是字符串切片,其生命周期至少与生命周期'a
一样长。函数签名还告诉 Rust,从函数返回的字符串切片的生存期至少与生命周期'a
一样长。实际上,这意味着longest
函数返回的引用的生命周期与函数参数引用的值的较小生命周期相同。这些关系是我们希望 Rust 在分析这段代码时使用的。
Remember, when we specify the lifetime parameters in this function signature,
we’re not changing the lifetimes of any values passed in or returned. Rather,
we’re specifying that the borrow checker should reject any values that don’t
adhere to these constraints. Note that the longest
function doesn’t need to
know exactly how long x
and y
will live, only that some scope can be
substituted for 'a
that will satisfy this signature.
请记住,当我们在此函数签名中指定生命周期参数时,我们不会更改传入或返回的任何值的生命周期。相反,我们指定借用检查器应拒绝任何不遵守这些约束的值。请注意, longest
函数不需要确切地知道x
和y
生存时间,只需用某个作用域替换'a
即可满足此签名。
When annotating lifetimes in functions, the annotations go in the function
signature, not in the function body. The lifetime annotations become part of
the contract of the function, much like the types in the signature. Having
function signatures contain the lifetime contract means the analysis the Rust
compiler does can be simpler. If there’s a problem with the way a function is
annotated or the way it is called, the compiler errors can point to the part of
our code and the constraints more precisely. If, instead, the Rust compiler
made more inferences about what we intended the relationships of the lifetimes
to be, the compiler might only be able to point to a use of our code many steps
away from the cause of the problem.
在函数中注释生命周期时,注释位于函数签名中,而不是函数主体中。生命周期注释成为函数契约的一部分,就像签名中的类型一样。让函数签名包含生命周期契约意味着 Rust 编译器所做的分析可以更简单。如果函数的注释方式或调用方式存在问题,编译器错误可以更准确地指出我们的代码部分和约束。相反,如果 Rust 编译器对我们想要的生命周期关系进行更多推断,则编译器可能只能指出我们代码的使用情况与问题原因相差很多步。
When we pass concrete references to longest
, the concrete lifetime that is
substituted for 'a
is the part of the scope of x
that overlaps with the
scope of y
. In other words, the generic lifetime 'a
will get the concrete
lifetime that is equal to the smaller of the lifetimes of x
and y
. Because
we’ve annotated the returned reference with the same lifetime parameter 'a
,
the returned reference will also be valid for the length of the smaller of the
lifetimes of x
and y
.
当我们传递对longest
具体引用时,替换'a
的具体生命周期是x
范围与y
范围重叠的部分。换句话说,通用生命周期'a
将获得等于x
和y
生命周期中较小者的具体生命周期。因为我们使用相同的生命周期参数'a
注释了返回的引用,所以返回的引用对于x
和y
生命周期中较小者的长度也有效。
Let’s look at how the lifetime annotations restrict the longest
function by
passing in references that have different concrete lifetimes. Listing 10-22 is
a straightforward example.
我们来看看生命周期注解是如何通过传入具有不同具体生命周期的引用来限制longest
函数的。清单 10-22 是一个简单的示例。
Filename: src/main.rs 文件名:src/main.rs
In this example, string1
is valid until the end of the outer scope, string2
is valid until the end of the inner scope, and result
references something
that is valid until the end of the inner scope. Run this code and you’ll see
that the borrow checker approves; it will compile and print The longest string is long string is long
.
在此示例中, string1
在外部作用域结束之前有效, string2
在内部作用域结束之前有效,而result
引用在内部作用域结束之前有效的内容。运行此代码,您将看到借用检查器已批准;它将编译并打印The longest string is long string is long
。
Next, let’s try an example that shows that the lifetime of the reference in
result
must be the smaller lifetime of the two arguments. We’ll move the
declaration of the result
variable outside the inner scope but leave the
assignment of the value to the result
variable inside the scope with
string2
. Then we’ll move the println!
that uses result
to outside the
inner scope, after the inner scope has ended. The code in Listing 10-23 will
not compile.
接下来,让我们尝试一个示例,该示例显示result
中引用的生命周期必须是两个参数中较小的生命周期。我们将把result
变量的声明移到内部作用域之外,但将值分配给string2
作用域内的result
变量。然后我们将移动println!
在内部作用域结束后,将result
用于内部作用域之外。清单 10-23 中的代码将无法编译。
Filename: src/main.rs 文件名:src/main.rs
When we try to compile this code, we get this error:
当我们尝试编译此代码时,我们收到此错误:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `string2` does not live long enough
--> 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
The error shows that for result
to be valid for the println!
statement,
string2
would need to be valid until the end of the outer scope. Rust knows
this because we annotated the lifetimes of the function parameters and return
values using the same lifetime parameter 'a
.
该错误表明result
对于println!
有效。语句中, string2
需要在外部作用域结束之前保持有效。 Rust 知道这一点,因为我们使用相同的生命周期参数'a
注释了函数参数和返回值的生命周期。
As humans, we can look at this code and see that string1
is longer than
string2
, and therefore, result
will contain a reference to string1
.
Because string1
has not gone out of scope yet, a reference to string1
will
still be valid for the println!
statement. However, the compiler can’t see
that the reference is valid in this case. We’ve told Rust that the lifetime of
the reference returned by the longest
function is the same as the smaller of
the lifetimes of the references passed in. Therefore, the borrow checker
disallows the code in Listing 10-23 as possibly having an invalid reference.
作为人类,我们可以查看这段代码,发现string1
比string2
长,因此result
将包含对string1
的引用。因为string1
尚未超出范围,所以对string1
的引用对于println!
陈述。但是,在这种情况下,编译器无法看到引用是否有效。我们已经告诉 Rust, longest
函数返回的引用的生命周期与传入引用的生命周期中较小的一个相同。因此,借用检查器不允许清单 10-23 中的代码可能具有无效引用。
Try designing more experiments that vary the values and lifetimes of the
references passed in to the longest
function and how the returned reference
is used. Make hypotheses about whether or not your experiments will pass the
borrow checker before you compile; then check to see if you’re right!
尝试设计更多实验来改变传递给longest
函数的引用的值和生命周期以及如何使用返回的引用。在编译之前假设你的实验是否会通过借用检查器;然后检查一下你是否正确!
Thinking in Terms of Lifetimes
从生命的角度思考
The way in which you need to specify lifetime parameters depends on what your
function is doing. For example, if we changed the implementation of the
longest
function to always return the first parameter rather than the longest
string slice, we wouldn’t need to specify a lifetime on the y
parameter. The
following code will compile:
您需要指定生命周期参数的方式取决于您的函数正在执行的操作。例如,如果我们将longest
函数的实现更改为始终返回第一个参数而不是最长的字符串切片,则不需要在y
参数上指定生命周期。以下代码将编译:
Filename: src/main.rs 文件名:src/main.rs
We’ve specified a lifetime parameter 'a
for the parameter x
and the return
type, but not for the parameter y
, because the lifetime of y
does not have
any relationship with the lifetime of x
or the return value.
我们为参数x
和返回类型指定了生命周期参数'a
,但没有为参数y
指定,因为y
的生命周期与x
或返回值的生命周期没有任何关系。
When returning a reference from a function, the lifetime parameter for the
return type needs to match the lifetime parameter for one of the parameters. If
the reference returned does not refer to one of the parameters, it must refer
to a value created within this function. However, this would be a dangling
reference because the value will go out of scope at the end of the function.
Consider this attempted implementation of the longest
function that won’t
compile:
从函数返回引用时,返回类型的生命周期参数需要与参数之一的生命周期参数匹配。如果返回的引用不引用参数之一,则它必须引用在此函数中创建的值。但是,这将是一个悬空引用,因为该值将在函数末尾超出范围。考虑一下无法编译的longest
函数的尝试实现:
Filename: src/main.rs 文件名:src/main.rs
Here, even though we’ve specified a lifetime parameter 'a
for the return
type, this implementation will fail to compile because the return value
lifetime is not related to the lifetime of the parameters at all. Here is the
error message we get:
在这里,即使我们为返回类型指定了生命周期参数'a
,该实现也将无法编译,因为返回值生命周期与参数的生命周期根本无关。这是我们收到的错误消息:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0515]: cannot return value referencing local variable `result`
--> 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
The problem is that result
goes out of scope and gets cleaned up at the end
of the longest
function. We’re also trying to return a reference to result
from the function. There is no way we can specify lifetime parameters that
would change the dangling reference, and Rust won’t let us create a dangling
reference. In this case, the best fix would be to return an owned data type
rather than a reference so the calling function is then responsible for
cleaning up the value.
问题是result
超出范围并在longest
函数结束时被清除。我们还尝试返回对函数result
的引用。我们无法指定会更改悬空引用的生命周期参数,并且 Rust 不允许我们创建悬空引用。在这种情况下,最好的解决方法是返回拥有的数据类型而不是引用,以便调用函数负责清理该值。
Ultimately, lifetime syntax is about connecting the lifetimes of various
parameters and return values of functions. Once they’re connected, Rust has
enough information to allow memory-safe operations and disallow operations that
would create dangling pointers or otherwise violate memory safety.
最终,生命周期语法是关于连接函数的各种参数和返回值的生命周期。一旦它们连接起来,Rust 就有足够的信息来允许内存安全操作并禁止会创建悬空指针或以其他方式违反内存安全的操作。
Lifetime Annotations in Struct Definitions
结构定义中的生命周期注释
So far, the structs we’ve defined all hold owned types. We can define structs
to hold references, but in that case we would need to add a lifetime annotation
on every reference in the struct’s definition. Listing 10-24 has a struct named
ImportantExcerpt
that holds a string slice.
到目前为止,我们定义的结构体都拥有自有类型。我们可以定义结构体来保存引用,但在这种情况下,我们需要在结构体定义中的每个引用上添加生命周期注释。清单10-24有一个名为ImportantExcerpt
的结构体,它保存一个字符串切片。
Filename: src/main.rs 文件名:src/main.rs
struct ImportantExcerpt<'a> {
part: &'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,
};
}
This struct has the single field part
that holds a string slice, which is a
reference. As with generic data types, we declare the name of the generic
lifetime parameter inside angle brackets after the name of the struct so we can
use the lifetime parameter in the body of the struct definition. This
annotation means an instance of ImportantExcerpt
can’t outlive the reference
it holds in its part
field.
该结构具有包含字符串切片的单个字段part
,该字符串切片是一个引用。与通用数据类型一样,我们在结构名称后面的尖括号内声明通用生命周期参数的名称,以便我们可以在结构定义主体中使用生命周期参数。此注释意味着ImportantExcerpt
的实例不能比它在其part
字段中保存的引用寿命更长。
The main
function here creates an instance of the ImportantExcerpt
struct
that holds a reference to the first sentence of the String
owned by the
variable novel
. The data in novel
exists before the ImportantExcerpt
instance is created. In addition, novel
doesn’t go out of scope until after
the ImportantExcerpt
goes out of scope, so the reference in the
ImportantExcerpt
instance is valid.
这里的main
函数创建了一个ImportantExcerpt
结构体的实例,它保存了对变量novel
所拥有的String
的第一句话的引用。 novel
中的数据在创建ImportantExcerpt
实例之前就已存在。此外,在ImportantExcerpt
超出范围之前, novel
不会超出范围,因此ImportantExcerpt
实例中的引用是有效的。
Lifetime Elision 终身消除
You’ve learned that every reference has a lifetime and that you need to specify
lifetime parameters for functions or structs that use references. However, we
had a function in Listing 4-9, shown again in Listing 10-25, that compiled
without lifetime annotations.
您已经了解到每个引用都有一个生命周期,并且您需要为使用引用的函数或结构指定生命周期参数。然而,我们在清单 4-9 中有一个函数(在清单 10-25 中再次显示),它在编译时没有使用生命周期注释。
Filename: src/lib.rs 文件名:src/lib.rs
The reason this function compiles without lifetime annotations is historical:
in early versions (pre-1.0) of Rust, this code wouldn’t have compiled because
every reference needed an explicit lifetime. At that time, the function
signature would have been written like this:
这个函数在没有生命周期注释的情况下编译的原因是历史性的:在 Rust 的早期版本(1.0 之前)中,这个代码不会被编译,因为每个引用都需要一个显式的生命周期。那时,函数签名会这样写:
fn first_word<'a>(s: &'a str) -> &'a str {
After writing a lot of Rust code, the Rust team found that Rust programmers
were entering the same lifetime annotations over and over in particular
situations. These situations were predictable and followed a few deterministic
patterns. The developers programmed these patterns into the compiler’s code so
the borrow checker could infer the lifetimes in these situations and wouldn’t
need explicit annotations.
在编写大量 Rust 代码后,Rust 团队发现 Rust 程序员在特定情况下一遍又一遍地输入相同的生命周期注释。这些情况是可以预测的,并且遵循一些确定性模式。开发人员将这些模式编程到编译器的代码中,以便借用检查器可以推断这些情况下的生命周期,并且不需要显式注释。
This piece of Rust history is relevant because it’s possible that more
deterministic patterns will emerge and be added to the compiler. In the future,
even fewer lifetime annotations might be required.
Rust 的这段历史是相关的,因为更多确定性模式可能会出现并被添加到编译器中。将来,可能需要更少的生命周期注释。
The patterns programmed into Rust’s analysis of references are called the
lifetime elision rules. These aren’t rules for programmers to follow; they’re
a set of particular cases that the compiler will consider, and if your code
fits these cases, you don’t need to write the lifetimes explicitly.
编程到 Rust 引用分析中的模式称为生命周期省略规则。这些不是程序员必须遵守的规则;而是程序员必须遵循的规则。它们是编译器将考虑的一组特殊情况,如果您的代码适合这些情况,则无需显式编写生命周期。
The elision rules don’t provide full inference. If there is still ambiguity as
to what lifetimes the references have after Rust applies the rules, the
compiler won’t guess what the lifetime of the remaining references should be.
Instead of guessing, the compiler will give you an error that you can resolve
by adding the lifetime annotations.
省略规则不提供完整的推理。如果 Rust 应用规则后引用的生命周期仍然不明确,编译器将不会猜测其余引用的生命周期应该是多少。编译器不会猜测,而是会给您一个错误,您可以通过添加生命周期注释来解决该错误。
Lifetimes on function or method parameters are called input lifetimes, and
lifetimes on return values are called output lifetimes.
函数或方法参数的生命周期称为输入生命周期,返回值的生命周期称为输出生命周期。
The compiler uses three rules to figure out the lifetimes of the references
when there aren’t explicit annotations. The first rule applies to input
lifetimes, and the second and third rules apply to output lifetimes. If the
compiler gets to the end of the three rules and there are still references for
which it can’t figure out lifetimes, the compiler will stop with an error.
These rules apply to fn
definitions as well as impl
blocks.
当没有显式注释时,编译器使用三个规则来计算引用的生命周期。第一个规则适用于输入生命周期,第二个和第三个规则适用于输出生命周期。如果编译器到达三个规则的末尾并且仍然存在无法计算出生命周期的引用,则编译器将因错误而停止。这些规则适用于fn
定义以及impl
块。
The first rule is that the compiler assigns a lifetime parameter to each
parameter that’s a reference. In other words, a function with one parameter
gets one lifetime parameter: fn foo<'a>(x: &'a i32)
; a function with two
parameters gets two separate lifetime parameters: fn foo<'a, 'b>(x: &'a i32, y: &'b i32)
; and so on.
第一条规则是编译器为每个引用参数分配一个生命周期参数。换句话说,具有一个参数的函数获得一个生命周期参数: fn foo<'a>(x: &'a i32)
;具有两个参数的函数获得两个单独的生命周期参数: fn foo<'a, 'b>(x: &'a i32, y: &'b i32)
;等等。
The second rule is that, if there is exactly one input lifetime parameter, that
lifetime is assigned to all output lifetime parameters: fn foo<'a>(x: &'a i32) -> &'a i32
.
第二条规则是,如果只有一个输入生命周期参数,则该生命周期将分配给所有输出生命周期参数: fn foo<'a>(x: &'a i32) -> &'a i32
。
The third rule is that, if there are multiple input lifetime parameters, but
one of them is &self
or &mut self
because this is a method, the lifetime of
self
is assigned to all output lifetime parameters. This third rule makes
methods much nicer to read and write because fewer symbols are necessary.
第三条规则是,如果有多个输入生命周期参数,但其中一个是&self
或&mut self
因为这是一种方法,则self
的生命周期将分配给所有输出生命周期参数。第三条规则使方法更易于读写,因为所需的符号更少。
Let’s pretend we’re the compiler. We’ll apply these rules to figure out the
lifetimes of the references in the signature of the first_word
function in
Listing 10-25. The signature starts without any lifetimes associated with the
references:
让我们假设我们是编译器。我们将应用这些规则来计算清单 10-25 中的first_word
函数签名中引用的生命周期。签名开始时没有与引用关联的任何生命周期:
fn first_word(s: &str) -> &str {
Then the compiler applies the first rule, which specifies that each parameter
gets its own lifetime. We’ll call it 'a
as usual, so now the signature is
this:
然后编译器应用第一条规则,该规则指定每个参数都有自己的生命周期。我们将像往常一样将其称为'a
,所以现在签名是这样的:
fn first_word<'a>(s: &'a str) -> &str {
The second rule applies because there is exactly one input lifetime. The second
rule specifies that the lifetime of the one input parameter gets assigned to
the output lifetime, so the signature is now this:
应用第二条规则是因为只有一个输入生命周期。第二条规则指定将一个输入参数的生命周期分配给输出生命周期,因此签名现在是这样的:
fn first_word<'a>(s: &'a str) -> &'a str {
Now all the references in this function signature have lifetimes, and the
compiler can continue its analysis without needing the programmer to annotate
the lifetimes in this function signature.
现在这个函数签名中的所有引用都有了生命周期,编译器可以继续分析,而不需要程序员在这个函数签名中注释生命周期。
Let’s look at another example, this time using the longest
function that had
no lifetime parameters when we started working with it in Listing 10-20:
让我们看另一个例子,这次使用的是longest
函数,当我们开始使用它时,它没有生命周期参数,如清单 10-20 所示:
fn longest(x: &str, y: &str) -> &str {
Let’s apply the first rule: each parameter gets its own lifetime. This time we
have two parameters instead of one, so we have two lifetimes:
让我们应用第一条规则:每个参数都有自己的生命周期。这次我们有两个参数而不是一个,所以我们有两个生命周期:
fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str {
You can see that the second rule doesn’t apply because there is more than one
input lifetime. The third rule doesn’t apply either, because longest
is a
function rather than a method, so none of the parameters are self
. After
working through all three rules, we still haven’t figured out what the return
type’s lifetime is. This is why we got an error trying to compile the code in
Listing 10-20: the compiler worked through the lifetime elision rules but still
couldn’t figure out all the lifetimes of the references in the signature.
您可以看到第二条规则不适用,因为存在多个输入生命周期。第三条规则也不适用,因为longest
是一个函数而不是一个方法,所以没有一个参数是self
。在完成所有三个规则之后,我们仍然没有弄清楚返回类型的生命周期是什么。这就是为什么我们在尝试编译清单 10-20 中的代码时遇到错误:编译器执行了生命周期省略规则,但仍然无法找出签名中引用的所有生命周期。
Because the third rule really only applies in method signatures, we’ll look at
lifetimes in that context next to see why the third rule means we don’t have to
annotate lifetimes in method signatures very often.
因为第三条规则实际上只适用于方法签名,所以接下来我们将在该上下文中查看生命周期,以了解为什么第三条规则意味着我们不必经常在方法签名中注释生命周期。
Lifetime Annotations in Method Definitions
方法定义中的生命周期注释
When we implement methods on a struct with lifetimes, we use the same syntax as
that of generic type parameters shown in Listing 10-11. Where we declare and
use the lifetime parameters depends on whether they’re related to the struct
fields or the method parameters and return values.
当我们在具有生命周期的结构上实现方法时,我们使用与清单 10-11 中所示的泛型类型参数相同的语法。我们在哪里声明和使用生命周期参数取决于它们是否与结构体字段或方法参数和返回值相关。
Lifetime names for struct fields always need to be declared after the impl
keyword and then used after the struct’s name because those lifetimes are part
of the struct’s type.
结构体字段的生命周期名称始终需要在impl
关键字之后声明,然后在结构体名称之后使用,因为这些生命周期是结构体类型的一部分。
In method signatures inside the impl
block, references might be tied to the
lifetime of references in the struct’s fields, or they might be independent. In
addition, the lifetime elision rules often make it so that lifetime annotations
aren’t necessary in method signatures. Let’s look at some examples using the
struct named ImportantExcerpt
that we defined in Listing 10-24.
在impl
块内的方法签名中,引用可能与结构字段中引用的生命周期相关联,也可能是独立的。此外,生命周期省略规则通常使得方法签名中不需要生命周期注释。让我们看一些使用清单 10-24 中定义的名为ImportantExcerpt
的结构的示例。
First we’ll use a method named level
whose only parameter is a reference to
self
and whose return value is an i32
, which is not a reference to anything:
首先,我们将使用一个名为level
方法,其唯一参数是对self
的引用,其返回值是i32
,它不是对任何内容的引用:
The lifetime parameter declaration after impl
and its use after the type name
are required, but we’re not required to annotate the lifetime of the reference
to self
because of the first elision rule.impl
之后的生命周期参数声明及其在类型名称之后的使用是必需的,但由于第一个省略规则,我们不需要注释对self
的引用的生命周期。
Here is an example where the third lifetime elision rule applies:
以下是应用第三生命周期省略规则的示例:
There are two input lifetimes, so Rust applies the first lifetime elision rule
and gives both &self
and announcement
their own lifetimes. Then, because
one of the parameters is &self
, the return type gets the lifetime of &self
,
and all lifetimes have been accounted for.
有两个输入生命周期,因此 Rust 应用第一个生命周期省略规则,并为&self
和announcement
赋予它们自己的生命周期。然后,因为参数之一是&self
,所以返回类型获取&self
的生命周期,并且所有生命周期都已被考虑在内。
The Static Lifetime 静态寿命
One special lifetime we need to discuss is 'static
, which denotes that the
affected reference can live for the entire duration of the program. All
string literals have the 'static
lifetime, which we can annotate as follows:
我们需要讨论的一个特殊生命周期是'static
,它表示受影响的引用可以在程序的整个持续时间内生存。所有字符串文字都有'static
生命周期,我们可以将其注释如下:
The text of this string is stored directly in the program’s binary, which is
always available. Therefore, the lifetime of all string literals is 'static
.
该字符串的文本直接存储在程序的二进制文件中,该二进制文件始终可用。因此,所有字符串文字的生命周期都是'static
。
You might see suggestions to use the 'static
lifetime in error messages. But
before specifying 'static
as the lifetime for a reference, think about
whether the reference you have actually lives the entire lifetime of your
program or not, and whether you want it to. Most of the time, an error message
suggesting the 'static
lifetime results from attempting to create a dangling
reference or a mismatch of the available lifetimes. In such cases, the solution
is to fix those problems, not to specify the 'static
lifetime.
您可能会在错误消息中看到使用'static
生命周期”的建议。但在指定'static
作为引用的生命周期之前,请考虑您所拥有的引用是否实际上存在于程序的整个生命周期中,以及您是否希望它如此。大多数时候,提示'static
生命周期”的错误消息是由于尝试创建悬空引用或可用生命周期不匹配而导致的。在这种情况下,解决方案是解决这些问题,而不是指定'static
生命周期”。
Generic Type Parameters, Trait Bounds, and Lifetimes Together
通用类型参数、特征界限和生命周期
Let’s briefly look at the syntax of specifying generic type parameters, trait
bounds, and lifetimes all in one function!
让我们简要地看一下在一个函数中指定泛型类型参数、特征边界和生命周期的语法!
This is the longest
function from Listing 10-21 that returns the longer of
two string slices. But now it has an extra parameter named ann
of the generic
type T
, which can be filled in by any type that implements the Display
trait as specified by the where
clause. This extra parameter will be printed
using {}
, which is why the Display
trait bound is necessary. Because
lifetimes are a type of generic, the declarations of the lifetime parameter
'a
and the generic type parameter T
go in the same list inside the angle
brackets after the function name.
这是清单 10-21 中longest
函数,它返回两个字符串切片中较长的一个。但现在它有一个名为ann
的泛型类型T
的额外参数,该参数可以由任何实现where
子句指定的Display
特征的类型填充。这个额外的参数将使用{}
打印,这就是为什么Display
特征绑定是必要的。因为生命周期是泛型类型,所以生命周期参数'a
和泛型类型参数T
的声明位于函数名称后面的尖括号内的同一列表中。
Summary 概括
We covered a lot in this chapter! Now that you know about generic type
parameters, traits and trait bounds, and generic lifetime parameters, you’re
ready to write code without repetition that works in many different situations.
Generic type parameters let you apply the code to different types. Traits and
trait bounds ensure that even though the types are generic, they’ll have the
behavior the code needs. You learned how to use lifetime annotations to ensure
that this flexible code won’t have any dangling references. And all of this
analysis happens at compile time, which doesn’t affect runtime performance!
我们在本章中介绍了很多内容!现在您已经了解了泛型类型参数、特征和特征边界以及泛型生命周期参数,您就可以编写无需重复且适用于许多不同情况的代码了。通用类型参数允许您将代码应用于不同的类型。特征和特征边界确保即使类型是通用的,它们也将具有代码所需的行为。您学习了如何使用生命周期注释来确保此灵活的代码不会有任何悬空引用。所有这些分析都发生在编译时,这不会影响运行时性能!
Believe it or not, there is much more to learn on the topics we discussed in
this chapter: Chapter 17 discusses trait objects, which are another way to use
traits. There are also more complex scenarios involving lifetime annotations
that you will only need in very advanced scenarios; for those, you should read
the Rust Reference. But next, you’ll learn how to write tests in
Rust so you can make sure your code is working the way it should.
不管你相信与否,关于我们在本章中讨论的主题,还有很多东西需要学习:第 17 章讨论了特征对象,这是使用特征的另一种方式。还有一些更复杂的场景涉及生命周期注释,只有在非常高级的场景中才需要它们;对于这些,您应该阅读Rust 参考。但接下来,您将学习如何用 Rust 编写测试,以便确保您的代码按应有的方式工作。
Writing Automated Tests 编写自动化测试
In his 1972 essay “The Humble Programmer,” Edsger W. Dijkstra said that
“Program testing can be a very effective way to show the presence of bugs, but
it is hopelessly inadequate for showing their absence.” That doesn’t mean we
shouldn’t try to test as much as we can!
Edsger W. Dijkstra 在他 1972 年的文章“谦虚的程序员”中说,“程序测试可以是显示错误存在的非常有效的方法,但它完全不足以显示错误的存在。”这并不意味着我们不应该尝试尽可能多地进行测试!
Correctness in our programs is the extent to which our code does what we intend
it to do. Rust is designed with a high degree of concern about the correctness
of programs, but correctness is complex and not easy to prove. Rust’s type
system shoulders a huge part of this burden, but the type system cannot catch
everything. As such, Rust includes support for writing automated software tests.
程序的正确性是指我们的代码执行我们想要执行的操作的程度。 Rust 的设计高度关注程序的正确性,但正确性很复杂且不易证明。 Rust 的类型系统承担了这一负担的很大一部分,但类型系统无法捕获所有内容。因此,Rust 支持编写自动化软件测试。
Say we write a function add_two
that adds 2 to whatever number is passed to
it. This function’s signature accepts an integer as a parameter and returns an
integer as a result. When we implement and compile that function, Rust does all
the type checking and borrow checking that you’ve learned so far to ensure
that, for instance, we aren’t passing a String
value or an invalid reference
to this function. But Rust can’t check that this function will do precisely
what we intend, which is return the parameter plus 2 rather than, say, the
parameter plus 10 or the parameter minus 50! That’s where tests come in.
假设我们编写了一个函数add_two
,它将 2 与传递给它的任何数字相加。该函数的签名接受一个整数作为参数并返回一个整数作为结果。当我们实现和编译该函数时,Rust 会执行您迄今为止学到的所有类型检查和借用检查,以确保我们不会传递String
值或对此函数的无效引用。但是 Rust无法检查这个函数是否会精确地执行我们想要的操作,即返回参数加 2,而不是参数加 10 或参数减 50!这就是测试发挥作用的地方。
We can write tests that assert, for example, that when we pass 3
to the
add_two
function, the returned value is 5
. We can run these tests whenever
we make changes to our code to make sure any existing correct behavior has not
changed.
我们可以编写测试来断言,例如,当我们将3
传递给add_two
函数时,返回值为5
。每当我们更改代码时,我们都可以运行这些测试,以确保任何现有的正确行为没有改变。
Testing is a complex skill: although we can’t cover every detail about how to
write good tests in one chapter, we’ll discuss the mechanics of Rust’s testing
facilities. We’ll talk about the annotations and macros available to you when
writing your tests, the default behavior and options provided for running your
tests, and how to organize tests into unit tests and integration tests.
测试是一项复杂的技能:虽然我们无法在一章中涵盖如何编写良好测试的所有细节,但我们将讨论 Rust 测试工具的机制。我们将讨论编写测试时可用的注释和宏、为运行测试提供的默认行为和选项,以及如何将测试组织为单元测试和集成测试。
How to Write Tests 如何编写测试
Tests are Rust functions that verify that the non-test code is functioning in
the expected manner. The bodies of test functions typically perform these three
actions:
测试是 Rust 函数,用于验证非测试代码是否按预期方式运行。测试函数体通常执行以下三个操作:
- Set up any needed data or state.
设置任何需要的数据或状态。 - Run the code you want to test.
运行您想要测试的代码。 - Assert the results are what you expect.
断言结果是您所期望的。
Let’s look at the features Rust provides specifically for writing tests that
take these actions, which include the test
attribute, a few macros, and the
should_panic
attribute.
让我们看一下 Rust 专门为编写执行这些操作的测试而提供的功能,其中包括test
属性、一些宏和should_panic
属性。
The Anatomy of a Test Function
测试函数的剖析
At its simplest, a test in Rust is a function that’s annotated with the test
attribute. Attributes are metadata about pieces of Rust code; one example is
the derive
attribute we used with structs in Chapter 5. To change a function
into a test function, add #[test]
on the line before fn
. When you run your
tests with the cargo test
command, Rust builds a test runner binary that runs
the annotated functions and reports on whether each
test function passes or fails.
最简单的是,Rust 中的测试是一个用test
属性注释的函数。属性是有关 Rust 代码片段的元数据;一个例子是我们在第 5 章中与结构一起使用的derive
属性。要将函数更改为测试函数,请在fn
之前的行中添加#[test]
。当您使用cargo test
命令运行测试时,Rust 会构建一个测试运行程序二进制文件,该二进制文件运行带注释的函数并报告每个测试函数是否通过或失败。
Whenever we make a new library project with Cargo, a test module with a test
function in it is automatically generated for us. This module gives you a
template for writing your tests so you don’t have to look up the exact
structure and syntax every time you start a new project. You can add as many
additional test functions and as many test modules as you want!
每当我们使用 Cargo 创建一个新的库项目时,都会自动为我们生成一个包含测试函数的测试模块。该模块为您提供了一个用于编写测试的模板,因此您不必在每次开始新项目时查找确切的结构和语法。您可以根据需要添加任意数量的附加测试功能和测试模块!
We’ll explore some aspects of how tests work by experimenting with the template
test before we actually test any code. Then we’ll write some real-world tests
that call some code that we’ve written and assert that its behavior is correct.
在实际测试任何代码之前,我们将通过试验模板测试来探索测试如何工作的某些方面。然后我们将编写一些现实世界的测试,调用我们编写的一些代码并断言其行为是正确的。
Let’s create a new library project called adder
that will add two numbers:
让我们创建一个名为adder
的新库项目,它将两个数字相加:
$ cargo new adder --lib
Created library `adder` project
$ cd adder
The contents of the src/lib.rs file in your adder
library should look like
Listing 11-1.adder
库中src/lib.rs文件的内容应如清单 11-1 所示。
Filename: src/lib.rs 文件名:src/lib.rs
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
For now, let’s focus solely on the it_works()
function. Note the
#[test]
annotation: this attribute indicates this is a test function, so the
test runner knows to treat this function as a test. We might also have non-test
functions in the tests
module to help set up common scenarios or perform
common operations, so we always need to indicate which functions are tests.
现在,我们只关注it_works()
函数。请注意#[test]
注释:此属性表明这是一个测试函数,因此测试运行者知道将此函数视为测试。我们还可能在tests
模块中包含非测试函数来帮助设置常见场景或执行常见操作,因此我们始终需要指示哪些函数是测试。
The example function body uses the assert_eq!
macro to assert that result
,
which contains the result of adding 2 and 2, equals 4. This assertion serves as
an example of the format for a typical test. Let’s run it to see that this test
passes.
示例函数体使用了assert_eq!
宏来断言result
,其中包含 2 和 2 相加的结果等于 4。此断言充当典型测试的格式示例。让我们运行一下看看这个测试是否通过。
The cargo test
command runs all tests in our project, as shown in Listing
11-2.cargo test
命令运行项目中的所有测试,如清单 11-2 所示。
$ 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
Cargo compiled and ran the test. We see the line running 1 test
. The next
line shows the name of the generated test function, called it_works
, and that
the result of running that test is ok
. The overall summary test result: ok.
means that all the tests passed, and the portion that reads 1 passed; 0 failed
totals the number of tests that passed or failed.
Cargo 编译并运行了测试。我们看到该行running 1 test
。下一行显示生成的测试函数的名称,称为it_works
,并且运行该测试的结果是ok
。总体总结test result: ok.
表示所有测试都通过了,读为1 passed; 0 failed
是通过或失败的测试总数。
It’s possible to mark a test as ignored so it doesn’t run in a particular
instance; we’ll cover that in the “Ignoring Some Tests Unless Specifically
Requested” section later in this chapter. Because we
haven’t done that here, the summary shows 0 ignored
. We can also pass an
argument to the cargo test
command to run only tests whose name matches a
string; this is called filtering and we’ll cover that in the “Running a
Subset of Tests by Name” section. We also haven’t
filtered the tests being run, so the end of the summary shows 0 filtered out
.
可以将测试标记为忽略,这样它就不会在特定实例中运行;我们将在本章后面的“忽略一些测试,除非特别要求”中介绍这一点。因为我们没有在这里这样做,所以摘要显示0 ignored
。我们还可以将参数传递给cargo test
命令,以仅运行名称与字符串匹配的测试;这称为过滤,我们将在“按名称运行测试子集”忽略部分中介绍它。我们还没有过滤正在运行的测试,因此摘要的末尾显示0 filtered out
。
The 0 measured
statistic is for benchmark tests that measure performance.
Benchmark tests are, as of this writing, only available in nightly Rust. See
the documentation about benchmark tests to learn more.0 measured
统计数据用于衡量性能的基准测试。截至撰写本文时,基准测试仅在夜间 Rust 中可用。请参阅有关基准测试的文档以了解更多信息。
The next part of the test output starting at Doc-tests adder
is for the
results of any documentation tests. We don’t have any documentation tests yet,
but Rust can compile any code examples that appear in our API documentation.
This feature helps keep your docs and your code in sync! We’ll discuss how to
write documentation tests in the “Documentation Comments as
Tests” section of Chapter 14. For now, we’ll
ignore the Doc-tests
output.
从Doc-tests adder
开始的测试输出的下一部分是任何文档测试的结果。我们还没有任何文档测试,但 Rust 可以编译 API 文档中出现的任何代码示例。此功能有助于保持您的文档和代码同步!我们将在第 14 章的“文档注释作为测试”忽略部分中讨论如何编写文档测试。现在,我们将忽略Doc-tests
输出。
Let’s start to customize the test to our own needs. First change the name of
the it_works
function to a different name, such as exploration
, like so:
让我们开始根据自己的需要定制测试。首先将it_works
函数的名称更改为其他名称,例如exploration
,如下所示:
Filename: src/lib.rs 文件名:src/lib.rs
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exploration() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
Then run cargo test
again. The output now shows exploration
instead of
it_works
:
然后再次运行cargo test
。输出现在显示exploration
而不是it_works
:
$ 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
Now we’ll add another test, but this time we’ll make a test that fails! Tests
fail when something in the test function panics. Each test is run in a new
thread, and when the main thread sees that a test thread has died, the test is
marked as failed. In Chapter 9, we talked about how the simplest way to panic
is to call the panic!
macro. Enter the new test as a function named
another
, so your src/lib.rs file looks like Listing 11-3.
现在我们将添加另一个测试,但这一次我们将进行一个失败的测试!当测试函数中出现紧急情况时,测试就会失败。每个测试都在一个新线程中运行,当主线程发现测试线程已死亡时,测试将被标记为失败。在第 9 章中,我们讨论了最简单的恐慌方法是调用panic!
宏。输入新测试作为名为another
函数,因此您的src/lib.rs文件如清单 11-3 所示。
Filename: src/lib.rs 文件名:src/lib.rs
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exploration() {
let result = add(2, 2);
assert_eq!(result, 4);
}
#[test]
fn another() {
panic!("Make this test fail");
}
}
Run the tests again using cargo test
. The output should look like Listing
11-4, which shows that our exploration
test passed and another
failed.
使用cargo test
再次运行测试。输出应如清单 11-4 所示,其中显示我们的exploration
测试通过了,而another
失败了。
$ 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`
Instead of ok
, the line test tests::another
shows FAILED
. Two new
sections appear between the individual results and the summary: the first
displays the detailed reason for each test failure. In this case, we get the
details that another
failed because it panicked at 'Make this test fail'
on
line 10 in the src/lib.rs file. The next section lists just the names of all
the failing tests, which is useful when there are lots of tests and lots of
detailed failing test output. We can use the name of a failing test to run just
that test to more easily debug it; we’ll talk more about ways to run tests in
the “Controlling How Tests Are Run” section.test tests::another
行显示FAILED
,而不是ok
。各个结果和摘要之间出现两个新部分:第一个部分显示每次测试失败的详细原因。在本例中,我们获得了another
失败的详细信息,因为它在src/lib.rs文件中第 10 行的panicked at 'Make this test fail'
。下一部分仅列出所有失败测试的名称,这在存在大量测试和大量详细失败测试输出时非常有用。我们可以使用失败测试的名称来运行该测试,以便更轻松地调试它;我们将在“控制测试的运行方式”忽略部分中详细讨论运行测试的方法。
The summary line displays at the end: overall, our test result is FAILED
. We
had one test pass and one test fail.
摘要行显示在最后:总的来说,我们的测试结果是FAILED
。我们有一项测试通过,一项测试失败。
Now that you’ve seen what the test results look like in different scenarios,
let’s look at some macros other than panic!
that are useful in tests.
现在您已经了解了不同场景下的测试结果,让我们看看除了panic!
这在测试中很有用。
Checking Results with the assert!
Macro
使用assert!
宏
The assert!
macro, provided by the standard library, is useful when you want
to ensure that some condition in a test evaluates to true
. We give the
assert!
macro an argument that evaluates to a Boolean. If the value is
true
, nothing happens and the test passes. If the value is false
, the
assert!
macro calls panic!
to cause the test to fail. Using the assert!
macro helps us check that our code is functioning in the way we intend.assert!
当您想要确保测试中的某些条件计算结果为true
时,标准库提供的宏非常有用。我们给出assert!
宏是一个计算结果为布尔值的参数。如果值为true
,则不会发生任何事情并且测试通过。如果值为false
,则assert!
宏呼panic!
导致测试失败。使用assert!
宏帮助我们检查代码是否按照我们预期的方式运行。
In Chapter 5, Listing 5-15, we used a Rectangle
struct and a can_hold
method, which are repeated here in Listing 11-5. Let’s put this code in the
src/lib.rs file, then write some tests for it using the assert!
macro.
在第 5 章清单 5-15 中,我们使用了Rectangle
结构体和can_hold
方法,清单 11-5 中重复了这些方法。让我们将此代码放在src/lib.rs文件中,然后使用assert!
宏。
Filename: src/lib.rs 文件名:src/lib.rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
The can_hold
method returns a Boolean, which means it’s a perfect use case
for the assert!
macro. In Listing 11-6, we write a test that exercises the
can_hold
method by creating a Rectangle
instance that has a width of 8 and
a height of 7 and asserting that it can hold another Rectangle
instance that
has a width of 5 and a height of 1.can_hold
方法返回一个布尔值,这意味着它是assert!
宏。在清单 11-6 中,我们编写了一个测试来练习can_hold
方法,方法是创建一个宽度为 8、高度为 7 的Rectangle
实例,并断言它可以容纳另一个Rectangle
为 5、高度为1.
Filename: src/lib.rs 文件名:src/lib.rs
Note that we’ve added a new line inside the tests
module: use super::*;
.
The tests
module is a regular module that follows the usual visibility rules
we covered in Chapter 7 in the “Paths for Referring to an Item in the Module
Tree”
section. Because the tests
module is an inner module, we need to bring the
code under test in the outer module into the scope of the inner module. We use
a glob here so anything we define in the outer module is available to this
tests
module.
请注意,我们在tests
模块中添加了一个新行: use super::*;
。 tests
模块是一个常规模块,遵循我们在第 7 章“引用模块树中项目的路径”忽略部分中介绍的常见可见性规则。因为tests
模块是一个内部模块,所以我们需要将外部模块中的被测代码纳入到内部模块的作用域中。我们在这里使用 glob,因此我们在外部模块中定义的任何内容都可供该tests
模块使用。
We’ve named our test larger_can_hold_smaller
, and we’ve created the two
Rectangle
instances that we need. Then we called the assert!
macro and
passed it the result of calling larger.can_hold(&smaller)
. This expression is
supposed to return true
, so our test should pass. Let’s find out!
我们将测试命名为larger_can_hold_smaller
,并创建了我们需要的两个Rectangle
实例。然后我们调用了assert!
宏并将调用larger.can_hold(&smaller)
的结果传递给它。该表达式应该返回true
,因此我们的测试应该通过。让我们来看看吧!
$ 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
It does pass! Let’s add another test, this time asserting that a smaller
rectangle cannot hold a larger rectangle:
它确实通过了!让我们添加另一个测试,这次断言较小的矩形不能容纳较大的矩形:
Filename: src/lib.rs 文件名:src/lib.rs
Because the correct result of the can_hold
function in this case is false
,
we need to negate that result before we pass it to the assert!
macro. As a
result, our test will pass if can_hold
returns false
:
因为在这种情况下can_hold
函数的正确结果是false
,所以我们需要在将结果传递给assert!
宏。因此,如果can_hold
返回false
,我们的测试就会通过:
$ 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
Two tests that pass! Now let’s see what happens to our test results when we
introduce a bug in our code. We’ll change the implementation of the can_hold
method by replacing the greater-than sign with a less-than sign when it
compares the widths:
两项测试均通过!现在让我们看看当我们在代码中引入错误时测试结果会发生什么。我们将更改can_hold
方法的实现,在比较宽度时将大于号替换为小于号:
Running the tests now produces the following:
现在运行测试会产生以下结果:
$ 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(&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`
Our tests caught the bug! Because larger.width
is 8 and smaller.width
is
5, the comparison of the widths in can_hold
now returns false
: 8 is not
less than 5.
我们的测试发现了这个错误!由于larger.width
为 8, smaller.width
为 5, can_hold
中的宽度比较现在返回false
:8 不小于 5。
Testing Equality with the assert_eq!
and assert_ne!
Macros
使用assert_eq!
测试相等性并assert_ne!
宏
A common way to verify functionality is to test for equality between the result
of the code under test and the value you expect the code to return. You could
do this using the assert!
macro and passing it an expression using the ==
operator. However, this is such a common test that the standard library
provides a pair of macros—assert_eq!
and assert_ne!
—to perform this test
more conveniently. These macros compare two arguments for equality or
inequality, respectively. They’ll also print the two values if the assertion
fails, which makes it easier to see why the test failed; conversely, the
assert!
macro only indicates that it got a false
value for the ==
expression, without printing the values that led to the false
value.
验证功能的常见方法是测试被测代码的结果与您期望代码返回的值之间是否相等。您可以使用assert!
宏并使用==
运算符向其传递一个表达式。然而,这是一个非常常见的测试,标准库提供了一对宏assert_eq!
并assert_ne!
——更方便地进行此测试。这些宏分别比较两个参数的相等或不相等。如果断言失败,他们还会打印这两个值,这使得更容易了解测试失败的原因;反之,则assert!
宏仅指示它得到==
表达式的false
值,而不打印导致false
值的值。
In Listing 11-7, we write a function named add_two
that adds 2
to its
parameter, then we test this function using the assert_eq!
macro.
在清单 11-7 中,我们编写了一个名为add_two
的函数,该函数将2
添加到其参数中,然后我们使用assert_eq!
测试该函数。宏。
Filename: src/lib.rs 文件名:src/lib.rs
pub fn add_two(a: i32) -> i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_adds_two() {
assert_eq!(4, add_two(2));
}
}
Let’s check that it passes!
让我们检查一下它是否通过!
$ 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
We pass 4
as the argument to assert_eq!
, which is equal to the result of
calling add_two(2)
. The line for this test is test tests::it_adds_two ... ok
, and the ok
text indicates that our test passed!
我们将4
作为参数传递给assert_eq!
,它等于调用add_two(2)
的结果。此测试的行是test tests::it_adds_two ... ok
, ok
文本表明我们的测试通过了!
Let’s introduce a bug into our code to see what assert_eq!
looks like when it
fails. Change the implementation of the add_two
function to instead add 3
:
让我们在代码中引入一个错误,看看assert_eq!
看起来像失败时。将add_two
函数的实现更改为 add 3
:
Run the tests again: 再次运行测试:
$ 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:11:9:
assertion `left == right` failed
left: 4
right: 5
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`
Our test caught the bug! The it_adds_two
test failed, and the message tells
us that the assertion that fails was assertion `left == right` failed
and what the left
and right
values are. This message helps us start
debugging: the left
argument was 4
but the right
argument, where we had
add_two(2)
, was 5
. You can imagine that this would be especially helpful
when we have a lot of tests going on.
我们的测试发现了这个错误! it_adds_two
测试失败,消息告诉我们失败的断言是assertion `left == right` failed
以及left
值和right
值是什么。此消息帮助我们开始调试: left
参数是4
,但right
参数(我们有add_two(2)
是5
。您可以想象,当我们正在进行大量测试时,这会特别有帮助。
Note that in some languages and test frameworks, the parameters to equality
assertion functions are called expected
and actual
, and the order in which
we specify the arguments matters. However, in Rust, they’re called left
and
right
, and the order in which we specify the value we expect and the value
the code produces doesn’t matter. We could write the assertion in this test as
assert_eq!(add_two(2), 4)
, which would result in the same failure message
that displays assertion failed: `(left == right)`
.
请注意,在某些语言和测试框架中,相等断言函数的参数称为expected
和actual
,并且我们指定参数的顺序很重要。然而,在 Rust 中,它们被称为left
和right
,我们指定期望值和代码生成值的顺序并不重要。我们可以在此测试中将断言编写为assert_eq!(add_two(2), 4)
,这将导致显示assertion failed: `(left == right)`
。
The assert_ne!
macro will pass if the two values we give it are not equal and
fail if they’re equal. This macro is most useful for cases when we’re not sure
what a value will be, but we know what the value definitely shouldn’t be.
For example, if we’re testing a function that is guaranteed to change its input
in some way, but the way in which the input is changed depends on the day of
the week that we run our tests, the best thing to assert might be that the
output of the function is not equal to the input.assert_ne!
如果我们给它的两个值不相等,则宏将通过;如果相等,则宏将失败。当我们不确定某个值是什么,但我们知道该值绝对不应该是什么时,该宏最有用。例如,如果我们正在测试一个保证以某种方式更改其输入的函数,但更改输入的方式取决于我们运行测试的星期几,那么最好的断言可能是函数的输出不等于输入。
Under the surface, the assert_eq!
and assert_ne!
macros use the operators
==
and !=
, respectively. When the assertions fail, these macros print their
arguments using debug formatting, which means the values being compared must
implement the PartialEq
and Debug
traits. All primitive types and most of
the standard library types implement these traits. For structs and enums that
you define yourself, you’ll need to implement PartialEq
to assert equality of
those types. You’ll also need to implement Debug
to print the values when the
assertion fails. Because both traits are derivable traits, as mentioned in
Listing 5-12 in Chapter 5, this is usually as straightforward as adding the
#[derive(PartialEq, Debug)]
annotation to your struct or enum definition. See
Appendix C, “Derivable Traits,” for more
details about these and other derivable traits.
在表面之下, assert_eq!
并assert_ne!
宏分别使用运算符==
和!=
。当断言失败时,这些宏使用调试格式打印其参数,这意味着要比较的值必须实现PartialEq
和Debug
特征。所有原始类型和大多数标准库类型都实现这些特征。对于您自己定义的结构和枚举,您需要实现PartialEq
来断言这些类型的相等性。您还需要实现Debug
以在断言失败时打印值。因为这两个特征都是可派生的特征,如第 5 章中的清单 5-12 中所述,所以这通常就像将#[derive(PartialEq, Debug)]
注释添加到结构或枚举定义中一样简单。有关这些和其他可衍生特征的更多详细信息,请参阅附录 C “可衍生特征” 。
Adding Custom Failure Messages
添加自定义失败消息
You can also add a custom message to be printed with the failure message as
optional arguments to the assert!
, assert_eq!
, and assert_ne!
macros. Any
arguments specified after the required arguments are passed along to the
format!
macro (discussed in Chapter 8 in the “Concatenation with the +
Operator or the format!
Macro”
section), so you can pass a format string that contains {}
placeholders and
values to go in those placeholders. Custom messages are useful for documenting
what an assertion means; when a test fails, you’ll have a better idea of what
the problem is with the code.
您还可以添加要与失败消息一起打印的自定义消息作为断言的assert!
, assert_eq!
,并assert_ne!
宏。在必需参数之后指定的任何参数都将传递到format!
宏(在第 8 章的“与+
运算符或format!
宏”忽略部分中讨论),因此您可以传递包含{}
占位符和要放入这些占位符中的值的格式字符串。自定义消息对于记录断言的含义很有用;当测试失败时,您将更好地了解代码的问题所在。
For example, let’s say we have a function that greets people by name and we
want to test that the name we pass into the function appears in the output:
例如,假设我们有一个通过名字向人们打招呼的函数,我们想要测试传递给函数的名字是否出现在输出中:
Filename: src/lib.rs 文件名:src/lib.rs
pub fn greeting(name: &str) -> String {
format!("Hello {name}!")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn greeting_contains_name() {
let result = greeting("Carol");
assert!(result.contains("Carol"));
}
}
The requirements for this program haven’t been agreed upon yet, and we’re
pretty sure the Hello
text at the beginning of the greeting will change. We
decided we don’t want to have to update the test when the requirements change,
so instead of checking for exact equality to the value returned from the
greeting
function, we’ll just assert that the output contains the text of the
input parameter.
该程序的要求尚未达成一致,我们非常确定问候语开头的Hello
文本将会发生变化。我们决定不想在需求发生变化时更新测试,因此我们不会检查与greeting
函数返回的值是否完全相等,而是断言输出包含输入参数的文本。
Now let’s introduce a bug into this code by changing greeting
to exclude
name
to see what the default test failure looks like:
现在,让我们通过更改greeting
以排除name
来引入一个错误到此代码中,以查看默认测试失败的情况:
Running this test produces the following:
运行此测试会产生以下结果:
$ 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`
This result just indicates that the assertion failed and which line the
assertion is on. A more useful failure message would print the value from the
greeting
function. Let’s add a custom failure message composed of a format
string with a placeholder filled in with the actual value we got from the
greeting
function:
这个结果只是表明断言失败以及断言在哪一行。更有用的失败消息将打印来自greeting
函数的值。让我们添加一个由格式字符串组成的自定义失败消息,其中占位符填充了从greeting
函数获得的实际值:
Now when we run the test, we’ll get a more informative error message:
现在,当我们运行测试时,我们将收到一条信息更丰富的错误消息:
$ 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`
We can see the value we actually got in the test output, which would help us
debug what happened instead of what we were expecting to happen.
我们可以在测试输出中看到实际获得的值,这将帮助我们调试发生的情况而不是我们期望发生的情况。
Checking for Panics with should_panic
使用should_panic
检查是否出现紧急情况
In addition to checking return values, it’s important to check that our code
handles error conditions as we expect. For example, consider the Guess
type
that we created in Chapter 9, Listing 9-13. Other code that uses Guess
depends on the guarantee that Guess
instances will contain only values
between 1 and 100. We can write a test that ensures that attempting to create a
Guess
instance with a value outside that range panics.
除了检查返回值之外,检查我们的代码是否按预期处理错误条件也很重要。例如,考虑我们在第 9 章清单 9-13 中创建的Guess
类型。使用Guess
的其他代码取决于Guess
实例仅包含 1 到 100 之间的值的保证。我们可以编写一个测试来确保尝试创建具有超出该范围的值的Guess
实例会发生恐慌。
We do this by adding the attribute should_panic
to our test function. The
test passes if the code inside the function panics; the test fails if the code
inside the function doesn’t panic.
我们通过将属性should_panic
添加到我们的测试函数中来做到这一点。如果函数内的代码发生恐慌,则测试通过;如果函数内的代码没有出现恐慌,则测试失败。
Listing 11-8 shows a test that checks that the error conditions of Guess::new
happen when we expect them to.
清单 11-8 显示了一个测试,该测试检查Guess::new
的错误条件是否在我们期望的时间发生。
Filename: src/lib.rs 文件名:src/lib.rs
pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 || value > 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);
}
}
We place the #[should_panic]
attribute after the #[test]
attribute and
before the test function it applies to. Let’s look at the result when this test
passes:
我们将#[should_panic]
属性放在#[test]
属性之后、它所适用的测试函数之前。让我们看看测试通过后的结果:
$ 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
Looks good! Now let’s introduce a bug in our code by removing the condition
that the new
function will panic if the value is greater than 100:
看起来不错!现在,让我们在代码中引入一个错误,删除new
函数在值大于 100 时将发生恐慌的条件:
When we run the test in Listing 11-8, it will fail:
当我们运行清单 11-8 中的测试时,它将失败:
$ 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`
We don’t get a very helpful message in this case, but when we look at the test
function, we see that it’s annotated with #[should_panic]
. The failure we got
means that the code in the test function did not cause a panic.
在这种情况下,我们没有得到非常有用的消息,但是当我们查看测试函数时,我们看到它带有#[should_panic]
注释。我们得到的失败意味着测试函数中的代码没有引起恐慌。
Tests that use should_panic
can be imprecise. A should_panic
test would
pass even if the test panics for a different reason from the one we were
expecting. To make should_panic
tests more precise, we can add an optional
expected
parameter to the should_panic
attribute. The test harness will
make sure that the failure message contains the provided text. For example,
consider the modified code for Guess
in Listing 11-9 where the new
function
panics with different messages depending on whether the value is too small or
too large.
使用should_panic
的测试可能不精确。即使测试因与我们预期不同的原因而发生恐慌, should_panic
测试也会通过。为了使should_panic
测试更加精确,我们可以向should_panic
属性添加一个可选的expected
参数。测试工具将确保失败消息包含提供的文本。例如,考虑清单 11-9 中Guess
的修改后的代码,其中new
函数根据值是否太小或太大而发出不同的消息。
Filename: src/lib.rs 文件名:src/lib.rs
This test will pass because the value we put in the should_panic
attribute’s
expected
parameter is a substring of the message that the Guess::new
function panics with. We could have specified the entire panic message that we
expect, which in this case would be Guess value must be less than or equal to 100, got 200.
What you choose to specify depends on how much of the panic
message is unique or dynamic and how precise you want your test to be. In this
case, a substring of the panic message is enough to ensure that the code in the
test function executes the else if value > 100
case.
该测试将通过,因为我们放入should_panic
属性的expected
参数中的值是Guess::new
函数发生恐慌的消息的子字符串。我们可以指定我们期望的整个紧急消息,在这种情况下, Guess value must be less than or equal to 100, got 200.
您选择指定的内容取决于紧急消息中有多少是唯一的或动态的,以及您希望测试有多精确。在这种情况下,恐慌消息的子字符串足以确保测试函数中的代码执行else if value > 100
情况。
To see what happens when a should_panic
test with an expected
message
fails, let’s again introduce a bug into our code by swapping the bodies of the
if value < 1
and the else if value > 100
blocks:
要了解当expected
消息的should_panic
测试失败时会发生什么,让我们通过交换if value < 1
和else if value > 100
块的主体,再次在代码中引入错误:
This time when we run the should_panic
test, it will fail:
这次当我们运行should_panic
测试时,它将失败:
$ 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`
The failure message indicates that this test did indeed panic as we expected,
but the panic message did not include the expected string less than or equal to 100
. The panic message that we did get in this case was Guess value must be greater than or equal to 1, got 200.
Now we can start figuring out where
our bug is!
失败消息表明此测试确实如我们预期的那样发生了恐慌,但是恐慌消息不包含less than or equal to 100
预期字符串。在这种情况下,我们确实收到的恐慌消息是Guess value must be greater than or equal to 1, got 200.
现在我们可以开始找出我们的错误在哪里!
Using Result<T, E>
in Tests
在测试中使用Result<T, E>
Our tests so far all panic when they fail. We can also write tests that use
Result<T, E>
! Here’s the test from Listing 11-1, rewritten to use Result<T, E>
and return an Err
instead of panicking:
到目前为止,我们的测试在失败时都会出现恐慌。我们还可以编写使用Result<T, E>
的测试!下面是清单 11-1 中的测试,重写为使用Result<T, E>
并返回Err
而不是恐慌:
#[cfg(test)]
mod tests {
#[test]
fn it_works() -> Result<(), String> {
if 2 + 2 == 4 {
Ok(())
} else {
Err(String::from("two plus two does not equal four"))
}
}
}
The it_works
function now has the Result<(), String>
return type. In the
body of the function, rather than calling the assert_eq!
macro, we return
Ok(())
when the test passes and an Err
with a String
inside when the test
fails.it_works
函数现在具有Result<(), String>
返回类型。在函数体中,而不是调用assert_eq!
宏,当测试通过时,我们返回Ok(())
当测试失败时,我们返回一个带有String
的Err
。
Writing tests so they return a Result<T, E>
enables you to use the question
mark operator in the body of tests, which can be a convenient way to write
tests that should fail if any operation within them returns an Err
variant.
编写测试使其返回Result<T, E>
使您能够在测试主体中使用问号运算符,这可以是编写测试的便捷方法,如果其中的任何操作返回Err
变体,这些测试就会失败。
You can’t use the #[should_panic]
annotation on tests that use Result<T, E>
. To assert that an operation returns an Err
variant, don’t use the
question mark operator on the Result<T, E>
value. Instead, use
assert!(value.is_err())
.
您不能在使用Result<T, E>
的测试中使用#[should_panic]
注释。要断言操作返回Err
变体,请勿对Result<T, E>
值使用问号运算符。相反,请使用assert!(value.is_err())
。
Now that you know several ways to write tests, let’s look at what is happening
when we run our tests and explore the different options we can use with cargo test
.
现在您已经知道了编写测试的几种方法,让我们看看运行测试时发生的情况,并探索可以与cargo test
一起使用的不同选项。
Controlling How Tests Are Run
控制测试的运行方式
Just as cargo run
compiles your code and then runs the resulting binary,
cargo test
compiles your code in test mode and runs the resulting test
binary. The default behavior of the binary produced by cargo test
is to run
all the tests in parallel and capture output generated during test runs,
preventing the output from being displayed and making it easier to read the
output related to the test results. You can, however, specify command line
options to change this default behavior.
正如cargo run
编译您的代码然后运行生成的二进制文件一样, cargo test
在测试模式下编译您的代码并运行生成的测试二进制文件。 cargo test
生成的二进制文件的默认行为是并行运行所有测试并捕获测试运行期间生成的输出,从而防止显示输出并使其更容易读取与测试结果相关的输出。但是,您可以指定命令行选项来更改此默认行为。
Some command line options go to cargo test
, and some go to the resulting test
binary. To separate these two types of arguments, you list the arguments that
go to cargo test
followed by the separator --
and then the ones that go to
the test binary. Running cargo test --help
displays the options you can use
with cargo test
, and running cargo test -- --help
displays the options you
can use after the separator.
一些命令行选项转到cargo test
,一些选项转到生成的测试二进制文件。要分隔这两种类型的参数,您可以列出进入cargo test
的参数,后跟分隔符--
然后列出进入测试二进制文件的参数。运行cargo test --help
显示可与cargo test
一起使用的选项,运行cargo test -- --help
显示可在分隔符后使用的选项。
Running Tests in Parallel or Consecutively
并行或连续运行测试
When you run multiple tests, by default they run in parallel using threads,
meaning they finish running faster and you get feedback quicker. Because the
tests are running at the same time, you must make sure your tests don’t depend
on each other or on any shared state, including a shared environment, such as
the current working directory or environment variables.
当您运行多个测试时,默认情况下它们使用线程并行运行,这意味着它们更快地完成运行,并且您可以更快地获得反馈。由于测试是同时运行的,因此您必须确保测试不相互依赖或不依赖于任何共享状态,包括共享环境,例如当前工作目录或环境变量。
For example, say each of your tests runs some code that creates a file on disk
named test-output.txt and writes some data to that file. Then each test reads
the data in that file and asserts that the file contains a particular value,
which is different in each test. Because the tests run at the same time, one
test might overwrite the file in the time between another test writing and
reading the file. The second test will then fail, not because the code is
incorrect but because the tests have interfered with each other while running
in parallel. One solution is to make sure each test writes to a different file;
another solution is to run the tests one at a time.
例如,假设每个测试都运行一些代码,这些代码在磁盘上创建一个名为test-output.txt的文件,并将一些数据写入该文件。然后,每个测试都会读取该文件中的数据,并断言该文件包含特定值,该值在每个测试中都不同。由于测试是同时运行的,因此一个测试可能会在另一个测试写入和读取文件之间的时间内覆盖该文件。第二个测试将失败,不是因为代码不正确,而是因为测试在并行运行时相互干扰。一种解决方案是确保每个测试写入不同的文件;另一种解决方案是一次运行一个测试。
If you don’t want to run the tests in parallel or if you want more fine-grained
control over the number of threads used, you can send the --test-threads
flag
and the number of threads you want to use to the test binary. Take a look at
the following example:
如果您不想并行运行测试,或者希望对所使用的线程数进行更细粒度的控制,则可以发送--test-threads
标志和要用于测试的线程数二进制。看一下下面的例子:
$ cargo test -- --test-threads=1
We set the number of test threads to 1
, telling the program not to use any
parallelism. Running the tests using one thread will take longer than running
them in parallel, but the tests won’t interfere with each other if they share
state.
我们将测试线程数设置为1
,告诉程序不要使用任何并行性。使用一个线程运行测试比并行运行它们需要更长的时间,但如果它们共享状态,测试就不会相互干扰。
Showing Function Output 显示函数输出
By default, if a test passes, Rust’s test library captures anything printed to
standard output. For example, if we call println!
in a test and the test
passes, we won’t see the println!
output in the terminal; we’ll see only the
line that indicates the test passed. If a test fails, we’ll see whatever was
printed to standard output with the rest of the failure message.
默认情况下,如果测试通过,Rust 的测试库会捕获打印到标准输出的任何内容。例如,如果我们调用println!
在测试中并且测试通过,我们将不会看到println!
在终端中输出;我们只会看到表明测试已通过的行。如果测试失败,我们将看到打印到标准输出的内容以及失败消息的其余部分。
As an example, Listing 11-10 has a silly function that prints the value of its
parameter and returns 10, as well as a test that passes and a test that fails.
例如,清单 11-10 有一个愚蠢的函数,它打印其参数的值并返回 10,以及一个通过的测试和一个失败的测试。
Filename: src/lib.rs 文件名:src/lib.rs
fn prints_and_returns_10(a: i32) -> 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!(10, value);
}
#[test]
fn this_test_will_fail() {
let value = prints_and_returns_10(8);
assert_eq!(5, value);
}
}
When we run these tests with cargo test
, we’ll see the following output:
当我们使用cargo test
运行这些测试时,我们将看到以下输出:
$ 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: 5
right: 10
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`
Note that nowhere in this output do we see I got the value 4
, which is what
is printed when the test that passes runs. That output has been captured. The
output from the test that failed, I got the value 8
, appears in the section
of the test summary output, which also shows the cause of the test failure.
请注意,在此输出中,我们没有看到I got the value 4
,这是运行通过的测试时打印的值。该输出已被捕获。失败的测试的输出, I got the value 8
,出现在测试摘要输出的部分中,这也显示了测试失败的原因。
If we want to see printed values for passing tests as well, we can tell Rust
to also show the output of successful tests with --show-output
.
如果我们还想查看通过测试的打印值,我们可以告诉 Rust 也使用--show-output
显示成功测试的输出。
$ cargo test -- --show-output
When we run the tests in Listing 11-10 again with the --show-output
flag, we
see the following output:
当我们使用--show-output
标志再次运行清单 11-10 中的测试时,我们会看到以下输出:
$ 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: 5
right: 10
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`
Running a Subset of Tests by Name
按名称运行测试子集
Sometimes, running a full test suite can take a long time. If you’re working on
code in a particular area, you might want to run only the tests pertaining to
that code. You can choose which tests to run by passing cargo test
the name
or names of the test(s) you want to run as an argument.
有时,运行完整的测试套件可能需要很长时间。如果您正在处理特定区域的代码,您可能只想运行与该代码相关的测试。您可以通过将要运行的测试的名称作为参数传递给cargo test
来选择要运行的测试。
To demonstrate how to run a subset of tests, we’ll first create three tests for
our add_two
function, as shown in Listing 11-11, and choose which ones to run.
为了演示如何运行测试子集,我们首先为add_two
函数创建三个测试(如清单 11-11 所示),然后选择要运行的测试。
Filename: src/lib.rs 文件名:src/lib.rs
pub fn add_two(a: i32) -> i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_two_and_two() {
assert_eq!(4, add_two(2));
}
#[test]
fn add_three_and_two() {
assert_eq!(5, add_two(3));
}
#[test]
fn one_hundred() {
assert_eq!(102, add_two(100));
}
}
If we run the tests without passing any arguments, as we saw earlier, all the
tests will run in parallel:
如果我们在不传递任何参数的情况下运行测试,如我们之前所见,所有测试将并行运行:
$ 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
Running Single Tests 运行单个测试
We can pass the name of any test function to cargo test
to run only that test:
我们可以将任何测试函数的名称传递给cargo test
以仅运行该测试:
$ 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
Only the test with the name one_hundred
ran; the other two tests didn’t match
that name. The test output lets us know we had more tests that didn’t run by
displaying 2 filtered out
at the end.
仅运行名为one_hundred
的测试;其他两个测试与该名称不匹配。测试输出通过在最后显示2 filtered out
让我们知道我们还有更多未运行的测试。
We can’t specify the names of multiple tests in this way; only the first value
given to cargo test
will be used. But there is a way to run multiple tests.
我们不能通过这种方式指定多个测试的名称;仅使用给予cargo test
的第一个值。但有一种方法可以运行多个测试。
Filtering to Run Multiple Tests
过滤以运行多个测试
We can specify part of a test name, and any test whose name matches that value
will be run. For example, because two of our tests’ names contain add
, we can
run those two by running cargo test add
:
我们可以指定测试名称的一部分,并且名称与该值匹配的任何测试都将运行。例如,因为我们的两个测试名称包含add
,所以我们可以通过运行cargo test add
来运行这两个测试:
$ 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
This command ran all tests with add
in the name and filtered out the test
named one_hundred
. Also note that the module in which a test appears becomes
part of the test’s name, so we can run all the tests in a module by filtering
on the module’s name.
此命令运行名称中包含add
所有测试,并过滤掉名为one_hundred
的测试。另请注意,出现测试的模块将成为测试名称的一部分,因此我们可以通过过滤模块名称来运行模块中的所有测试。
Ignoring Some Tests Unless Specifically Requested
除非特别要求,否则忽略一些测试
Sometimes a few specific tests can be very time-consuming to execute, so you
might want to exclude them during most runs of cargo test
. Rather than
listing as arguments all tests you do want to run, you can instead annotate the
time-consuming tests using the ignore
attribute to exclude them, as shown
here:
有时,执行一些特定的测试可能非常耗时,因此您可能希望在大多数运行cargo test
的过程中排除它们。您可以使用ignore
属性注释耗时的测试以排除它们,而不是将您想要运行的所有测试作为参数列出,如下所示:
Filename: src/lib.rs 文件名:src/lib.rs
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
#[ignore]
fn expensive_test() {
// code that takes an hour to run
}
After #[test]
we add the #[ignore]
line to the test we want to exclude. Now
when we run our tests, it_works
runs, but expensive_test
doesn’t:
在#[test]
之后,我们将#[ignore]
行添加到我们要排除的测试中。现在,当我们运行测试时, it_works
会运行,但expensive_test
不会:
$ 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 expensive_test ... ignored
test 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
The expensive_test
function is listed as ignored
. If we want to run only
the ignored tests, we can use cargo test -- --ignored
:expensive_test
函数被列为ignored
。如果我们只想运行被忽略的测试,我们可以使用cargo test -- --ignored
:
$ 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
By controlling which tests run, you can make sure your cargo test
results
will be fast. When you’re at a point where it makes sense to check the results
of the ignored
tests and you have time to wait for the results, you can run
cargo test -- --ignored
instead. If you want to run all tests whether they’re
ignored or not, you can run cargo test -- --include-ignored
.
通过控制运行哪些测试,您可以确保快速获得cargo test
结果。当您需要检查ignored
测试的结果并且您有时间等待结果时,您可以运行cargo test -- --ignored
来代替。如果您想运行所有测试,无论它们是否被忽略,您可以运行cargo test -- --include-ignored
。
Test Organization 测试组织
As mentioned at the start of the chapter, testing is a complex discipline, and
different people use different terminology and organization. The Rust community
thinks about tests in terms of two main categories: unit tests and integration
tests. Unit tests are small and more focused, testing one module in isolation
at a time, and can test private interfaces. Integration tests are entirely
external to your library and use your code in the same way any other external
code would, using only the public interface and potentially exercising multiple
modules per test.
正如本章开头提到的,测试是一门复杂的学科,不同的人使用不同的术语和组织。 Rust 社区从两个主要类别来考虑测试:单元测试和集成测试。单元测试规模较小且更有针对性,一次单独测试一个模块,并且可以测试私有接口。集成测试完全在您的库外部,并以与任何其他外部代码相同的方式使用您的代码,仅使用公共接口,并且每个测试可能会执行多个模块。
Writing both kinds of tests is important to ensure that the pieces of your
library are doing what you expect them to, separately and together.
编写这两种测试对于确保库的各个部分分别或一起执行您期望的操作非常重要。
Unit Tests 单元测试
The purpose of unit tests is to test each unit of code in isolation from the
rest of the code to quickly pinpoint where code is and isn’t working as
expected. You’ll put unit tests in the src directory in each file with the
code that they’re testing. The convention is to create a module named tests
in each file to contain the test functions and to annotate the module with
cfg(test)
.
单元测试的目的是独立于其余代码来测试每个代码单元,以快速查明代码在何处按预期工作以及在何处未按预期工作。您将使用它们正在测试的代码将单元测试放在每个文件的src目录中。约定是在每个文件中创建一个名为tests
模块来包含测试函数并使用cfg(test)
注释该模块。
The Tests Module and #[cfg(test)]
测试模块和#[cfg(test)]
The #[cfg(test)]
annotation on the tests module tells Rust to compile and run
the test code only when you run cargo test
, not when you run cargo build
.
This saves compile time when you only want to build the library and saves space
in the resulting compiled artifact because the tests are not included. You’ll
see that because integration tests go in a different directory, they don’t need
the #[cfg(test)]
annotation. However, because unit tests go in the same files
as the code, you’ll use #[cfg(test)]
to specify that they shouldn’t be
included in the compiled result.
测试模块上的#[cfg(test)]
注释告诉Rust仅在运行cargo test
时编译并运行测试代码,而不是在运行cargo build
时。当您只想构建库时,这可以节省编译时间,并节省生成的编译工件的空间,因为不包含测试。您将看到,由于集成测试位于不同的目录中,因此它们不需要#[cfg(test)]
注释。但是,由于单元测试与代码位于同一文件中,因此您将使用#[cfg(test)]
来指定它们不应包含在编译结果中。
Recall that when we generated the new adder
project in the first section of
this chapter, Cargo generated this code for us:
回想一下,当我们在本章第一部分生成新的adder
项目时,Cargo 为我们生成了以下代码:
Filename: src/lib.rs 文件名:src/lib.rs
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
This code is the automatically generated test module. The attribute cfg
stands for configuration and tells Rust that the following item should only
be included given a certain configuration option. In this case, the
configuration option is test
, which is provided by Rust for compiling and
running tests. By using the cfg
attribute, Cargo compiles our test code only
if we actively run the tests with cargo test
. This includes any helper
functions that might be within this module, in addition to the functions
annotated with #[test]
.
该代码是自动生成的测试模块。属性cfg
代表配置,并告诉 Rust 仅在给定特定配置选项的情况下才应包含以下项目。在这种情况下,配置选项是test
,它是 Rust 提供的用于编译和运行测试的。通过使用cfg
属性,仅当我们主动cargo test
运行测试时,Cargo 才会编译我们的测试代码。除了用#[test]
注释的函数之外,这还包括此模块中可能存在的任何辅助函数。
Testing Private Functions
测试私有函数
There’s debate within the testing community about whether or not private
functions should be tested directly, and other languages make it difficult or
impossible to test private functions. Regardless of which testing ideology you
adhere to, Rust’s privacy rules do allow you to test private functions.
Consider the code in Listing 11-12 with the private function internal_adder
.
测试社区内部存在关于是否应该直接测试私有函数的争论,而其他语言使得测试私有函数变得困难或不可能。无论您遵循哪种测试理念,Rust 的隐私规则都允许您测试私有函数。考虑清单11-12中带有私有函数internal_adder
的代码。
Filename: src/lib.rs 文件名:src/lib.rs
pub fn add_two(a: i32) -> i32 {
internal_adder(a, 2)
}
fn internal_adder(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn internal() {
assert_eq!(4, internal_adder(2, 2));
}
}
Note that the internal_adder
function is not marked as pub
. Tests are just
Rust code, and the tests
module is just another module. As we discussed in
the “Paths for Referring to an Item in the Module Tree”
section, items in child modules can use the items in their ancestor modules. In
this test, we bring all of the tests
module’s parent’s items into scope with
use super::*
, and then the test can call internal_adder
. If you don’t think
private functions should be tested, there’s nothing in Rust that will compel
you to do so.
请注意, internal_adder
函数未标记为pub
。测试只是 Rust 代码, tests
模块只是另一个模块。正如我们在“引用模块树中的项目的路径”忽略部分中讨论的那样,子模块中的项目可以使用其祖先模块中的项目。在此测试中,我们use super::*
将所有tests
模块的父项纳入范围,然后测试可以调用internal_adder
。如果您认为不应该测试私有函数,那么 Rust 中没有任何内容会迫使您这样做。
Integration Tests 集成测试
In Rust, integration tests are entirely external to your library. They use your
library in the same way any other code would, which means they can only call
functions that are part of your library’s public API. Their purpose is to test
whether many parts of your library work together correctly. Units of code that
work correctly on their own could have problems when integrated, so test
coverage of the integrated code is important as well. To create integration
tests, you first need a tests directory.
在 Rust 中,集成测试完全在您的库外部。他们以与任何其他代码相同的方式使用您的库,这意味着他们只能调用属于您的库的公共 API 一部分的函数。它们的目的是测试库的许多部分是否可以正常工作。单独正常工作的代码单元在集成时可能会出现问题,因此集成代码的测试覆盖率也很重要。要创建集成测试,您首先需要一个测试目录。
The tests Directory
测试目录
We create a tests directory at the top level of our project directory, next
to src. Cargo knows to look for integration test files in this directory. We
can then make as many test files as we want, and Cargo will compile each of the
files as an individual crate.
我们在项目目录的顶层创建一个测试目录,位于src旁边。 Cargo 知道在此目录中查找集成测试文件。然后我们可以根据需要制作任意数量的测试文件,Cargo 会将每个文件编译为单独的 crate。
Let’s create an integration test. With the code in Listing 11-12 still in the
src/lib.rs file, make a tests directory, and create a new file named
tests/integration_test.rs. Your directory structure should look like this:
让我们创建一个集成测试。清单 11-12 中的代码仍在src/lib.rs文件中,创建一个测试目录,并创建一个名为tests/integration_test.rs的新文件。您的目录结构应如下所示:
adder
├── Cargo.lock
├── Cargo.toml
├── src
│ └── lib.rs
└── tests
└── integration_test.rs
Enter the code in Listing 11-13 into the tests/integration_test.rs file:
将清单11-13中的代码输入到tests/integration_test.rs文件中:
Filename: tests/integration_test.rs
文件名:测试/integration_test.rs
use adder::add_two;
#[test]
fn it_adds_two() {
assert_eq!(4, add_two(2));
}
Each file in the tests
directory is a separate crate, so we need to bring our
library into each test crate’s scope. For that reason we add use adder::add_two
at the top of the code, which we didn’t need in the unit
tests.tests
目录中的每个文件都是一个单独的板条箱,因此我们需要将我们的库纳入每个测试板条箱的范围。因此,我们在代码顶部添加了use adder::add_two
,这是我们在单元测试中不需要的。
We don’t need to annotate any code in tests/integration_test.rs with
#[cfg(test)]
. Cargo treats the tests
directory specially and compiles files
in this directory only when we run cargo test
. Run cargo test
now:
我们不需要用#[cfg(test)]
注释tests/integration_test.rs中的任何代码。 Cargo 特殊对待tests
目录,并且仅当我们运行cargo test
时才编译该目录中的文件。现在运行cargo test
:
$ 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
The three sections of output include the unit tests, the integration test, and
the doc tests. Note that if any test in a section fails, the following sections
will not be run. For example, if a unit test fails, there won’t be any output
for integration and doc tests because those tests will only be run if all unit
tests are passing.
输出的三个部分包括单元测试、集成测试和文档测试。请注意,如果某个部分中的任何测试失败,则不会运行以下部分。例如,如果单元测试失败,则集成和文档测试不会有任何输出,因为只有所有单元测试都通过时才会运行这些测试。
The first section for the unit tests is the same as we’ve been seeing: one line
for each unit test (one named internal
that we added in Listing 11-12) and
then a summary line for the unit tests.
单元测试的第一部分与我们所看到的相同:每个单元测试一行(我们在清单 11-12 中添加的一个名为“ internal
的行),然后是单元测试的摘要行。
The integration tests section starts with the line Running tests/integration_test.rs
. Next, there is a line for each test function in
that integration test and a summary line for the results of the integration
test just before the Doc-tests adder
section starts.
集成测试部分以Running tests/integration_test.rs
行开始。接下来,在Doc-tests adder
部分开始之前,该集成测试中的每个测试函数都有一行,还有一个集成测试结果的摘要行。
Each integration test file has its own section, so if we add more files in the
tests directory, there will be more integration test sections.
每个集成测试文件都有自己的部分,因此如果我们在测试目录中添加更多文件,将会有更多的集成测试部分。
We can still run a particular integration test function by specifying the test
function’s name as an argument to cargo test
. To run all the tests in a
particular integration test file, use the --test
argument of cargo test
followed by the name of the file:
我们仍然可以通过将测试函数的名称指定为cargo test
参数来运行特定的集成测试函数。要运行特定集成测试文件中的所有测试,请使用cargo test
的--test
参数,后跟文件名:
$ 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
This command runs only the tests in the tests/integration_test.rs file.
此命令仅运行tests/integration_test.rs文件中的测试。
Submodules in Integration Tests
集成测试中的子模块
As you add more integration tests, you might want to make more files in the
tests directory to help organize them; for example, you can group the test
functions by the functionality they’re testing. As mentioned earlier, each file
in the tests directory is compiled as its own separate crate, which is useful
for creating separate scopes to more closely imitate the way end users will be
using your crate. However, this means files in the tests directory don’t
share the same behavior as files in src do, as you learned in Chapter 7
regarding how to separate code into modules and files.
当您添加更多集成测试时,您可能希望在测试目录中创建更多文件以帮助组织它们;例如,您可以根据测试功能正在测试的功能对测试功能进行分组。如前所述, tests目录中的每个文件都被编译为自己单独的 crate,这对于创建单独的范围以更接近地模仿最终用户使用您的 crate 的方式非常有用。然而,这意味着测试目录中的文件与src中的文件不具有相同的行为,正如您在第 7 章中了解的如何将代码分离为模块和文件一样。
The different behavior of tests directory files is most noticeable when you
have a set of helper functions to use in multiple integration test files and
you try to follow the steps in the “Separating Modules into Different
Files” section of Chapter 7 to
extract them into a common module. For example, if we create tests/common.rs
and place a function named setup
in it, we can add some code to setup
that
we want to call from multiple test functions in multiple test files:
当您有一组辅助函数要在多个集成测试文件中使用并且您尝试按照第 7 章“将模块分离到不同文件”忽略部分中的步骤将它们提取到一个通用模块。例如,如果我们创建tests/common.rs并在其中放置一个名为setup
函数,我们可以向setup
添加一些我们想要从多个测试文件中的多个测试函数调用的代码:
Filename: tests/common.rs
文件名:测试/common.rs
pub fn setup() {
// setup code specific to your library's tests would go here
}
When we run the tests again, we’ll see a new section in the test output for the
common.rs file, even though this file doesn’t contain any test functions nor
did we call the setup
function from anywhere:
当我们再次运行测试时,我们将在common.rs文件的测试输出中看到一个新部分,即使该文件不包含任何测试函数,也没有从任何地方调用setup
函数:
$ 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
Having common
appear in the test results with running 0 tests
displayed for
it is not what we wanted. We just wanted to share some code with the other
integration test files.
让common
出现在测试结果中并显示running 0 tests
并不是我们想要的。我们只是想与其他集成测试文件共享一些代码。
To avoid having common
appear in the test output, instead of creating
tests/common.rs, we’ll create tests/common/mod.rs. The project directory
now looks like this:
为了避免common
出现在测试输出中,我们将创建tests/ common/mod.rs,而不是创建tests/common.rs 。项目目录现在如下所示:
├── Cargo.lock
├── Cargo.toml
├── src
│ └── lib.rs
└── tests
├── common
│ └── mod.rs
└── integration_test.rs
This is the older naming convention that Rust also understands that we
mentioned in the “Alternate File Paths” section of
Chapter 7. Naming the file this way tells Rust not to treat the common
module
as an integration test file. When we move the setup
function code into
tests/common/mod.rs and delete the tests/common.rs file, the section in the
test output will no longer appear. Files in subdirectories of the tests
directory don’t get compiled as separate crates or have sections in the test
output.
这是 Rust 也理解的旧命名约定,我们在第 7 章的“备用文件路径”忽略部分中提到过。以这种方式命名文件告诉 Rust 不要将common
模块视为集成测试文件。当我们将setup
功能代码移至tests/common/mod.rs并删除tests/common.rs文件时,测试输出中的该部分将不再出现。测试目录的子目录中的文件不会编译为单独的包,也不会在测试输出中包含部分。
After we’ve created tests/common/mod.rs, we can use it from any of the
integration test files as a module. Here’s an example of calling the setup
function from the it_adds_two
test in tests/integration_test.rs:
创建test/common/mod.rs后,我们可以将任何集成测试文件中的它用作模块。以下是从test/integration_test.rs中的it_adds_two
测试setup
函数的示例:
Filename: tests/integration_test.rs
文件名:测试/integration_test.rs
use adder;
mod common;
#[test]
fn it_adds_two() {
common::setup();
assert_eq!(4, adder::add_two(2));
}
Note that the mod common;
declaration is the same as the module declaration
we demonstrated in Listing 7-21. Then in the test function, we can call the
common::setup()
function.
注意mod common;
声明与我们在清单 7-21 中演示的模块声明相同。然后在测试函数中,我们可以调用common::setup()
函数。
Integration Tests for Binary Crates
二进制 crate 的集成测试
If our project is a binary crate that only contains a src/main.rs file and
doesn’t have a src/lib.rs file, we can’t create integration tests in the
tests directory and bring functions defined in the src/main.rs file into
scope with a use
statement. Only library crates expose functions that other
crates can use; binary crates are meant to be run on their own.
如果我们的项目是一个只包含src/main.rs文件而没有src/lib.rs文件的二进制 crate,则我们无法在测试目录中创建集成测试并引入src/main中定义的函数use
语句将.rs文件放入范围内。只有库 crate 才会公开其他 crate 可以使用的函数;二进制板条箱应该独立运行。
This is one of the reasons Rust projects that provide a binary have a
straightforward src/main.rs file that calls logic that lives in the
src/lib.rs file. Using that structure, integration tests can test the
library crate with use
to make the important functionality available.
If the important functionality works, the small amount of code in the
src/main.rs file will work as well, and that small amount of code doesn’t
need to be tested.
这是提供二进制文件的 Rust 项目有一个简单的src/main.rs文件的原因之一,该文件调用src/lib.rs文件中的逻辑。使用该结构,集成测试可以测试库箱的use
,以使重要的功能可用。如果重要功能有效,则src/main.rs文件中的少量代码也将有效,并且不需要测试该少量代码。
Summary 概括
Rust’s testing features provide a way to specify how code should function to
ensure it continues to work as you expect, even as you make changes. Unit tests
exercise different parts of a library separately and can test private
implementation details. Integration tests check that many parts of the library
work together correctly, and they use the library’s public API to test the code
in the same way external code will use it. Even though Rust’s type system and
ownership rules help prevent some kinds of bugs, tests are still important to
reduce logic bugs having to do with how your code is expected to behave.
Rust 的测试功能提供了一种指定代码应如何运行的方法,以确保即使您进行更改,它也能继续按您的预期工作。单元测试分别运行库的不同部分,并且可以测试私有实现细节。集成测试检查库的许多部分是否正确协同工作,并且它们使用库的公共 API 来测试代码,就像外部代码使用它一样。尽管 Rust 的类型系统和所有权规则有助于防止某些类型的错误,但测试对于减少与代码预期行为方式相关的逻辑错误仍然很重要。
Let’s combine the knowledge you learned in this chapter and in previous
chapters to work on a project!
让我们结合您在本章和前面章节中学到的知识来完成一个项目!
An I/O Project: Building a Command Line Program
I/O 项目:构建命令行程序
This chapter is a recap of the many skills you’ve learned so far and an
exploration of a few more standard library features. We’ll build a command line
tool that interacts with file and command line input/output to practice some of
the Rust concepts you now have under your belt.
本章回顾了您迄今为止学到的许多技能,并探索了更多标准库功能。我们将构建一个与文件和命令行输入/输出交互的命令行工具,以练习您现在掌握的一些 Rust 概念。
Rust’s speed, safety, single binary output, and cross-platform support make it
an ideal language for creating command line tools, so for our project, we’ll
make our own version of the classic command line search tool grep
(globally search a regular expression and print). In the
simplest use case, grep
searches a specified file for a specified string. To
do so, grep
takes as its arguments a file path and a string. Then it reads
the file, finds lines in that file that contain the string argument, and prints
those lines.
Rust 的速度、安全性、单一二进制输出和跨平台支持使其成为创建命令行工具的理想语言,因此对于我们的项目,我们将制作我们自己的经典命令行搜索工具grep
版本(全局搜索正则表达式和打印)。在最简单的用例中, grep
在指定文件中搜索指定字符串。为此, grep
将文件路径和字符串作为其参数。然后它读取该文件,查找该文件中包含字符串参数的行,并打印这些行。
Along the way, we’ll show how to make our command line tool use the terminal
features that many other command line tools use. We’ll read the value of an
environment variable to allow the user to configure the behavior of our tool.
We’ll also print error messages to the standard error console stream (stderr
)
instead of standard output (stdout
), so, for example, the user can redirect
successful output to a file while still seeing error messages onscreen.
在此过程中,我们将展示如何使我们的命令行工具使用许多其他命令行工具使用的终端功能。我们将读取环境变量的值,以允许用户配置我们工具的行为。我们还将错误消息打印到标准错误控制台流 ( stderr
) 而不是标准输出 ( stdout
),因此,例如,用户可以将成功的输出重定向到文件,同时仍然在屏幕上看到错误消息。
One Rust community member, Andrew Gallant, has already created a fully
featured, very fast version of grep
, called ripgrep
. By comparison, our
version will be fairly simple, but this chapter will give you some of the
background knowledge you need to understand a real-world project such as
ripgrep
.
Rust 社区成员 Andrew Gallant 已经创建了一个功能齐全、速度非常快的grep
版本,称为ripgrep
。相比之下,我们的版本将相当简单,但本章将为您提供一些理解真实项目(例如ripgrep
所需的背景知识。
Our grep
project will combine a number of concepts you’ve learned so far:
我们的grep
项目将结合您迄今为止学到的许多概念:
- Organizing code (using what you learned about modules in Chapter 7)
组织代码(使用您在第 7 章中学到的有关模块的知识ignore) - Using vectors and strings (collections, Chapter 8)
使用向量和字符串(集合,第 8 章忽略) - Handling errors (Chapter 9)
处理错误(第9章忽略) - Using traits and lifetimes where appropriate (Chapter 10)
在适当的情况下使用特征和生命周期(第10章忽略) - Writing tests (Chapter 11)
编写测试(第11章忽略)
We’ll also briefly introduce closures, iterators, and trait objects, which
Chapters 13 and 17 will cover in
detail.
我们还将简要介绍闭包、迭代器和特征对象,第13章忽略和第 17 章将详细介绍这些内容。
Accepting Command Line Arguments
接受命令行参数
Let’s create a new project with, as always, cargo new
. We’ll call our project
minigrep
to distinguish it from the grep
tool that you might already have
on your system.
让我们像往常一样使用cargo new
创建一个新项目。我们将我们的项目称为minigrep
以将其与您系统上可能已有的grep
工具区分开来。
$ cargo new minigrep
Created binary (application) `minigrep` project
$ cd minigrep
The first task is to make minigrep
accept its two command line arguments: the
file path and a string to search for. That is, we want to be able to run our
program with cargo run
, two hyphens to indicate the following arguments are
for our program rather than for cargo
, a string to search for, and a path to
a file to search in, like so:
第一个任务是让minigrep
接受它的两个命令行参数:文件路径和要搜索的字符串。也就是说,我们希望能够使用cargo run
来运行我们的程序,两个连字符表示以下参数是我们的程序而不是cargo
,一个要搜索的字符串,以及一个要搜索的文件的路径,如下所示:
$ cargo run -- searchstring example-filename.txt
Right now, the program generated by cargo new
cannot process arguments we
give it. Some existing libraries on crates.io can help
with writing a program that accepts command line arguments, but because you’re
just learning this concept, let’s implement this capability ourselves.
目前,由cargo new
生成的程序无法处理我们给它的参数。 crates.io上的一些现有库可以帮助编写接受命令行参数的程序,但因为您刚刚学习这个概念,所以让我们自己实现此功能。
Reading the Argument Values
读取参数值
To enable minigrep
to read the values of command line arguments we pass to
it, we’ll need the std::env::args
function provided in Rust’s standard
library. This function returns an iterator of the command line arguments passed
to minigrep
. We’ll cover iterators fully in Chapter 13. For now, you only need to know two details about iterators: iterators
produce a series of values, and we can call the collect
method on an iterator
to turn it into a collection, such as a vector, that contains all the elements
the iterator produces.
为了使minigrep
能够读取我们传递给它的命令行参数的值,我们需要 Rust 标准库中提供的std::env::args
函数。此函数返回传递给minigrep
的命令行参数的迭代器。我们将在第 13 章中全面介绍迭代器。现在,您只需要了解有关迭代器的两个细节:迭代器会产生一系列值,我们可以调用迭代器上的collect
方法将其转换为集合,例如向量,其中包含迭代器产生的所有元素。
The code in Listing 12-1 allows your minigrep
program to read any command
line arguments passed to it and then collect the values into a vector.
清单 12-1 中的代码允许您的minigrep
程序读取传递给它的任何命令行参数,然后将这些值收集到一个向量中。
Filename: src/main.rs 文件名:src/main.rs
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
dbg!(args);
}
First, we bring the std::env
module into scope with a use
statement so we
can use its args
function. Notice that the std::env::args
function is
nested in two levels of modules. As we discussed in Chapter
7, in cases where the desired function is
nested in more than one module, we’ve chosen to bring the parent module into
scope rather than the function. By doing so, we can easily use other functions
from std::env
. It’s also less ambiguous than adding use std::env::args
and
then calling the function with just args
, because args
might easily be
mistaken for a function that’s defined in the current module.
首先,我们use
语句将std::env
模块引入作用域,以便我们可以使用它的args
函数。请注意, std::env::args
函数嵌套在两层模块中。正如我们在第 7 章中讨论的ignore,如果所需的函数嵌套在多个模块中,我们选择将父模块而不是函数纳入作用域。通过这样做,我们可以轻松地使用std::env
中的其他函数。它也比添加use std::env::args
然后仅使用args
调用函数更明确,因为args
可能很容易被误认为是当前模块中定义的函数。
The args
Function and Invalid Unicode
args
函数和无效的 Unicode
Note that std::env::args
will panic if any argument contains invalid
Unicode. If your program needs to accept arguments containing invalid
Unicode, use std::env::args_os
instead. That function returns an iterator
that produces OsString
values instead of String
values. We’ve chosen to
use std::env::args
here for simplicity, because OsString
values differ
per platform and are more complex to work with than String
values.
请注意,如果任何参数包含无效的 Unicode, std::env::args
将会出现恐慌。如果您的程序需要接受包含无效 Unicode 的参数,请改用std::env::args_os
。该函数返回一个迭代器,该迭代器生成OsString
值而不是String
值。为了简单起见,我们选择在这里使用std::env::args
,因为OsString
值因平台而异,并且比String
值使用起来更复杂。
On the first line of main
, we call env::args
, and we immediately use
collect
to turn the iterator into a vector containing all the values produced
by the iterator. We can use the collect
function to create many kinds of
collections, so we explicitly annotate the type of args
to specify that we
want a vector of strings. Although we very rarely need to annotate types in
Rust, collect
is one function you do often need to annotate because Rust
isn’t able to infer the kind of collection you want.
在main
的第一行,我们调用env::args
,然后立即使用collect
将迭代器转换为包含迭代器产生的所有值的向量。我们可以使用collect
函数创建多种集合,因此我们显式注释args
的类型以指定我们想要一个字符串向量。尽管我们很少需要在 Rust 中注释类型,但collect
是您经常需要注释的函数之一,因为 Rust 无法推断您想要的集合类型。
Finally, we print the vector using the debug macro. Let’s try running the code
first with no arguments and then with two arguments:
最后,我们使用调试宏打印向量。让我们尝试先不带参数运行代码,然后使用两个参数运行代码:
$ 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",
]
$ 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",
]
Notice that the first value in the vector is "target/debug/minigrep"
, which
is the name of our binary. This matches the behavior of the arguments list in
C, letting programs use the name by which they were invoked in their execution.
It’s often convenient to have access to the program name in case you want to
print it in messages or change behavior of the program based on what command
line alias was used to invoke the program. But for the purposes of this
chapter, we’ll ignore it and save only the two arguments we need.
请注意,向量中的第一个值是"target/debug/minigrep"
,这是我们的二进制文件的名称。这与 C 中参数列表的行为相匹配,让程序使用在执行中调用它们的名称。如果您想在消息中打印程序名称或根据用于调用程序的命令行别名更改程序的行为,访问程序名称通常很方便。但出于本章的目的,我们将忽略它并仅保存我们需要的两个参数。
Saving the Argument Values in Variables
将参数值保存在变量中
The program is currently able to access the values specified as command line
arguments. Now we need to save the values of the two arguments in variables so
we can use the values throughout the rest of the program. We do that in Listing
12-2.
该程序当前能够访问指定为命令行参数的值。现在我们需要将两个参数的值保存在变量中,以便我们可以在程序的其余部分使用这些值。我们在清单 12-2 中做到了这一点。
Filename: src/main.rs 文件名:src/main.rs
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let query = &args[1];
let file_path = &args[2];
println!("Searching for {query}");
println!("In file {file_path}");
}
As we saw when we printed the vector, the program’s name takes up the first
value in the vector at args[0]
, so we’re starting arguments at index 1
. The
first argument minigrep
takes is the string we’re searching for, so we put a
reference to the first argument in the variable query
. The second argument
will be the file path, so we put a reference to the second argument in the
variable file_path
.
正如我们在打印向量时所看到的,程序的名称占据了向量中args[0]
处的第一个值,因此我们从索引1
处开始参数。 minigrep
采用的第一个参数是我们正在搜索的字符串,因此我们将第一个参数的引用放入变量query
中。第二个参数将是文件路径,因此我们将对第二个参数的引用放入变量file_path
中。
We temporarily print the values of these variables to prove that the code is
working as we intend. Let’s run this program again with the arguments test
and sample.txt
:
我们暂时打印这些变量的值,以证明代码按我们的预期运行。让我们使用参数test
和sample.txt
再次运行该程序:
$ 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
Great, the program is working! The values of the arguments we need are being
saved into the right variables. Later we’ll add some error handling to deal
with certain potential erroneous situations, such as when the user provides no
arguments; for now, we’ll ignore that situation and work on adding file-reading
capabilities instead.
太好了,程序正在运行!我们需要的参数值被保存到正确的变量中。稍后我们将添加一些错误处理来处理某些潜在的错误情况,例如当用户没有提供参数时;现在,我们将忽略这种情况并致力于添加文件读取功能。
Reading a File 读取文件
Now we’ll add functionality to read the file specified in the file_path
argument. First, we need a sample file to test it with: we’ll use a file with a
small amount of text over multiple lines with some repeated words. Listing 12-3
has an Emily Dickinson poem that will work well! Create a file called
poem.txt at the root level of your project, and enter the poem “I’m Nobody!
Who are you?”
现在我们将添加功能来读取file_path
参数中指定的文件。首先,我们需要一个示例文件来测试它:我们将使用一个包含多行少量文本和一些重复单词的文件。清单 12-3 有一首 Emily Dickinson 的诗,效果很好!在项目的根级别创建一个名为诗歌.txt的文件,并输入诗“我是无名小卒!你是谁?
Filename: poem.txt 文件名: 诗.txt
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!
With the text in place, edit src/main.rs and add code to read the file, as
shown in Listing 12-4.
文本就位后,编辑src/main.rs并添加代码来读取该文件,如清单 12-4 所示。
Filename: src/main.rs 文件名:src/main.rs
First, we bring in a relevant part of the standard library with a use
statement: we need std::fs
to handle files.
首先,我们通过use
语句引入标准库的相关部分:我们需要std::fs
来处理文件。
In main
, the new statement fs::read_to_string
takes the file_path
, opens
that file, and returns a std::io::Result<String>
of the file’s contents.
在main
中,新语句fs::read_to_string
接受file_path
,打开该文件,并返回文件内容的std::io::Result<String>
。
After that, we again add a temporary println!
statement that prints the value
of contents
after the file is read, so we can check that the program is
working so far.
之后,我们再次添加一个临时println!
语句在读取文件后打印contents
的值,这样我们就可以检查程序到目前为止是否正常工作。
Let’s run this code with any string as the first command line argument (because
we haven’t implemented the searching part yet) and the poem.txt file as the
second argument:
让我们使用任意字符串作为第一个命令行参数(因为我们还没有实现搜索部分)并使用诗歌.txt文件作为第二个参数来运行此代码:
$ 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!
Great! The code read and then printed the contents of the file. But the code
has a few flaws. At the moment, the main
function has multiple
responsibilities: generally, functions are clearer and easier to maintain if
each function is responsible for only one idea. The other problem is that we’re
not handling errors as well as we could. The program is still small, so these
flaws aren’t a big problem, but as the program grows, it will be harder to fix
them cleanly. It’s good practice to begin refactoring early on when developing
a program, because it’s much easier to refactor smaller amounts of code. We’ll
do that next.
伟大的!该代码读取并打印文件的内容。但该代码有一些缺陷。目前, main
函数具有多重职责:一般来说,如果每个函数只负责一个想法,那么函数会更清晰,更容易维护。另一个问题是我们没有尽力处理错误。程序还很小,所以这些缺陷并不是什么大问题,但随着程序的增长,彻底修复它们就会变得更加困难。在开发程序时尽早开始重构是一种很好的做法,因为重构少量代码会更容易。我们接下来就这样做。
Refactoring to Improve Modularity and Error Handling
重构以改进模块化和错误处理
To improve our program, we’ll fix four problems that have to do with the
program’s structure and how it’s handling potential errors. First, our main
function now performs two tasks: it parses arguments and reads files. As our
program grows, the number of separate tasks the main
function handles will
increase. As a function gains responsibilities, it becomes more difficult to
reason about, harder to test, and harder to change without breaking one of its
parts. It’s best to separate functionality so each function is responsible for
one task.
为了改进我们的程序,我们将修复与程序结构及其处理潜在错误的方式有关的四个问题。首先,我们的main
函数现在执行两项任务:解析参数和读取文件。随着程序的增长, main
函数处理的单独任务的数量将会增加。当一个功能获得职责时,它会变得更难推理、更难测试、更难在不破坏其任何部分的情况下进行更改。最好将功能分开,以便每个功能负责一项任务。
This issue also ties into the second problem: although query
and file_path
are configuration variables to our program, variables like contents
are used
to perform the program’s logic. The longer main
becomes, the more variables
we’ll need to bring into scope; the more variables we have in scope, the harder
it will be to keep track of the purpose of each. It’s best to group the
configuration variables into one structure to make their purpose clear.
这个问题也与第二个问题相关:虽然query
和file_path
是我们程序的配置变量,但像contents
这样的变量用于执行程序的逻辑。 main
变得越长,我们需要引入作用域的变量就越多;范围内的变量越多,跟踪每个变量的目的就越困难。最好将配置变量分组到一个结构中,以明确其目的。
The third problem is that we’ve used expect
to print an error message when
reading the file fails, but the error message just prints Should have been able to read the file
. Reading a file can fail in a number of ways: for
example, the file could be missing, or we might not have permission to open it.
Right now, regardless of the situation, we’d print the same error message for
everything, which wouldn’t give the user any information!
第三个问题是,我们已经使用expect
在读取文件失败时打印错误消息,但是错误消息只是打印Should have been able to read the file
。读取文件可能会因多种原因而失败:例如,文件可能丢失,或者我们可能没有打开它的权限。现在,无论情况如何,我们都会为所有内容打印相同的错误消息,这不会向用户提供任何信息!
Fourth, we use expect
to handle an error, and if the user runs our program
without specifying enough arguments, they’ll get an index out of bounds
error
from Rust that doesn’t clearly explain the problem. It would be best if all the
error-handling code were in one place so future maintainers had only one place
to consult the code if the error-handling logic needed to change. Having all the
error-handling code in one place will also ensure that we’re printing messages
that will be meaningful to our end users.
第四,我们使用expect
来处理错误,如果用户在没有指定足够参数的情况下运行我们的程序,他们会从Rust中得到一个index out of bounds
错误,而这个错误并不能清楚地解释问题。最好将所有错误处理代码都放在一处,以便未来的维护人员在错误处理逻辑需要更改时只有一处可以查阅代码。将所有错误处理代码放在一处还可以确保我们打印的消息对最终用户有意义。
Let’s address these four problems by refactoring our project.
让我们通过重构我们的项目来解决这四个问题。
Separation of Concerns for Binary Projects
二进制项目的关注点分离
The organizational problem of allocating responsibility for multiple tasks to
the main
function is common to many binary projects. As a result, the Rust
community has developed guidelines for splitting the separate concerns of a
binary program when main
starts getting large. This process has the following
steps:
将多个任务的责任分配给main
函数的组织问题是许多二进制项目的常见问题。因此,Rust 社区制定了当main
开始变大时分割二进制程序的单独关注点的指南。该过程有以下步骤:
- Split your program into a main.rs and a lib.rs and move your program’s
logic to lib.rs.
将程序拆分为main.rs和lib.rs ,并将程序的逻辑移至lib.rs 。 - As long as your command line parsing logic is small, it can remain in
main.rs.
只要你的命令行解析逻辑很小,它就可以保留在main.rs中。 - When the command line parsing logic starts getting complicated, extract it
from main.rs and move it to lib.rs.
当命令行解析逻辑开始变得复杂时,将其从main.rs中提取并将其移动到lib.rs 。
The responsibilities that remain in the main
function after this process
should be limited to the following:
此过程之后保留在main
函数中的职责应限于以下内容:
- Calling the command line parsing logic with the argument values
使用参数值调用命令行解析逻辑 - Setting up any other configuration
设置任何其他配置 - Calling a
run
function in lib.rs
调用lib.rs中的run
函数 - Handling the error if
run
returns an error
如果run
返回错误,则处理错误
This pattern is about separating concerns: main.rs handles running the
program, and lib.rs handles all the logic of the task at hand. Because you
can’t test the main
function directly, this structure lets you test all of
your program’s logic by moving it into functions in lib.rs. The code that
remains in main.rs will be small enough to verify its correctness by reading
it. Let’s rework our program by following this process.
这种模式是关于分离关注点: main.rs处理运行程序, lib.rs处理手头任务的所有逻辑。因为您无法直接测试main
函数,所以此结构允许您通过将程序的所有逻辑移动到lib.rs中的函数中来测试它。 main.rs中保留的代码足够小,可以通过读取来验证其正确性。让我们按照这个过程重新编写我们的程序。
Extracting the Argument Parser
提取参数解析器
We’ll extract the functionality for parsing arguments into a function that
main
will call to prepare for moving the command line parsing logic to
src/lib.rs. Listing 12-5 shows the new start of main
that calls a new
function parse_config
, which we’ll define in src/main.rs for the moment.
我们将把解析参数的功能提取到main
将调用的函数中,以准备将命令行解析逻辑移动到src/lib.rs 。清单 12-5 显示了main
的新开始,它调用了一个新函数parse_config
,我们暂时在src/main.rs中定义该函数。
Filename: src/main.rs 文件名:src/main.rs
We’re still collecting the command line arguments into a vector, but instead of
assigning the argument value at index 1 to the variable query
and the
argument value at index 2 to the variable file_path
within the main
function, we pass the whole vector to the parse_config
function. The
parse_config
function then holds the logic that determines which argument
goes in which variable and passes the values back to main
. We still create
the query
and file_path
variables in main
, but main
no longer has the
responsibility of determining how the command line arguments and variables
correspond.
我们仍然将命令行参数收集到一个向量中,但我们不是将索引 1 处的参数值分配给变量query
,将索引 2 处的参数值分配给main
函数中的变量file_path
,而是将整个向量传递给parse_config
函数。然后, parse_config
函数保存确定哪个参数放入哪个变量并将值传递回main
逻辑。我们仍然在main
中创建query
和file_path
变量,但main
不再负责确定命令行参数和变量如何对应。
This rework may seem like overkill for our small program, but we’re refactoring
in small, incremental steps. After making this change, run the program again to
verify that the argument parsing still works. It’s good to check your progress
often, to help identify the cause of problems when they occur.
对于我们的小程序来说,这种返工似乎有些过头了,但我们正在以小的、渐进的步骤进行重构。进行此更改后,再次运行程序以验证参数解析是否仍然有效。经常检查您的进度是很好的做法,有助于在问题发生时确定问题的原因。
Grouping Configuration Values
对配置值进行分组
We can take another small step to improve the parse_config
function further.
At the moment, we’re returning a tuple, but then we immediately break that
tuple into individual parts again. This is a sign that perhaps we don’t have
the right abstraction yet.
我们可以再采取一小步来进一步改进parse_config
函数。目前,我们正在返回一个元组,但随后我们立即再次将该元组分解为各个部分。这表明我们可能还没有正确的抽象。
Another indicator that shows there’s room for improvement is the config
part
of parse_config
, which implies that the two values we return are related and
are both part of one configuration value. We’re not currently conveying this
meaning in the structure of the data other than by grouping the two values into
a tuple; we’ll instead put the two values into one struct and give each of the
struct fields a meaningful name. Doing so will make it easier for future
maintainers of this code to understand how the different values relate to each
other and what their purpose is.
显示还有改进空间的另一个指标是parse_config
的config
部分,这意味着我们返回的两个值是相关的,并且都是一个配置值的一部分。目前,除了将两个值分组到一个元组中之外,我们还没有在数据结构中传达这种含义;相反,我们会将这两个值放入一个结构体中,并为每个结构体字段指定一个有意义的名称。这样做将使该代码的未来维护者更容易理解不同值如何相互关联以及它们的目的是什么。
Listing 12-6 shows the improvements to the parse_config
function.
清单 12-6 显示了对parse_config
函数的改进。
Filename: src/main.rs 文件名:src/main.rs
We’ve added a struct named Config
defined to have fields named query
and
file_path
. The signature of parse_config
now indicates that it returns a
Config
value. In the body of parse_config
, where we used to return
string slices that reference String
values in args
, we now define Config
to contain owned String
values. The args
variable in main
is the owner of
the argument values and is only letting the parse_config
function borrow
them, which means we’d violate Rust’s borrowing rules if Config
tried to take
ownership of the values in args
.
我们添加了一个名为Config
结构,定义了名为query
和file_path
的字段。 parse_config
的签名现在表明它返回一个Config
值。在parse_config
的主体中,我们过去常常返回引用args
中的String
值的字符串切片,现在我们定义Config
来包含拥有的String
值。 main
中的args
变量是参数值的所有者,并且只允许parse_config
函数借用它们,这意味着如果Config
尝试获取args
中值的所有权,我们就会违反 Rust 的借用规则。
There are a number of ways we could manage the String
data; the easiest,
though somewhat inefficient, route is to call the clone
method on the values.
This will make a full copy of the data for the Config
instance to own, which
takes more time and memory than storing a reference to the string data.
However, cloning the data also makes our code very straightforward because we
don’t have to manage the lifetimes of the references; in this circumstance,
giving up a little performance to gain simplicity is a worthwhile trade-off.
我们可以通过多种方式管理String
数据;最简单但效率有些低的方法是对值调用clone
方法。这将为Config
实例创建数据的完整副本以供其拥有,这比存储对字符串数据的引用需要更多的时间和内存。然而,克隆数据也使我们的代码变得非常简单,因为我们不必管理引用的生命周期;在这种情况下,放弃一点性能以获得简单性是值得的权衡。
The Trade-Offs of Using clone
使用clone
的权衡
There’s a tendency among many Rustaceans to avoid using clone
to fix
ownership problems because of its runtime cost. In
Chapter 13, you’ll learn how to use more efficient
methods in this type of situation. But for now, it’s okay to copy a few
strings to continue making progress because you’ll make these copies only
once and your file path and query string are very small. It’s better to have
a working program that’s a bit inefficient than to try to hyperoptimize code
on your first pass. As you become more experienced with Rust, it’ll be
easier to start with the most efficient solution, but for now, it’s
perfectly acceptable to call clone
.
由于运行时成本,许多 Rustaceans 倾向于避免使用clone
来解决所有权问题。在第 13 章中,你将学习如何在这种情况下使用更有效的方法。但目前,可以复制一些字符串以继续取得进展,因为您只需复制一次这些副本,并且您的文件路径和查询字符串非常小。最好有一个效率有点低的工作程序,而不是在第一次就尝试对代码进行超级优化。随着您对 Rust 的经验越来越丰富,从最有效的解决方案开始会变得更容易,但现在,调用clone
是完全可以接受的。
We’ve updated main
so it places the instance of Config
returned by
parse_config
into a variable named config
, and we updated the code that
previously used the separate query
and file_path
variables so it now uses
the fields on the Config
struct instead.
我们更新了main
,因此它将parse_config
返回的Config
实例放入名为config
的变量中,并且我们更新了之前使用单独的query
和file_path
变量的代码,因此它现在使用Config
结构体上的字段。
Now our code more clearly conveys that query
and file_path
are related and
that their purpose is to configure how the program will work. Any code that
uses these values knows to find them in the config
instance in the fields
named for their purpose.
现在我们的代码更清楚地传达了query
和file_path
是相关的,并且它们的目的是配置程序的工作方式。任何使用这些值的代码都知道在config
实例中为其目的命名的字段中找到它们。
Creating a Constructor for Config
为Config
创建构造函数
So far, we’ve extracted the logic responsible for parsing the command line
arguments from main
and placed it in the parse_config
function. Doing so
helped us to see that the query
and file_path
values were related and that
relationship should be conveyed in our code. We then added a Config
struct to
name the related purpose of query
and file_path
and to be able to return the
values’ names as struct field names from the parse_config
function.
到目前为止,我们已经从main
中提取了负责解析命令行参数的逻辑,并将其放置在parse_config
函数中。这样做可以帮助我们看到query
和file_path
值是相关的,并且应该在我们的代码中传达这种关系。然后,我们添加了一个Config
结构体来命名query
和file_path
的相关用途,并能够从parse_config
函数将值的名称作为结构体字段名称返回。
So now that the purpose of the parse_config
function is to create a Config
instance, we can change parse_config
from a plain function to a function
named new
that is associated with the Config
struct. Making this change
will make the code more idiomatic. We can create instances of types in the
standard library, such as String
, by calling String::new
. Similarly, by
changing parse_config
into a new
function associated with Config
, we’ll
be able to create instances of Config
by calling Config::new
. Listing 12-7
shows the changes we need to make.
现在parse_config
函数的目的是创建一个Config
实例,我们可以将parse_config
从普通函数更改为与Config
结构体关联的名为new
函数。进行此更改将使代码更加惯用。我们可以通过调用String::new
创建标准库中类型的实例,例如String
。类似地,通过将parse_config
更改为与Config
关联的new
函数,我们将能够通过调用Config::new
创建Config
的实例。清单 12-7 显示了我们需要进行的更改。
Filename: src/main.rs 文件名:src/main.rs
We’ve updated main
where we were calling parse_config
to instead call
Config::new
. We’ve changed the name of parse_config
to new
and moved it
within an impl
block, which associates the new
function with Config
. Try
compiling this code again to make sure it works.
我们更新了main
调用parse_config
位置,改为调用Config::new
。我们已将parse_config
的名称更改为new
并将其移至impl
块内,该块将new
函数与Config
相关联。尝试再次编译此代码以确保其有效。
Fixing the Error Handling
修复错误处理
Now we’ll work on fixing our error handling. Recall that attempting to access
the values in the args
vector at index 1 or index 2 will cause the program to
panic if the vector contains fewer than three items. Try running the program
without any arguments; it will look like this:
现在我们将致力于修复错误处理。回想一下,如果向量包含的项少于三个,尝试访问args
向量中索引 1 或索引 2 处的值将导致程序出现恐慌。尝试在不带任何参数的情况下运行该程序;它看起来像这样:
$ 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
The line index out of bounds: the len is 1 but the index is 1
is an error
message intended for programmers. It won’t help our end users understand what
they should do instead. Let’s fix that now.
行index out of bounds: the len is 1 but the index is 1
是针对程序员的错误消息。它不会帮助我们的最终用户了解他们应该做什么。现在让我们解决这个问题。
Improving the Error Message
改进错误消息
In Listing 12-8, we add a check in the new
function that will verify that the
slice is long enough before accessing index 1 and 2. If the slice isn’t long
enough, the program panics and displays a better error message.
在清单 12-8 中,我们在new
函数中添加了一个检查,该检查将在访问索引 1 和 2 之前验证切片是否足够长。如果切片不够长,程序会出现混乱并显示更好的错误消息。
Filename: src/main.rs 文件名:src/main.rs
This code is similar to the Guess::new
function we wrote in Listing
9-13, where we called panic!
when the
value
argument was out of the range of valid values. Instead of checking for
a range of values here, we’re checking that the length of args
is at least 3
and the rest of the function can operate under the assumption that this
condition has been met. If args
has fewer than three items, this condition
will be true, and we call the panic!
macro to end the program immediately.
这段代码类似于我们在清单 9-13ignore 中编写的Guess::new
函数,我们在其中调用了panic!
当value
参数超出有效值范围时。我们不是在这里检查值的范围,而是检查args
的长度是否至少为 3,并且函数的其余部分可以在满足此条件的假设下运行。如果args
少于三个项目,则此条件将为真,我们称之为panic!
立即结束程序的宏。
With these extra few lines of code in new
, let’s run the program without any
arguments again to see what the error looks like now:
使用new
中的这些额外的几行代码,让我们再次运行不带任何参数的程序,看看错误现在是什么样子:
$ 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
This output is better: we now have a reasonable error message. However, we also
have extraneous information we don’t want to give to our users. Perhaps using
the technique we used in Listing 9-13 isn’t the best to use here: a call to
panic!
is more appropriate for a programming problem than a usage problem,
as discussed in Chapter 9. Instead,
we’ll use the other technique you learned about in Chapter 9—returning a
Result
that indicates either success or an error.
这个输出更好了:我们现在有一个合理的错误消息。然而,我们也有一些不想提供给用户的无关信息。也许我们在清单 9-13 中使用的技术并不是最好的选择:调用panic!
比使用问题更适合编程问题,如第 9 章中讨论的ignore。相反,我们将使用您在第 9 章中学到的其他技术- 返回指示成功或错误的Result
忽略。
Returning a Result
Instead of Calling panic!
返回Result
而不是引发panic!
We can instead return a Result
value that will contain a Config
instance in
the successful case and will describe the problem in the error case. We’re also
going to change the function name from new
to build
because many
programmers expect new
functions to never fail. When Config::build
is
communicating to main
, we can use the Result
type to signal there was a
problem. Then we can change main
to convert an Err
variant into a more
practical error for our users without the surrounding text about thread 'main'
and RUST_BACKTRACE
that a call to panic!
causes.
相反,我们可以返回一个Result
值,该值在成功情况下包含Config
实例,在错误情况下描述问题。我们还将函数名称从new
更改为build
因为许多程序员希望new
函数永远不会失败。当Config::build
与main
通信时,我们可以使用Result
类型来表示存在问题。然后我们可以更改main
将Err
变体转换为对我们的用户来说更实际的错误,而无需围绕thread 'main'
和RUST_BACKTRACE
的文本来调用panic!
原因。
Listing 12-9 shows the changes we need to make to the return value of the
function we’re now calling Config::build
and the body of the function needed
to return a Result
. Note that this won’t compile until we update main
as
well, which we’ll do in the next listing.
清单 12-9 显示了我们需要对我们现在调用Config::build
函数的返回值进行的更改以及返回Result
所需的函数体。请注意,直到我们也更新main
之前,这不会编译,我们将在下一个清单中执行此操作。
Filename: src/main.rs 文件名:src/main.rs
Our build
function returns a Result
with a Config
instance in the success
case and a &'static str
in the error case. Our error values will always be
string literals that have the 'static
lifetime.
我们的build
函数在成功情况下Result
一个Config
实例,在错误情况下返回一个&'static str
。我们的错误值将始终是具有'static
生命周期”的字符串文字。
We’ve made two changes in the body of the function: instead of calling panic!
when the user doesn’t pass enough arguments, we now return an Err
value, and
we’ve wrapped the Config
return value in an Ok
. These changes make the
function conform to its new type signature.
我们对函数体进行了两处更改:而不是调用panic!
当用户没有传递足够的参数时,我们现在返回一个Err
值,并且我们将Config
返回值包装在Ok
中。这些更改使函数符合其新的类型签名。
Returning an Err
value from Config::build
allows the main
function to
handle the Result
value returned from the build
function and exit the
process more cleanly in the error case.
从Config::build
返回Err
值允许main
函数处理从build
函数返回的Result
值,并在错误情况下更干净地退出进程。
Calling Config::build
and Handling Errors
调用Config::build
并处理错误
To handle the error case and print a user-friendly message, we need to update
main
to handle the Result
being returned by Config::build
, as shown in
Listing 12-10. We’ll also take the responsibility of exiting the command line
tool with a nonzero error code away from panic!
and instead implement it by
hand. A nonzero exit status is a convention to signal to the process that
called our program that the program exited with an error state.
为了处理错误情况并打印用户友好的消息,我们需要更新main
以处理Config::build
返回的Result
,如清单 12-10 所示。我们还将负责以非零错误代码退出命令行工具,以避免panic!
而是手动实现它。非零退出状态是一种约定,用于向调用我们程序的进程发出信号,表明该程序以错误状态退出。
Filename: src/main.rs 文件名:src/main.rs
In this listing, we’ve used a method we haven’t covered in detail yet:
unwrap_or_else
, which is defined on Result<T, E>
by the standard library.
Using unwrap_or_else
allows us to define some custom, non-panic!
error
handling. If the Result
is an Ok
value, this method’s behavior is similar
to unwrap
: it returns the inner value Ok
is wrapping. However, if the value
is an Err
value, this method calls the code in the closure, which is an
anonymous function we define and pass as an argument to unwrap_or_else
. We’ll
cover closures in more detail in Chapter 13. For now,
you just need to know that unwrap_or_else
will pass the inner value of the
Err
, which in this case is the static string "not enough arguments"
that we
added in Listing 12-9, to our closure in the argument err
that appears
between the vertical pipes. The code in the closure can then use the err
value when it runs.
在此清单中,我们使用了尚未详细介绍的方法: unwrap_or_else
,它是由标准库在Result<T, E>
上定义的。使用unwrap_or_else
允许我们定义一些自定义的、非panic!
错误处理。如果Result
是Ok
值,则此方法的行为类似于unwrap
:它返回Ok
正在包装的内部值。但是,如果该值是Err
值,则此方法会调用闭包中的代码,闭包是我们定义并作为参数传递给unwrap_or_else
的匿名函数。我们将在第 13 章中更详细地介绍闭包。现在,您只需要知道unwrap_or_else
会将Err
的内部值(在本例中是我们在清单 12-9 中添加的静态字符串"not enough arguments"
传递到出现的参数err
中的闭包垂直管道之间。然后,闭包中的代码可以在运行时使用err
值。
We’ve added a new use
line to bring process
from the standard library into
scope. The code in the closure that will be run in the error case is only two
lines: we print the err
value and then call process::exit
. The
process::exit
function will stop the program immediately and return the
number that was passed as the exit status code. This is similar to the
panic!
-based handling we used in Listing 12-8, but we no longer get all the
extra output. Let’s try it:
我们添加了一个新的use
行,将标准库中的process
引入范围。在错误情况下运行的闭包中的代码只有两行:我们打印err
值,然后调用process::exit
。 process::exit
函数将立即停止程序并返回作为退出状态代码传递的数字。这和panic!
我们在清单 12-8 中使用了基于 - 的处理,但我们不再获得所有额外的输出。我们来尝试一下:
$ 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
Great! This output is much friendlier for our users.
伟大的!这个输出对我们的用户来说更加友好。
Extracting Logic from main
从main
中提取逻辑
Now that we’ve finished refactoring the configuration parsing, let’s turn to
the program’s logic. As we stated in “Separation of Concerns for Binary
Projects”, we’ll
extract a function named run
that will hold all the logic currently in the
main
function that isn’t involved with setting up configuration or handling
errors. When we’re done, main
will be concise and easy to verify by
inspection, and we’ll be able to write tests for all the other logic.
现在我们已经完成了配置解析的重构,让我们转向程序的逻辑。正如我们在“二进制项目的关注点分离”中所述,我们将提取一个名为run
的函数,该函数将保存main
函数中当前不涉及设置配置或处理错误的所有逻辑。当我们完成后, main
将变得简洁并且易于通过检查进行验证,并且我们将能够为所有其他逻辑编写测试。
Listing 12-11 shows the extracted run
function. For now, we’re just making
the small, incremental improvement of extracting the function. We’re still
defining the function in src/main.rs.
清单 12-11 显示了提取的run
函数。目前,我们只是对提取函数进行微小的渐进式改进。我们仍在src/main.rs中定义该函数。
Filename: src/main.rs 文件名:src/main.rs
The run
function now contains all the remaining logic from main
, starting
from reading the file. The run
function takes the Config
instance as an
argument.run
函数现在包含main
中从读取文件开始的所有剩余逻辑。 run
函数将Config
实例作为参数。
Returning Errors from the run
Function
从run
函数返回错误
With the remaining program logic separated into the run
function, we can
improve the error handling, as we did with Config::build
in Listing 12-9.
Instead of allowing the program to panic by calling expect
, the run
function will return a Result<T, E>
when something goes wrong. This will let
us further consolidate the logic around handling errors into main
in a
user-friendly way. Listing 12-12 shows the changes we need to make to the
signature and body of run
.
将剩余的程序逻辑分离到run
函数中,我们可以改进错误处理,就像清单 12-9 中的Config::build
所做的那样。当出现问题时, run
函数将返回Result<T, E>
而不是通过调用expect
来让程序发生恐慌。这将使我们以用户友好的方式进一步将处理错误的逻辑整合到main
中。清单 12-12 显示了我们需要对run
的签名和主体进行的更改。
Filename: src/main.rs 文件名:src/main.rs
We’ve made three significant changes here. First, we changed the return type of
the run
function to Result<(), Box<dyn Error>>
. This function previously
returned the unit type, ()
, and we keep that as the value returned in the
Ok
case.
我们在这里做了三项重大改变。首先,我们将run
函数的返回类型更改为Result<(), Box<dyn Error>>
。该函数之前返回了单位类型()
,我们将其保留为Ok
情况下返回的值。
For the error type, we used the trait object Box<dyn Error>
(and we’ve
brought std::error::Error
into scope with a use
statement at the top).
We’ll cover trait objects in Chapter 17. For now, just
know that Box<dyn Error>
means the function will return a type that
implements the Error
trait, but we don’t have to specify what particular type
the return value will be. This gives us flexibility to return error values that
may be of different types in different error cases. The dyn
keyword is short
for “dynamic.”
对于错误类型,我们使用了特征对象Box<dyn Error>
(并且我们通过顶部的use
语句将std::error::Error
引入了作用域)。我们将在第17章中介绍特征对象ignore。现在,只需知道Box<dyn Error>
意味着该函数将返回实现Error
特征的类型,但我们不必指定返回值的特定类型。这使我们能够灵活地返回在不同错误情况下可能具有不同类型的错误值。 dyn
关键字是“dynamic”的缩写。
Second, we’ve removed the call to expect
in favor of the ?
operator, as we
talked about in Chapter 9. Rather than
panic!
on an error, ?
will return the error value from the current function
for the caller to handle.
其次,我们删除了对expect
的调用,转而使用?
运算符,正如我们在第 9 章中讨论的ignore 。而不是panic!
出现错误时, ?
将从当前函数返回错误值供调用者处理。
Third, the run
function now returns an Ok
value in the success case.
We’ve declared the run
function’s success type as ()
in the signature,
which means we need to wrap the unit type value in the Ok
value. This
Ok(())
syntax might look a bit strange at first, but using ()
like this is
the idiomatic way to indicate that we’re calling run
for its side effects
only; it doesn’t return a value we need.
第三, run
函数现在在成功情况下返回Ok
值。我们在签名中将run
函数的成功类型声明为()
,这意味着我们需要将单位类型值包装在Ok
值中。这个Ok(())
语法乍一看可能有点奇怪,但像这样使用()
是惯用的方式,表明我们只是为了它的副作用而调用run
;它没有返回我们需要的值。
When you run this code, it will compile but will display a warning:
当您运行此代码时,它将编译但会显示警告:
$ cargo run -- the poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
warning: unused `Result` that must be used
--> 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!
Rust tells us that our code ignored the Result
value and the Result
value
might indicate that an error occurred. But we’re not checking to see whether or
not there was an error, and the compiler reminds us that we probably meant to
have some error-handling code here! Let’s rectify that problem now.
Rust 告诉我们,我们的代码忽略了Result
值,而Result
值可能表明发生了错误。但我们并没有检查是否存在错误,并且编译器提醒我们,我们可能想在这里有一些错误处理代码!现在让我们纠正这个问题。
Handling Errors Returned from run
in main
处理main
中run
返回的错误
We’ll check for errors and handle them using a technique similar to one we used
with Config::build
in Listing 12-10, but with a slight difference:
我们将检查错误并使用类似于清单 12-10 中Config::build
使用的技术来处理错误,但略有不同:
Filename: src/main.rs 文件名:src/main.rs
We use if let
rather than unwrap_or_else
to check whether run
returns an
Err
value and call process::exit(1)
if it does. The run
function doesn’t
return a value that we want to unwrap
in the same way that Config::build
returns the Config
instance. Because run
returns ()
in the success case,
we only care about detecting an error, so we don’t need unwrap_or_else
to
return the unwrapped value, which would only be ()
.
我们使用if let
而不是unwrap_or_else
来检查run
是否返回Err
值,如果返回则调用process::exit(1)
。 run
函数不会返回我们想要以Config::build
返回Config
实例的方式unwrap
的值。因为run
在成功的情况下返回()
,所以我们只关心检测错误,所以我们不需要unwrap_or_else
来返回展开的值,它只会是()
。
The bodies of the if let
and the unwrap_or_else
functions are the same in
both cases: we print the error and exit.if let
和unwrap_or_else
函数的主体在这两种情况下是相同的:我们打印错误并退出。
Splitting Code into a Library Crate
将代码拆分到 Library Crate 中
Our minigrep
project is looking good so far! Now we’ll split the
src/main.rs file and put some code into the src/lib.rs file. That way we
can test the code and have a src/main.rs file with fewer responsibilities.
到目前为止,我们的minigrep
项目看起来不错!现在我们将拆分src/main.rs文件并将一些代码放入src/lib.rs文件中。这样我们就可以测试代码并拥有一个责任更少的src/main.rs文件。
Let’s move all the code that isn’t the main
function from src/main.rs to
src/lib.rs:
让我们将所有不是main
函数的代码从src/main.rs移动到src/lib.rs :
- The
run
function definitionrun
函数定义 - The relevant
use
statements
相关use
说明 - The definition of
Config
Config
的定义 - The
Config::build
function definitionConfig::build
函数定义
The contents of src/lib.rs should have the signatures shown in Listing 12-13
(we’ve omitted the bodies of the functions for brevity). Note that this won’t
compile until we modify src/main.rs in Listing 12-14.
src/lib.rs的内容应该具有清单 12-13 中所示的签名(为简洁起见,我们省略了函数体)。请注意,在我们修改清单 12-14 中的src/main.rs之前,它不会编译。
Filename: src/lib.rs 文件名:src/lib.rs
We’ve made liberal use of the pub
keyword: on Config
, on its fields and its
build
method, and on the run
function. We now have a library crate that has
a public API we can test!
我们自由地使用了pub
关键字:在Config
、其字段及其build
方法以及run
函数上。我们现在有了一个库箱,其中有一个可以测试的公共 API!
Now we need to bring the code we moved to src/lib.rs into the scope of the
binary crate in src/main.rs, as shown in Listing 12-14.
现在我们需要将移动到src/lib.rs的代码放入src/main.rs中的二进制 crate 的范围内,如清单 12-14 所示。
Filename: src/main.rs 文件名:src/main.rs
We add a use minigrep::Config
line to bring the Config
type from the
library crate into the binary crate’s scope, and we prefix the run
function
with our crate name. Now all the functionality should be connected and should
work. Run the program with cargo run
and make sure everything works
correctly.
我们添加了一个use minigrep::Config
行,将Config
类型从库 crate 引入到二进制 crate 的范围中,并在run
函数中添加我们的 crate 名称作为前缀。现在所有功能都应该已连接并且应该可以工作。使用cargo run
运行程序并确保一切正常。
Whew! That was a lot of work, but we’ve set ourselves up for success in the
future. Now it’s much easier to handle errors, and we’ve made the code more
modular. Almost all of our work will be done in src/lib.rs from here on out.
哇!这是一项艰巨的工作,但我们已经为未来的成功做好了准备。现在处理错误变得更加容易,并且我们使代码更加模块化。从现在开始,我们几乎所有的工作都将在src/lib.rs中完成。
Let’s take advantage of this newfound modularity by doing something that would
have been difficult with the old code but is easy with the new code: we’ll
write some tests!
让我们利用这种新发现的模块化,做一些对于旧代码来说很困难但对于新代码来说很容易的事情:我们将编写一些测试!
Developing the Library’s Functionality with Test-Driven Development
通过测试驱动开发来开发库的功能
Now that we’ve extracted the logic into src/lib.rs and left the argument
collecting and error handling in src/main.rs, it’s much easier to write tests
for the core functionality of our code. We can call functions directly with
various arguments and check return values without having to call our binary
from the command line.
现在我们已经将逻辑提取到src/lib.rs并将参数收集和错误处理留在src/main.rs中,为代码的核心功能编写测试变得容易得多。我们可以使用各种参数直接调用函数并检查返回值,而无需从命令行调用二进制文件。
In this section, we’ll add the searching logic to the minigrep
program
using the test-driven development (TDD) process with the following steps:
在本节中,我们将使用测试驱动开发 (TDD) 流程将搜索逻辑添加到minigrep
程序中,步骤如下:
- Write a test that fails and run it to make sure it fails for the reason you
expect.
编写一个失败的测试并运行它以确保它因您期望的原因而失败。 - Write or modify just enough code to make the new test pass.
编写或修改足够的代码以使新测试通过。 - Refactor the code you just added or changed and make sure the tests
continue to pass.
重构您刚刚添加或更改的代码并确保测试继续通过。 - Repeat from step 1! 从步骤 1 开始重复!
Though it’s just one of many ways to write software, TDD can help drive code
design. Writing the test before you write the code that makes the test pass
helps to maintain high test coverage throughout the process.
尽管 TDD 只是编写软件的众多方法之一,但它可以帮助推动代码设计。在编写使测试通过的代码之前编写测试有助于在整个过程中保持较高的测试覆盖率。
We’ll test drive the implementation of the functionality that will actually do
the searching for the query string in the file contents and produce a list of
lines that match the query. We’ll add this functionality in a function called
search
.
我们将测试驱动功能的实现,该功能将实际在文件内容中搜索查询字符串并生成与查询匹配的行列表。我们将在名为search
的函数中添加此功能。
Writing a Failing Test 编写失败的测试
Because we don’t need them anymore, let’s remove the println!
statements from
src/lib.rs and src/main.rs that we used to check the program’s behavior.
Then, in src/lib.rs, add a tests
module with a test function, as we did in
Chapter 11. The test function specifies the
behavior we want the search
function to have: it will take a query and the
text to search, and it will return only the lines from the text that contain
the query. Listing 12-15 shows this test, which won’t compile yet.
因为我们不再需要它们,所以让我们删除println!
我们用来检查程序行为的src/lib.rs和src/main.rs中的语句。然后,在src/lib.rs中,添加一个带有测试函数的tests
模块,就像我们在第 11 章中所做的一样。测试函数指定我们希望search
函数具有的行为:它将接受查询和要搜索的文本,并且仅返回文本中包含查询的行。清单 12-15 显示了这个测试,它还无法编译。
Filename: src/lib.rs 文件名:src/lib.rs
This test searches for the string "duct"
. The text we’re searching is three
lines, only one of which contains "duct"
(Note that the backslash after the
opening double quote tells Rust not to put a newline character at the beginning
of the contents of this string literal). We assert that the value returned from
the search
function contains only the line we expect.
此测试搜索字符串"duct"
。我们正在搜索的文本有三行,其中只有一行包含"duct"
(请注意,左双引号后面的反斜杠告诉 Rust 不要在此字符串文字内容的开头放置换行符)。我们断言search
函数返回的值仅包含我们期望的行。
We aren’t yet able to run this test and watch it fail because the test doesn’t
even compile: the search
function doesn’t exist yet! In accordance with TDD
principles, we’ll add just enough code to get the test to compile and run by
adding a definition of the search
function that always returns an empty
vector, as shown in Listing 12-16. Then the test should compile and fail
because an empty vector doesn’t match a vector containing the line "safe, fast, productive."
我们还无法运行此测试并观察它失败,因为测试甚至无法编译: search
功能还不存在!根据 TDD 原则,我们将通过添加始终返回空向量的search
函数的定义来添加足够的代码来编译和运行测试,如清单 12-16 所示。然后测试应该编译并失败,因为空向量与包含"safe, fast, productive."
Filename: src/lib.rs 文件名:src/lib.rs
Notice that we need to define an explicit lifetime 'a
in the signature of
search
and use that lifetime with the contents
argument and the return
value. Recall in Chapter 10 that the lifetime
parameters specify which argument lifetime is connected to the lifetime of the
return value. In this case, we indicate that the returned vector should contain
string slices that reference slices of the argument contents
(rather than the
argument query
).
请注意,我们需要在search
的签名中定义显式生命周期'a
,并将该生命周期与contents
参数和返回值一起使用。回想一下第 10 章中忽略的生命周期参数指定哪个参数生命周期与返回值的生命周期相关。在这种情况下,我们指示返回的向量应包含引用参数contents
切片(而不是参数query
)的字符串切片。
In other words, we tell Rust that the data returned by the search
function
will live as long as the data passed into the search
function in the
contents
argument. This is important! The data referenced by a slice needs
to be valid for the reference to be valid; if the compiler assumes we’re making
string slices of query
rather than contents
, it will do its safety checking
incorrectly.
换句话说,我们告诉 Rust, search
函数返回的数据将随着contents
参数中传递到search
函数的数据而存在。这很重要!切片引用的数据需要有效,引用才有效;如果编译器假设我们正在制作query
的字符串切片而不是contents
,它将错误地进行安全检查。
If we forget the lifetime annotations and try to compile this function, we’ll
get this error:
如果我们忘记了生命周期注释并尝试编译此函数,我们将收到此错误:
$ cargo build
Compiling minigrep v0.1.0 (file:///projects/minigrep)
error[E0106]: missing lifetime specifier
--> src/lib.rs:28:51
|
28 | pub fn search(query: &str, contents: &str) -> Vec<&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 `query` or `contents`
help: consider introducing a named lifetime parameter
|
28 | pub fn search<'a>(query: &'a str, contents: &'a str) -> Vec<&'a str> {
| ++++ ++ ++ ++
For more information about this error, try `rustc --explain E0106`.
error: could not compile `minigrep` (lib) due to 1 previous error
Rust can’t possibly know which of the two arguments we need, so we need to tell
it explicitly. Because contents
is the argument that contains all of our text
and we want to return the parts of that text that match, we know contents
is
the argument that should be connected to the return value using the lifetime
syntax.
Rust 不可能知道我们需要两个参数中的哪一个,所以我们需要明确地告诉它。因为contents
是包含所有文本的参数,并且我们希望返回该文本中匹配的部分,所以我们知道contents
是应该使用生命周期语法连接到返回值的参数。
Other programming languages don’t require you to connect arguments to return
values in the signature, but this practice will get easier over time. You might
want to compare this example with the “Validating References with
Lifetimes” section in
Chapter 10.
其他编程语言不要求您将参数连接到签名中的返回值,但随着时间的推移,这种做法会变得更容易。您可能想将此示例与第 10 章中的“使用生命周期验证引用”忽略部分进行比较。
Now let’s run the test:
现在让我们运行测试:
$ 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`
Great, the test fails, exactly as we expected. Let’s get the test to pass!
太好了,测试失败了,正如我们所料。让我们通过测试吧!
Writing Code to Pass the Test
编写代码以通过测试
Currently, our test is failing because we always return an empty vector. To fix
that and implement search
, our program needs to follow these steps:
目前,我们的测试失败了,因为我们总是返回一个空向量。为了解决这个问题并实现search
,我们的程序需要遵循以下步骤:
- Iterate through each line of the contents.
迭代每一行内容。 - Check whether the line contains our query string.
检查该行是否包含我们的查询字符串。 - If it does, add it to the list of values we’re returning.
如果是,请将其添加到我们返回的值列表中。 - If it doesn’t, do nothing.
如果没有,则什么都不做。 - Return the list of results that match.
返回匹配的结果列表。
Let’s work through each step, starting with iterating through lines.
让我们从迭代行开始,完成每个步骤。
Iterating Through Lines with the lines
Method
使用lines
方法迭代行
Rust has a helpful method to handle line-by-line iteration of strings,
conveniently named lines
, that works as shown in Listing 12-17. Note this
won’t compile yet.
Rust 有一个有用的方法来处理字符串的逐行迭代,方便地命名为lines
,其工作原理如清单12-17所示。请注意,这还无法编译。
Filename: src/lib.rs 文件名:src/lib.rs
The lines
method returns an iterator. We’ll talk about iterators in depth in
Chapter 13, but recall that you saw this way
of using an iterator in Listing 3-5, where we used a
for
loop with an iterator to run some code on each item in a collection.lines
方法返回一个迭代器。我们将在第 13 章中深入讨论迭代器ignore,但回想一下,您在清单 3-5ignore中看到了这种使用迭代器的方式,其中我们使用带有迭代器的for
循环来对集合中的每个项目运行一些代码。
Searching Each Line for the Query
搜索每一行的查询
Next, we’ll check whether the current line contains our query string.
Fortunately, strings have a helpful method named contains
that does this for
us! Add a call to the contains
method in the search
function, as shown in
Listing 12-18. Note this still won’t compile yet.
接下来,我们将检查当前行是否包含我们的查询字符串。幸运的是,字符串有一个名为contains
有用方法可以为我们做到这一点!在search
函数中添加对contains
方法的调用,如清单 12-18 所示。请注意,这仍然无法编译。
Filename: src/lib.rs 文件名:src/lib.rs
At the moment, we’re building up functionality. To get it to compile, we need
to return a value from the body as we indicated we would in the function
signature.
目前,我们正在构建功能。为了让它编译,我们需要从函数体中返回一个值,就像我们在函数签名中指出的那样。
Storing Matching Lines 存储匹配线
To finish this function, we need a way to store the matching lines that we want
to return. For that, we can make a mutable vector before the for
loop and
call the push
method to store a line
in the vector. After the for
loop,
we return the vector, as shown in Listing 12-19.
为了完成这个功能,我们需要一种方法来存储我们想要返回的匹配行。为此,我们可以在for
循环之前创建一个可变向量,并调用push
方法在向量中存储line
。在for
循环之后,我们返回向量,如清单 12-19 所示。
Filename: src/lib.rs 文件名:src/lib.rs
Now the search
function should return only the lines that contain query
,
and our test should pass. Let’s run the test:
现在search
函数应该只返回包含query
行,并且我们的测试应该通过。让我们运行测试:
$ 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
Our test passed, so we know it works!
我们的测试通过了,所以我们知道它有效!
At this point, we could consider opportunities for refactoring the
implementation of the search function while keeping the tests passing to
maintain the same functionality. The code in the search function isn’t too bad,
but it doesn’t take advantage of some useful features of iterators. We’ll
return to this example in Chapter 13, where
we’ll explore iterators in detail, and look at how to improve it.
此时,我们可以考虑重构搜索功能的实现,同时保持测试通过以保持相同的功能。搜索函数中的代码还不错,但它没有利用迭代器的一些有用功能。我们将在第 13 章中返回这个例子,我们将详细探讨迭代器,并研究如何改进它。
Using the search
Function in the run
Function
在run
函数中使用search
函数
Now that the search
function is working and tested, we need to call search
from our run
function. We need to pass the config.query
value and the
contents
that run
reads from the file to the search
function. Then run
will print each line returned from search
:
现在search
函数已经运行并经过测试,我们需要从run
函数中调用search
。我们需要将从文件中run
config.query
值和contents
传递给search
函数。然后run
将打印从search
返回的每一行:
Filename: src/lib.rs 文件名:src/lib.rs
We’re still using a for
loop to return each line from search
and print it.
我们仍然使用for
循环从search
中返回每一行并打印它。
Now the entire program should work! Let’s try it out, first with a word that
should return exactly one line from the Emily Dickinson poem, “frog”:
现在整个程序应该可以运行了!让我们尝试一下,首先使用一个应该恰好返回艾米莉·狄金森诗“青蛙”中的一行的单词:
$ 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
Cool! Now let’s try a word that will match multiple lines, like “body”:
凉爽的!现在让我们尝试一个匹配多行的单词,例如“body”:
$ 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!
And finally, let’s make sure that we don’t get any lines when we search for a
word that isn’t anywhere in the poem, such as “monomorphization”:
最后,让我们确保当我们搜索诗中任何地方都没有的单词时,我们不会得到任何行,例如“单态化”:
$ 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`
Excellent! We’ve built our own mini version of a classic tool and learned a lot
about how to structure applications. We’ve also learned a bit about file input
and output, lifetimes, testing, and command line parsing.
出色的!我们已经构建了自己的迷你版经典工具,并了解了很多有关如何构建应用程序的知识。我们还了解了一些有关文件输入和输出、生命周期、测试和命令行解析的知识。
To round out this project, we’ll briefly demonstrate how to work with
environment variables and how to print to standard error, both of which are
useful when you’re writing command line programs.
为了完善这个项目,我们将简要演示如何使用环境变量以及如何打印到标准错误,这两者在编写命令行程序时都很有用。
Working with Environment Variables
使用环境变量
We’ll improve minigrep
by adding an extra feature: an option for
case-insensitive searching that the user can turn on via an environment
variable. We could make this feature a command line option and require that
users enter it each time they want it to apply, but by instead making it an
environment variable, we allow our users to set the environment variable once
and have all their searches be case insensitive in that terminal session.
我们将通过添加一个额外的功能来改进minigrep
:用户可以通过环境变量打开的不区分大小写搜索的选项。我们可以将此功能设置为命令行选项,并要求用户每次希望应用时输入它,但通过将其设置为环境变量,我们允许用户设置环境变量一次,并使所有搜索不区分大小写在那个终端会话中。
Writing a Failing Test for the Case-Insensitive search
Function
为不区分大小写的search
函数编写失败测试
We first add a new search_case_insensitive
function that will be called when
the environment variable has a value. We’ll continue to follow the TDD process,
so the first step is again to write a failing test. We’ll add a new test for
the new search_case_insensitive
function and rename our old test from
one_result
to case_sensitive
to clarify the differences between the two
tests, as shown in Listing 12-20.
我们首先添加一个新的search_case_insensitive
函数,当环境变量有值时将调用该函数。我们将继续遵循 TDD 流程,因此第一步再次是编写失败的测试。我们将为新的search_case_insensitive
函数添加一个新测试,并将旧测试从one_result
重命名为case_sensitive
,以阐明两个测试之间的差异,如清单 12-20 所示。
Filename: src/lib.rs 文件名:src/lib.rs
Note that we’ve edited the old test’s contents
too. We’ve added a new line
with the text "Duct tape."
using a capital D that shouldn’t match the query
"duct"
when we’re searching in a case-sensitive manner. Changing the old test
in this way helps ensure that we don’t accidentally break the case-sensitive
search functionality that we’ve already implemented. This test should pass now
and should continue to pass as we work on the case-insensitive search.
请注意,我们也编辑了旧测试的contents
。我们添加了一个新行,其中包含文本"Duct tape."
当我们以区分大小写的方式进行搜索时,使用大写 D 不应与查询"duct"
匹配。以这种方式更改旧测试有助于确保我们不会意外破坏我们已经实现的区分大小写的搜索功能。该测试现在应该通过,并且在我们进行不区分大小写的搜索时应该继续通过。
The new test for the case-insensitive search uses "rUsT"
as its query. In
the search_case_insensitive
function we’re about to add, the query "rUsT"
should match the line containing "Rust:"
with a capital R and match the line
"Trust me."
even though both have different casing from the query. This is
our failing test, and it will fail to compile because we haven’t yet defined
the search_case_insensitive
function. Feel free to add a skeleton
implementation that always returns an empty vector, similar to the way we did
for the search
function in Listing 12-16 to see the test compile and fail.
不区分大小写搜索的新测试使用"rUsT"
作为其查询。在我们要添加的search_case_insensitive
函数中,查询"rUsT"
应该与包含大写 R 的"Rust:"
的行匹配,并与"Trust me."
即使两者的查询大小写不同。这是我们失败的测试,它将无法编译,因为我们还没有定义search_case_insensitive
函数。请随意添加一个始终返回空向量的框架实现,类似于我们对清单 12-16 中的search
函数所做的方式,以查看测试编译和失败。
Implementing the search_case_insensitive
Function
实现search_case_insensitive
函数
The search_case_insensitive
function, shown in Listing 12-21, will be almost
the same as the search
function. The only difference is that we’ll lowercase
the query
and each line
so whatever the case of the input arguments,
they’ll be the same case when we check whether the line contains the query.search_case_insensitive
函数(如清单 12-21 所示)几乎与search
函数相同。唯一的区别是,我们将小写query
和每line
,因此无论输入参数的大小写如何,当我们检查该行是否包含查询时,它们的大小写都是相同的。
Filename: src/lib.rs 文件名:src/lib.rs
First, we lowercase the query
string and store it in a shadowed variable with
the same name. Calling to_lowercase
on the query is necessary so no
matter whether the user’s query is "rust"
, "RUST"
, "Rust"
, or "rUsT"
,
we’ll treat the query as if it were "rust"
and be insensitive to the case.
While to_lowercase
will handle basic Unicode, it won’t be 100% accurate. If
we were writing a real application, we’d want to do a bit more work here, but
this section is about environment variables, not Unicode, so we’ll leave it at
that here.
首先,我们将query
字符串小写并将其存储在同名的隐藏变量中。在查询上调用to_lowercase
是必要的,因此无论用户的查询是"rust"
、 "RUST"
、 "Rust"
或"rUsT"
,我们都会将查询视为"rust"
并且对案件。虽然to_lowercase
可以处理基本的 Unicode,但它不会 100% 准确。如果我们正在编写一个真正的应用程序,我们需要在这里做更多的工作,但是本节是关于环境变量,而不是 Unicode,所以我们将其保留在这里。
Note that query
is now a String
rather than a string slice, because calling
to_lowercase
creates new data rather than referencing existing data. Say the
query is "rUsT"
, as an example: that string slice doesn’t contain a lowercase
u
or t
for us to use, so we have to allocate a new String
containing
"rust"
. When we pass query
as an argument to the contains
method now, we
need to add an ampersand because the signature of contains
is defined to take
a string slice.
请注意, query
现在是String
而不是字符串切片,因为调用to_lowercase
会创建新数据而不是引用现有数据。假设查询是"rUsT"
,例如:该字符串切片不包含可供我们使用的小写u
或t
,因此我们必须分配一个包含"rust"
的新String
。现在,当我们将query
作为参数传递给contains
方法时,我们需要添加一个 & 符号,因为contains
的签名被定义为采用字符串切片。
Next, we add a call to to_lowercase
on each line
to lowercase all
characters. Now that we’ve converted line
and query
to lowercase, we’ll
find matches no matter what the case of the query is.
接下来,我们在每line
添加对to_lowercase
的调用,以小写所有字符。现在我们已经将line
和query
转换为小写,无论查询的大小写如何,我们都会找到匹配项。
Let’s see if this implementation passes the tests:
让我们看看这个实现是否通过测试:
$ 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
Great! They passed. Now, let’s call the new search_case_insensitive
function
from the run
function. First, we’ll add a configuration option to the
Config
struct to switch between case-sensitive and case-insensitive search.
Adding this field will cause compiler errors because we aren’t initializing
this field anywhere yet:
伟大的!他们通过了。现在,让我们从run
函数中调用新的search_case_insensitive
函数。首先,我们将向Config
结构添加一个配置选项,以在区分大小写和不区分大小写的搜索之间切换。添加此字段将导致编译器错误,因为我们尚未在任何地方初始化此字段:
Filename: src/lib.rs 文件名:src/lib.rs
We added the ignore_case
field that holds a Boolean. Next, we need the run
function to check the ignore_case
field’s value and use that to decide
whether to call the search
function or the search_case_insensitive
function, as shown in Listing 12-22. This still won’t compile yet.
我们添加了包含布尔值的ignore_case
字段。接下来,我们需要run
函数来检查ignore_case
字段的值,并用它来决定是调用search
函数还是search_case_insensitive
函数,如清单12-22所示。这仍然无法编译。
Filename: src/lib.rs 文件名:src/lib.rs
Finally, we need to check for the environment variable. The functions for
working with environment variables are in the env
module in the standard
library, so we bring that module into scope at the top of src/lib.rs. Then
we’ll use the var
function from the env
module to check if any value
has been set for an environment variable named IGNORE_CASE
, as shown in
Listing 12-23.
最后,我们需要检查环境变量。用于处理环境变量的函数位于标准库的env
模块中,因此我们将该模块纳入src/lib.rs顶部的范围内。然后,我们将使用env
模块中的var
函数来检查是否已为名为IGNORE_CASE
的环境变量设置了任何值,如清单 12-23 所示。
Filename: src/lib.rs 文件名:src/lib.rs
Here, we create a new variable ignore_case
. To set its value, we call the
env::var
function and pass it the name of the IGNORE_CASE
environment
variable. The env::var
function returns a Result
that will be the
successful Ok
variant that contains the value of the environment variable if
the environment variable is set to any value. It will return the Err
variant
if the environment variable is not set.
在这里,我们创建一个新变量ignore_case
。要设置其值,我们调用env::var
函数并向其传递IGNORE_CASE
环境变量的名称。如果环境变量设置为任何值,则env::var
函数返回一个Result
,该结果将是成功的Ok
变体,其中包含环境变量的值。如果未设置环境变量,它将返回Err
变体。
We’re using the is_ok
method on the Result
to check whether the environment
variable is set, which means the program should do a case-insensitive search.
If the IGNORE_CASE
environment variable isn’t set to anything, is_ok
will
return false and the program will perform a case-sensitive search. We don’t
care about the value of the environment variable, just whether it’s set or
unset, so we’re checking is_ok
rather than using unwrap
, expect
, or any
of the other methods we’ve seen on Result
.
我们在Result
上使用is_ok
方法来检查是否设置了环境变量,这意味着程序应该执行不区分大小写的搜索。如果IGNORE_CASE
环境变量未设置任何内容, is_ok
将返回 false,并且程序将执行区分大小写的搜索。我们不关心环境变量的值,只关心它是设置还是未设置,因此我们检查is_ok
而不是使用unwrap
、 expect
或我们在Result
上看到的任何其他方法。
We pass the value in the ignore_case
variable to the Config
instance so the
run
function can read that value and decide whether to call
search_case_insensitive
or search
, as we implemented in Listing 12-22.
我们将ignore_case
变量中的值传递给Config
实例,以便run
函数可以读取该值并决定是否调用search_case_insensitive
或search
,如清单12-22中实现的那样。
Let’s give it a try! First, we’ll run our program without the environment
variable set and with the query to
, which should match any line that contains
the word “to” in all lowercase:
让我们尝试一下吧!首先,我们将在不设置环境变量的情况下运行程序,并使用查询to
,该查询应与包含全小写单词“to”的任何行匹配:
$ 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!
Looks like that still works! Now, let’s run the program with IGNORE_CASE
set to 1
but with the same query to
.
看起来这仍然有效!现在,让我们运行该程序,并将IGNORE_CASE
设置为1
,但to
.
$ IGNORE_CASE=1 cargo run -- to poem.txt
If you’re using PowerShell, you will need to set the environment variable and
run the program as separate commands:
如果您使用 PowerShell,则需要设置环境变量并作为单独的命令运行程序:
PS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt
This will make IGNORE_CASE
persist for the remainder of your shell
session. It can be unset with the Remove-Item
cmdlet:
这将使IGNORE_CASE
在 shell 会话的剩余时间内持续存在。可以使用Remove-Item
cmdlet 取消设置:
PS> Remove-Item Env:IGNORE_CASE
We should get lines that contain “to” that might have uppercase letters:
我们应该得到包含“to”且可能包含大写字母的行:
Are you nobody, too?
How dreary to be somebody!
To tell your name the livelong day
To an admiring bog!
Excellent, we also got lines containing “To”! Our minigrep
program can now do
case-insensitive searching controlled by an environment variable. Now you know
how to manage options set using either command line arguments or environment
variables.
太棒了,我们还得到了包含“To”的行!我们的minigrep
程序现在可以执行由环境变量控制的不区分大小写的搜索。现在您知道如何使用命令行参数或环境变量来管理选项集。
Some programs allow arguments and environment variables for the same
configuration. In those cases, the programs decide that one or the other takes
precedence. For another exercise on your own, try controlling case sensitivity
through either a command line argument or an environment variable. Decide
whether the command line argument or the environment variable should take
precedence if the program is run with one set to case sensitive and one set to
ignore case.
有些程序允许相同配置的参数和环境变量。在这些情况下,程序会决定其中一个优先。对于您自己的另一个练习,请尝试通过命令行参数或环境变量控制区分大小写。如果程序以一组区分大小写和一组忽略大小写的方式运行,请确定命令行参数或环境变量是否应优先。
The std::env
module contains many more useful features for dealing with
environment variables: check out its documentation to see what is available.std::env
模块包含许多用于处理环境变量的更有用的功能:查看其文档以了解可用的功能。
Writing Error Messages to Standard Error Instead of Standard Output
将错误消息写入标准错误而不是标准输出
At the moment, we’re writing all of our output to the terminal using the
println!
macro. In most terminals, there are two kinds of output: standard
output (stdout
) for general information and standard error (stderr
) for
error messages. This distinction enables users to choose to direct the
successful output of a program to a file but still print error messages to the
screen.
目前,我们正在使用println!
将所有输出写入终端。宏。在大多数终端中,有两种输出:用于一般信息的标准输出( stdout
) 和用于错误消息的标准错误( stderr
)。这种区别使用户可以选择将程序成功输出到文件,但仍将错误消息打印到屏幕上。
The println!
macro is only capable of printing to standard output, so we
have to use something else to print to standard error.println!
宏只能打印到标准输出,因此我们必须使用其他东西来打印到标准错误。
Checking Where Errors Are Written
检查错误写入位置
First, let’s observe how the content printed by minigrep
is currently being
written to standard output, including any error messages we want to write to
standard error instead. We’ll do that by redirecting the standard output stream
to a file while intentionally causing an error. We won’t redirect the standard
error stream, so any content sent to standard error will continue to display on
the screen.
首先,让我们观察minigrep
打印的内容当前如何写入标准输出,包括我们想要写入标准错误的任何错误消息。我们将通过将标准输出流重定向到文件来实现这一点,同时故意引发错误。我们不会重定向标准错误流,因此发送到标准错误的任何内容将继续显示在屏幕上。
Command line programs are expected to send error messages to the standard error
stream so we can still see error messages on the screen even if we redirect the
standard output stream to a file. Our program is not currently well-behaved:
we’re about to see that it saves the error message output to a file instead!
命令行程序应该将错误消息发送到标准错误流,因此即使我们将标准输出流重定向到文件,我们仍然可以在屏幕上看到错误消息。我们的程序目前表现不佳:我们将看到它将错误消息输出保存到文件中!
To demonstrate this behavior, we’ll run the program with >
and the file path,
output.txt, that we want to redirect the standard output stream to. We won’t
pass any arguments, which should cause an error:
为了演示此行为,我们将使用>
和我们要将标准输出流重定向到的文件路径output.txt运行程序。我们不会传递任何参数,这会导致错误:
$ cargo run > output.txt
The >
syntax tells the shell to write the contents of standard output to
output.txt instead of the screen. We didn’t see the error message we were
expecting printed to the screen, so that means it must have ended up in the
file. This is what output.txt contains:>
语法告诉 shell 将标准输出的内容写入output.txt而不是屏幕。我们没有看到我们期望打印到屏幕上的错误消息,因此这意味着它一定已经出现在文件中。这是output.txt包含的内容:
Problem parsing arguments: not enough arguments
Yup, our error message is being printed to standard output. It’s much more
useful for error messages like this to be printed to standard error so only
data from a successful run ends up in the file. We’ll change that.
是的,我们的错误消息正在打印到标准输出。将这样的错误消息打印到标准错误会更有用,因此只有成功运行的数据才会出现在文件中。我们会改变这一点。
Printing Errors to Standard Error
将错误打印为标准错误
We’ll use the code in Listing 12-24 to change how error messages are printed.
Because of the refactoring we did earlier in this chapter, all the code that
prints error messages is in one function, main
. The standard library provides
the eprintln!
macro that prints to the standard error stream, so let’s change
the two places we were calling println!
to print errors to use eprintln!
instead.
我们将使用清单 12-24 中的代码来更改错误消息的打印方式。由于我们在本章前面所做的重构,所有打印错误消息的代码都在一个函数main
中。标准库提供了eprintln!
打印到标准错误流的宏,所以让我们更改调用println!
打印错误使用eprintln!
反而。
Filename: src/main.rs 文件名:src/main.rs
Let’s now run the program again in the same way, without any arguments and
redirecting standard output with >
:
现在让我们以相同的方式再次运行该程序,不带任何参数并使用>
重定向标准输出:
$ cargo run > output.txt
Problem parsing arguments: not enough arguments
Now we see the error onscreen and output.txt contains nothing, which is the
behavior we expect of command line programs.
现在我们在屏幕上看到错误,并且output.txt不包含任何内容,这是我们期望命令行程序的行为。
Let’s run the program again with arguments that don’t cause an error but still
redirect standard output to a file, like so:
让我们使用不会导致错误但仍将标准输出重定向到文件的参数再次运行该程序,如下所示:
$ cargo run -- to poem.txt > output.txt
We won’t see any output to the terminal, and output.txt will contain our
results:
我们不会在终端看到任何输出, output.txt将包含我们的结果:
Filename: output.txt 文件名:输出.txt
Are you nobody, too?
How dreary to be somebody!
This demonstrates that we’re now using standard output for successful output
and standard error for error output as appropriate.
这表明我们现在使用标准输出来成功输出,并使用标准错误来适当地输出错误。
Summary 概括
This chapter recapped some of the major concepts you’ve learned so far and
covered how to perform common I/O operations in Rust. By using command line
arguments, files, environment variables, and the eprintln!
macro for printing
errors, you’re now prepared to write command line applications. Combined with
the concepts in previous chapters, your code will be well organized, store data
effectively in the appropriate data structures, handle errors nicely, and be
well tested.
本章回顾了您迄今为止学到的一些主要概念,并介绍了如何在 Rust 中执行常见的 I/O 操作。通过使用命令行参数、文件、环境变量和eprintln!
宏用于打印错误,您现在准备编写命令行应用程序。结合前面章节中的概念,您的代码将组织良好,在适当的数据结构中有效存储数据,很好地处理错误,并经过良好的测试。
Next, we’ll explore some Rust features that were influenced by functional
languages: closures and iterators.
接下来,我们将探讨一些受函数式语言影响的 Rust 功能:闭包和迭代器。
Functional Language Features: Iterators and Closures
函数式语言特性:迭代器和闭包
Rust’s design has taken inspiration from many existing languages and
techniques, and one significant influence is functional programming.
Programming in a functional style often includes using functions as values by
passing them in arguments, returning them from other functions, assigning them
to variables for later execution, and so forth.
Rust 的设计从许多现有的语言和技术中汲取了灵感,其中一个重要的影响就是函数式编程。函数式编程通常包括通过将函数作为值传递给参数、从其他函数返回它们、将它们分配给变量以供以后执行等等。
In this chapter, we won’t debate the issue of what functional programming is or
isn’t but will instead discuss some features of Rust that are similar to
features in many languages often referred to as functional.
在本章中,我们不会争论函数式编程是什么或不是什么的问题,而是讨论 Rust 的一些特性,这些特性与许多语言中通常称为函数式的特性相似。
More specifically, we’ll cover:
更具体地说,我们将介绍:
- Closures, a function-like construct you can store in a variable
闭包,一种可以存储在变量中的类似函数的构造 - Iterators, a way of processing a series of elements
迭代器,一种处理一系列元素的方法 - How to use closures and iterators to improve the I/O project in Chapter 12
第12章如何使用闭包和迭代器改进I/O项目 - The performance of closures and iterators (Spoiler alert: they’re faster than
you might think!)
闭包和迭代器的性能(剧透警告:它们比你想象的要快!)
We’ve already covered some other Rust features, such as pattern matching and
enums, that are also influenced by the functional style. Because mastering
closures and iterators is an important part of writing idiomatic, fast Rust
code, we’ll devote this entire chapter to them.
我们已经介绍了一些其他 Rust 功能,例如模式匹配和枚举,它们也受到函数式风格的影响。因为掌握闭包和迭代器是编写惯用的、快速的 Rust 代码的重要组成部分,所以我们将用整章来讨论它们。
Closures: Anonymous Functions that Capture Their Environment
闭包:捕获环境的匿名函数
Rust’s closures are anonymous functions you can save in a variable or pass as
arguments to other functions. You can create the closure in one place and then
call the closure elsewhere to evaluate it in a different context. Unlike
functions, closures can capture values from the scope in which they’re defined.
We’ll demonstrate how these closure features allow for code reuse and behavior
customization.
Rust 的闭包是匿名函数,您可以将其保存在变量中或作为参数传递给其他函数。您可以在一处创建闭包,然后在其他地方调用该闭包以在不同的上下文中对其进行评估。与函数不同,闭包可以从定义它们的范围中捕获值。我们将演示这些闭包功能如何允许代码重用和行为定制。
Capturing the Environment with Closures
用闭包捕捉环境
We’ll first examine how we can use closures to capture values from the
environment they’re defined in for later use. Here’s the scenario: Every so
often, our t-shirt company gives away an exclusive, limited-edition shirt to
someone on our mailing list as a promotion. People on the mailing list can
optionally add their favorite color to their profile. If the person chosen for
a free shirt has their favorite color set, they get that color shirt. If the
person hasn’t specified a favorite color, they get whatever color the company
currently has the most of.
我们将首先研究如何使用闭包从它们定义的环境中捕获值以供以后使用。场景如下:我们的 T 恤公司经常向我们邮件列表中的某人赠送一件独家限量版衬衫作为促销。邮件列表中的人们可以选择将他们喜欢的颜色添加到他们的个人资料中。如果被选为免费衬衫的人有他们最喜欢的颜色套装,他们就会得到该颜色的衬衫。如果此人没有指定最喜欢的颜色,他们会选择公司目前最常用的颜色。
There are many ways to implement this. For this example, we’re going to use an
enum called ShirtColor
that has the variants Red
and Blue
(limiting the
number of colors available for simplicity). We represent the company’s
inventory with an Inventory
struct that has a field named shirts
that
contains a Vec<ShirtColor>
representing the shirt colors currently in stock.
The method giveaway
defined on Inventory
gets the optional shirt
color preference of the free shirt winner, and returns the shirt color the
person will get. This setup is shown in Listing 13-1:
有很多方法可以实现这一点。对于此示例,我们将使用名为ShirtColor
枚举,它具有Red
和Blue
变体(为简单起见限制可用颜色的数量)。我们用Inventory
结构表示公司的库存,该结构有一个名为shirts
字段,其中包含表示当前库存衬衫颜色的Vec<ShirtColor>
。 Inventory
上定义的giveaway
方法获取免费衬衫获胜者的可选衬衫颜色偏好,并返回该人将获得的衬衫颜色。此设置如清单 13-1 所示:
Filename: src/main.rs 文件名:src/main.rs
#[derive(Debug, PartialEq, Copy, Clone)]
enum ShirtColor {
Red,
Blue,
}
struct Inventory {
shirts: Vec<ShirtColor>,
}
impl Inventory {
fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor {
user_preference.unwrap_or_else(|| self.most_stocked())
}
fn most_stocked(&self) -> ShirtColor {
let mut num_red = 0;
let mut num_blue = 0;
for color in &self.shirts {
match color {
ShirtColor::Red => num_red += 1,
ShirtColor::Blue => num_blue += 1,
}
}
if num_red > 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
);
}
The store
defined in main
has two blue shirts and one red shirt remaining
to distribute for this limited-edition promotion. We call the giveaway
method
for a user with a preference for a red shirt and a user without any preference.main
中定义的store
还有两件蓝色衬衫和一件红色衬衫可供分发用于此限量版促销活动。我们将偏爱红色衬衫的用户和没有任何偏爱的用户称为giveaway
方法。
Again, this code could be implemented in many ways, and here, to focus on
closures, we’ve stuck to concepts you’ve already learned except for the body of
the giveaway
method that uses a closure. In the giveaway
method, we get the
user preference as a parameter of type Option<ShirtColor>
and call the
unwrap_or_else
method on user_preference
. The unwrap_or_else
method on
Option<T>
is defined by the standard library.
It takes one argument: a closure without any arguments that returns a value T
(the same type stored in the Some
variant of the Option<T>
, in this case
ShirtColor
). If the Option<T>
is the Some
variant, unwrap_or_else
returns the value from within the Some
. If the Option<T>
is the None
variant, unwrap_or_else
calls the closure and returns the value returned by
the closure.
同样,这段代码可以通过多种方式实现,在这里,为了关注闭包,我们坚持使用您已经学到的概念,除了使用闭包的giveaway
方法的主体之外。在giveaway
方法中,我们将用户首选项作为Option<ShirtColor>
类型的参数获取,并调用user_preference
上的unwrap_or_else
方法。 Option<T>
忽略的unwrap_or_else
方法由标准库定义。它需要一个参数:一个不带任何参数的闭包,返回值T
(与Option<T>
的Some
变体中存储的类型相同,在本例中ShirtColor
)。如果Option<T>
是Some
变体,则unwrap_or_else
从Some
中返回值。如果Option<T>
是None
变体,则unwrap_or_else
调用闭包并返回闭包返回的值。
We specify the closure expression || self.most_stocked()
as the argument to
unwrap_or_else
. This is a closure that takes no parameters itself (if the
closure had parameters, they would appear between the two vertical bars). The
body of the closure calls self.most_stocked()
. We’re defining the closure
here, and the implementation of unwrap_or_else
will evaluate the closure
later if the result is needed.
我们指定闭包表达式|| self.most_stocked()
作为unwrap_or_else
的参数。这是一个本身不带参数的闭包(如果闭包有参数,它们将出现在两个垂直条之间)。闭包的主体调用self.most_stocked()
。我们在这里定义闭包,如果需要结果, unwrap_or_else
的实现将在稍后评估闭包。
Running this code prints:
运行此代码打印:
$ 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
One interesting aspect here is that we’ve passed a closure that calls
self.most_stocked()
on the current Inventory
instance. The standard library
didn’t need to know anything about the Inventory
or ShirtColor
types we
defined, or the logic we want to use in this scenario. The closure captures an
immutable reference to the self
Inventory
instance and passes it with the
code we specify to the unwrap_or_else
method. Functions, on the other hand,
are not able to capture their environment in this way.
这里一个有趣的方面是,我们传递了一个对当前Inventory
实例调用self.most_stocked()
的闭包。标准库不需要了解有关我们定义的Inventory
或ShirtColor
类型的任何信息,或者我们想要在此场景中使用的逻辑。闭包捕获对self
Inventory
实例的不可变引用,并将其与我们指定的代码一起传递给unwrap_or_else
方法。另一方面,函数无法以这种方式捕获其环境。
Closure Type Inference and Annotation
闭包类型推断和注释
There are more differences between functions and closures. Closures don’t
usually require you to annotate the types of the parameters or the return value
like fn
functions do. Type annotations are required on functions because the
types are part of an explicit interface exposed to your users. Defining this
interface rigidly is important for ensuring that everyone agrees on what types
of values a function uses and returns. Closures, on the other hand, aren’t used
in an exposed interface like this: they’re stored in variables and used without
naming them and exposing them to users of our library.
函数和闭包之间存在更多差异。闭包通常不需要像fn
函数那样注释参数的类型或返回值。函数上需要类型注释,因为类型是向用户公开的显式接口的一部分。严格定义此接口对于确保每个人都同意函数使用和返回的值类型非常重要。另一方面,闭包不会在这样的公开接口中使用:它们存储在变量中并在不命名它们并将它们暴露给我们库的用户的情况下使用。
Closures are typically short and relevant only within a narrow context rather
than in any arbitrary scenario. Within these limited contexts, the compiler can
infer the types of the parameters and the return type, similar to how it’s able
to infer the types of most variables (there are rare cases where the compiler
needs closure type annotations too).
闭包通常很短,并且仅在狭窄的上下文中相关,而不是在任何任意场景中。在这些有限的上下文中,编译器可以推断参数的类型和返回类型,类似于它如何推断大多数变量的类型(在极少数情况下,编译器也需要闭包类型注释)。
As with variables, we can add type annotations if we want to increase
explicitness and clarity at the cost of being more verbose than is strictly
necessary. Annotating the types for a closure would look like the definition
shown in Listing 13-2. In this example, we’re defining a closure and storing it
in a variable rather than defining the closure in the spot we pass it as an
argument as we did in Listing 13-1.
与变量一样,如果我们想提高明确性和清晰度,则可以添加类型注释,但代价是比严格必要的更加冗长。注释闭包的类型类似于清单 13-2 中所示的定义。在这个例子中,我们定义了一个闭包并将其存储在一个变量中,而不是像清单 13-1 中那样在将其作为参数传递的地方定义闭包。
Filename: src/main.rs 文件名:src/main.rs
With type annotations added, the syntax of closures looks more similar to the
syntax of functions. Here we define a function that adds 1 to its parameter and
a closure that has the same behavior, for comparison. We’ve added some spaces
to line up the relevant parts. This illustrates how closure syntax is similar
to function syntax except for the use of pipes and the amount of syntax that is
optional:
添加类型注释后,闭包的语法看起来与函数的语法更加相似。这里我们定义一个参数加 1 的函数和一个具有相同行为的闭包,以进行比较。我们添加了一些空格来排列相关部分。这说明了闭包语法与函数语法的相似之处,除了管道的使用和可选语法的数量之外:
fn add_one_v1 (x: u32) -> u32 { x + 1 }
let add_one_v2 = |x: u32| -> u32 { x + 1 };
let add_one_v3 = |x| { x + 1 };
let add_one_v4 = |x| x + 1 ;
The first line shows a function definition, and the second line shows a fully
annotated closure definition. In the third line, we remove the type annotations
from the closure definition. In the fourth line, we remove the brackets, which
are optional because the closure body has only one expression. These are all
valid definitions that will produce the same behavior when they’re called. The
add_one_v3
and add_one_v4
lines require the closures to be evaluated to be
able to compile because the types will be inferred from their usage. This is
similar to let v = Vec::new();
needing either type annotations or values of
some type to be inserted into the Vec
for Rust to be able to infer the type.
第一行显示函数定义,第二行显示完整注释的闭包定义。在第三行中,我们从闭包定义中删除类型注释。在第四行中,我们删除了括号,这是可选的,因为闭包体只有一个表达式。这些都是有效的定义,在调用它们时会产生相同的行为。 add_one_v3
和add_one_v4
行要求对闭包进行评估才能编译,因为类型将从其用法中推断出来。这类似于let v = Vec::new();
需要将类型注释或某种类型的值插入到Vec
中,以便 Rust 能够推断类型。
For closure definitions, the compiler will infer one concrete type for each of
their parameters and for their return value. For instance, Listing 13-3 shows
the definition of a short closure that just returns the value it receives as a
parameter. This closure isn’t very useful except for the purposes of this
example. Note that we haven’t added any type annotations to the definition.
Because there are no type annotations, we can call the closure with any type,
which we’ve done here with String
the first time. If we then try to call
example_closure
with an integer, we’ll get an error.
对于闭包定义,编译器将为每个参数及其返回值推断出一种具体类型。例如,清单 13-3 显示了一个短闭包的定义,它只返回作为参数接收的值。除了本示例的目的之外,此闭包并不是很有用。请注意,我们没有向定义添加任何类型注释。因为没有类型注释,所以我们可以使用任何类型调用闭包,这是我们第一次使用String
完成的。如果我们随后尝试使用整数调用example_closure
,我们将收到错误。
Filename: src/main.rs 文件名:src/main.rs
The compiler gives us this error:
编译器给我们这个错误:
$ cargo run
Compiling closure-example v0.1.0 (file:///projects/closure-example)
error[E0308]: mismatched types
--> 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`
--> 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
--> 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
The first time we call example_closure
with the String
value, the compiler
infers the type of x
and the return type of the closure to be String
. Those
types are then locked into the closure in example_closure
, and we get a type
error when we next try to use a different type with the same closure.
第一次使用String
值调用example_closure
时,编译器将x
的类型和闭包的返回类型推断为String
。然后这些类型被锁定到example_closure
中的闭包中,当我们下次尝试使用具有相同闭包的不同类型时,我们会收到类型错误。
Capturing References or Moving Ownership
捕获引用或移动所有权
Closures can capture values from their environment in three ways, which
directly map to the three ways a function can take a parameter: borrowing
immutably, borrowing mutably, and taking ownership. The closure will decide
which of these to use based on what the body of the function does with the
captured values.
闭包可以通过三种方式从环境中捕获值,这直接映射到函数可以采用参数的三种方式:不可变借用、可变借用和获取所有权。闭包将根据函数体对捕获的值执行的操作来决定使用其中的哪一个。
In Listing 13-4, we define a closure that captures an immutable reference to
the vector named list
because it only needs an immutable reference to print
the value:
在清单 13-4 中,我们定义了一个闭包,它捕获对名为list
向量的不可变引用,因为它只需要一个不可变引用来打印值:
Filename: src/main.rs 文件名:src/main.rs
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:?}");
}
This example also illustrates that a variable can bind to a closure definition,
and we can later call the closure by using the variable name and parentheses as
if the variable name were a function name.
这个例子还说明了变量可以绑定到闭包定义,以后我们可以使用变量名和括号来调用闭包,就像变量名是函数名一样。
Because we can have multiple immutable references to list
at the same time,
list
is still accessible from the code before the closure definition, after
the closure definition but before the closure is called, and after the closure
is called. This code compiles, runs, and prints:
因为我们可以同时有多个对list
的不可变引用,所以仍然可以从闭包定义之前、闭包定义之后但调用闭包之前以及调用闭包之后的代码访问list
。此代码编译、运行并打印:
$ cargo run
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]
Next, in Listing 13-5, we change the closure body so that it adds an element to
the list
vector. The closure now captures a mutable reference:
接下来,在清单 13-5 中,我们更改了闭包主体,以便它将一个元素添加到list
向量中。闭包现在捕获一个可变引用:
Filename: src/main.rs 文件名:src/main.rs
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:?}");
}
This code compiles, runs, and prints:
此代码编译、运行并打印:
$ cargo run
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]
Note that there’s no longer a println!
between the definition and the call of
the borrows_mutably
closure: when borrows_mutably
is defined, it captures a
mutable reference to list
. We don’t use the closure again after the closure
is called, so the mutable borrow ends. Between the closure definition and the
closure call, an immutable borrow to print isn’t allowed because no other
borrows are allowed when there’s a mutable borrow. Try adding a println!
there to see what error message you get!
请注意,不再有println!
borrows_mutably
闭包的定义和调用之间:当定义borrows_mutably
时,它捕获对list
的可变引用。调用闭包后我们不再使用闭包,因此可变借用结束。在闭包定义和闭包调用之间,不允许进行不可变的借用打印,因为当存在可变借用时不允许其他借用。尝试添加一个println!
在那里查看您收到的错误消息!
If you want to force the closure to take ownership of the values it uses in the
environment even though the body of the closure doesn’t strictly need
ownership, you can use the move
keyword before the parameter list.
如果您想强制闭包取得它在环境中使用的值的所有权,即使闭包主体并不严格需要所有权,您也可以在参数列表之前使用move
关键字。
This technique is mostly useful when passing a closure to a new thread to move
the data so that it’s owned by the new thread. We’ll discuss threads and why
you would want to use them in detail in Chapter 16 when we talk about
concurrency, but for now, let’s briefly explore spawning a new thread using a
closure that needs the move
keyword. Listing 13-6 shows Listing 13-4 modified
to print the vector in a new thread rather than in the main thread:
当将闭包传递给新线程以移动数据以使其归新线程所有时,此技术最有用。我们将在第 16 章讨论并发时详细讨论线程以及为什么要使用它们,但现在,让我们简要探讨一下使用需要move
关键字的闭包生成一个新线程。清单 13-6 显示了修改后的清单 13-4,以在新线程而不是主线程中打印向量:
Filename: src/main.rs 文件名:src/main.rs
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();
}
We spawn a new thread, giving the thread a closure to run as an argument. The
closure body prints out the list. In Listing 13-4, the closure only captured
list
using an immutable reference because that’s the least amount of access
to list
needed to print it. In this example, even though the closure body
still only needs an immutable reference, we need to specify that list
should
be moved into the closure by putting the move
keyword at the beginning of the
closure definition. The new thread might finish before the rest of the main
thread finishes, or the main thread might finish first. If the main thread
maintained ownership of list
but ended before the new thread did and dropped
list
, the immutable reference in the thread would be invalid. Therefore, the
compiler requires that list
be moved into the closure given to the new thread
so the reference will be valid. Try removing the move
keyword or using list
in the main thread after the closure is defined to see what compiler errors you
get!
我们生成一个新线程,为该线程提供一个闭包作为参数运行。闭包主体打印出列表。在清单 13-4 中,闭包仅使用不可变引用捕获list
,因为这是打印list
所需的最少访问量。在此示例中,即使闭包主体仍然只需要一个不可变引用,我们也需要通过将move
关键字放在闭包定义的开头来指定应将list
移动到闭包中。新线程可能会在主线程的其余部分完成之前完成,或者主线程可能会先完成。如果主线程保留了list
的所有权,但在新线程完成并删除list
之前结束,则线程中的不可变引用将无效。因此,编译器要求将list
移动到给新线程的闭包中,以便引用有效。尝试在定义闭包后删除move
关键字或在主线程中使用list
,看看会出现什么编译器错误!
Moving Captured Values Out of Closures and the Fn
Traits
将捕获的值移出闭包和Fn
特征
Once a closure has captured a reference or captured ownership of a value from
the environment where the closure is defined (thus affecting what, if anything,
is moved into the closure), the code in the body of the closure defines what
happens to the references or values when the closure is evaluated later (thus
affecting what, if anything, is moved out of the closure). A closure body can
do any of the following: move a captured value out of the closure, mutate the
captured value, neither move nor mutate the value, or capture nothing from the
environment to begin with.
一旦闭包从定义闭包的环境中捕获了引用或捕获了值的所有权(从而影响了移入闭包中的内容(如果有的话)),闭包主体中的代码定义了引用发生的情况或稍后评估闭包时的值(从而影响从闭包中移出的内容(如果有的话))。闭包主体可以执行以下任意操作:将捕获的值移出闭包、改变捕获的值、既不移动也不改变该值,或者从一开始就从环境中不捕获任何内容。
The way a closure captures and handles values from the environment affects
which traits the closure implements, and traits are how functions and structs
can specify what kinds of closures they can use. Closures will automatically
implement one, two, or all three of these Fn
traits, in an additive fashion,
depending on how the closure’s body handles the values:
闭包捕获和处理来自环境的值的方式会影响闭包实现的特征,而特征是函数和结构如何指定它们可以使用哪种类型的闭包。闭包将以附加方式自动实现这些Fn
特征中的一个、两个或全部三个,具体取决于闭包主体如何处理这些值:
FnOnce
applies to closures that can be called once. All closures implement at least this trait, because all closures can be called. A closure that moves captured values out of its body will only implementFnOnce
and none of the otherFn
traits, because it can only be called once.FnOnce
适用于可以调用一次的闭包。所有闭包都至少实现这个特性,因为所有闭包都可以被调用。将捕获的值移出其主体的闭包将仅实现FnOnce
而不会实现其他Fn
特征,因为它只能被调用一次。FnMut
applies to closures that don’t move captured values out of their body, but that might mutate the captured values. These closures can be called more than once.FnMut
适用于不会将捕获的值移出其主体的闭包,但这可能会改变捕获的值。这些闭包可以被多次调用。Fn
applies to closures that don’t move captured values out of their body and that don’t mutate captured values, as well as closures that capture nothing from their environment. These closures can be called more than once without mutating their environment, which is important in cases such as calling a closure multiple times concurrently.Fn
适用于不会将捕获的值移出其主体且不会改变捕获的值的闭包,以及不从其环境中捕获任何内容的闭包。这些闭包可以被多次调用,而无需改变其环境,这在并发多次调用闭包等情况下非常重要。
Let’s look at the definition of the unwrap_or_else
method on Option<T>
that
we used in Listing 13-1:
让我们看看清单 13-1 中使用的Option<T>
上的unwrap_or_else
方法的定义:
impl<T> Option<T> {
pub fn unwrap_or_else<F>(self, f: F) -> T
where
F: FnOnce() -> T
{
match self {
Some(x) => x,
None => f(),
}
}
}
Recall that T
is the generic type representing the type of the value in the
Some
variant of an Option
. That type T
is also the return type of the
unwrap_or_else
function: code that calls unwrap_or_else
on an
Option<String>
, for example, will get a String
.
回想一下, T
是泛型类型,表示Option
的Some
变体中值的类型。该类型T
也是unwrap_or_else
函数的返回类型:例如,在Option<String>
上调用unwrap_or_else
的代码将获得String
。
Next, notice that the unwrap_or_else
function has the additional generic type
parameter F
. The F
type is the type of the parameter named f
, which is
the closure we provide when calling unwrap_or_else
.
接下来,请注意unwrap_or_else
函数具有附加的泛型类型参数F
。 F
类型是名为f
的参数的类型,它是我们在调用unwrap_or_else
时提供的闭包。
The trait bound specified on the generic type F
is FnOnce() -> T
, which
means F
must be able to be called once, take no arguments, and return a T
.
Using FnOnce
in the trait bound expresses the constraint that
unwrap_or_else
is only going to call f
at most one time. In the body of
unwrap_or_else
, we can see that if the Option
is Some
, f
won’t be
called. If the Option
is None
, f
will be called once. Because all
closures implement FnOnce
, unwrap_or_else
accepts all three kinds of
closures and is as flexible as it can be.
泛型类型F
上指定的特征界限是FnOnce() -> T
,这意味着F
必须能够被调用一次、不带参数并返回T
。在特征边界中使用FnOnce
表达了unwrap_or_else
最多只能调用f
一次的约束。在unwrap_or_else
的主体中,我们可以看到如果Option
是Some
,则不会调用f
。如果Option
为None
, f
将被调用一次。因为所有闭包都实现FnOnce
,所以unwrap_or_else
接受所有三种闭包,并且尽可能灵活。
Note: Functions can implement all three of the Fn
traits too. If what we
want to do doesn’t require capturing a value from the environment, we can use
the name of a function rather than a closure where we need something that
implements one of the Fn
traits. For example, on an Option<Vec<T>>
value,
we could call unwrap_or_else(Vec::new)
to get a new, empty vector if the
value is None
.
注意:函数也可以实现所有三个Fn
特征。如果我们想要做的事情不需要从环境中捕获值,那么我们可以在需要实现Fn
特征之一的东西时使用函数的名称而不是闭包。例如,对于Option<Vec<T>>
值,如果值为None
,我们可以调用unwrap_or_else(Vec::new)
来获取新的空向量。
Now let’s look at the standard library method sort_by_key
defined on slices,
to see how that differs from unwrap_or_else
and why sort_by_key
uses
FnMut
instead of FnOnce
for the trait bound. The closure gets one argument
in the form of a reference to the current item in the slice being considered,
and returns a value of type K
that can be ordered. This function is useful
when you want to sort a slice by a particular attribute of each item. In
Listing 13-7, we have a list of Rectangle
instances and we use sort_by_key
to order them by their width
attribute from low to high:
现在让我们看一下切片上定义的标准库方法sort_by_key
,看看它与unwrap_or_else
有何不同,以及为什么sort_by_key
使用FnMut
而不是FnOnce
作为特征绑定。该闭包以对正在考虑的切片中当前项的引用的形式获取一个参数,并返回一个可排序的K
类型值。当您想要按每个项目的特定属性对切片进行排序时,此函数非常有用。在清单 13-7 中,我们有一个Rectangle
实例列表,我们使用sort_by_key
按width
属性从低到高对它们进行排序:
Filename: src/main.rs 文件名:src/main.rs
#[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:#?}");
}
This code prints: 此代码打印:
$ 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,
},
]
The reason sort_by_key
is defined to take an FnMut
closure is that it calls
the closure multiple times: once for each item in the slice. The closure |r| r.width
doesn’t capture, mutate, or move out anything from its environment, so
it meets the trait bound requirements.sort_by_key
被定义为采用FnMut
闭包的原因是它多次调用闭包:对切片中的每个项目调用一次。闭包|r| r.width
不会捕获、变异或移出其环境中的任何内容,因此它满足特征绑定要求。
In contrast, Listing 13-8 shows an example of a closure that implements just
the FnOnce
trait, because it moves a value out of the environment. The
compiler won’t let us use this closure with sort_by_key
:
相比之下,清单 13-8 显示了一个仅实现FnOnce
特征的闭包示例,因为它将值移出环境。编译器不允许我们将此闭包与sort_by_key
一起使用:
Filename: src/main.rs 文件名:src/main.rs
#[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:#?}");
}
This is a contrived, convoluted way (that doesn’t work) to try and count the
number of times sort_by_key
calls the closure when sorting list
. This code
attempts to do this counting by pushing value
—a String
from the closure’s
environment—into the sort_operations
vector. The closure captures value
then moves value
out of the closure by transferring ownership of value
to
the sort_operations
vector. This closure can be called once; trying to call
it a second time wouldn’t work because value
would no longer be in the
environment to be pushed into sort_operations
again! Therefore, this closure
only implements FnOnce
. When we try to compile this code, we get this error
that value
can’t be moved out of the closure because the closure must
implement FnMut
:
这是一种人为的、复杂的方法(不起作用),用于尝试计算sort_by_key
在排序list
时调用闭包的次数。此代码尝试通过将value
(来自闭包环境的String
)推入sort_operations
向量来执行此计数。闭包捕获value
,然后通过将value
的所有权转移到sort_operations
向量,将value
移出闭包。这个闭包可以被调用一次;尝试第二次调用它是行不通的,因为value
将不再存在于再次被推入sort_operations
的环境中!因此,这个闭包只实现了FnOnce
。当我们尝试编译此代码时,我们收到以下错误: value
无法移出闭包,因为闭包必须实现FnMut
:
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure
--> 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
For more information about this error, try `rustc --explain E0507`.
error: could not compile `rectangles` (bin "rectangles") due to 1 previous error
The error points to the line in the closure body that moves value
out of the
environment. To fix this, we need to change the closure body so that it doesn’t
move values out of the environment. To count the number of times the closure
is called, keeping a counter in the environment and incrementing its value in
the closure body is a more straightforward way to calculate that. The closure
in Listing 13-9 works with sort_by_key
because it is only capturing a mutable
reference to the num_sort_operations
counter and can therefore be called more
than once:
该错误指向闭包主体中将value
移出环境的行。为了解决这个问题,我们需要更改闭包主体,以便它不会将值移出环境。要计算闭包被调用的次数,在环境中保留一个计数器并在闭包主体中增加其值是一种更直接的计算方法。清单 13-9 中的闭包与sort_by_key
一起使用,因为它仅捕获对num_sort_operations
计数器的可变引用,因此可以多次调用:
Filename: src/main.rs 文件名:src/main.rs
#[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");
}
The Fn
traits are important when defining or using functions or types that
make use of closures. In the next section, we’ll discuss iterators. Many
iterator methods take closure arguments, so keep these closure details in mind
as we continue!
在定义或使用使用闭包的函数或类型时, Fn
特征非常重要。在下一节中,我们将讨论迭代器。许多迭代器方法都采用闭包参数,因此在我们继续时请记住这些闭包细节!
Processing a Series of Items with Iterators
使用迭代器处理一系列项目
The iterator pattern allows you to perform some task on a sequence of items in
turn. An iterator is responsible for the logic of iterating over each item and
determining when the sequence has finished. When you use iterators, you don’t
have to reimplement that logic yourself.
迭代器模式允许您依次对一系列项目执行某些任务。迭代器负责迭代每个项目并确定序列何时完成的逻辑。当您使用迭代器时,您不必自己重新实现该逻辑。
In Rust, iterators are lazy, meaning they have no effect until you call
methods that consume the iterator to use it up. For example, the code in
Listing 13-10 creates an iterator over the items in the vector v1
by calling
the iter
method defined on Vec<T>
. This code by itself doesn’t do anything
useful.
在 Rust 中,迭代器是惰性的,这意味着在您调用消耗迭代器的方法将其用完之前,它们不会产生任何效果。例如,清单 13-10 中的代码通过调用Vec<T>
上定义的iter
方法在向量v1
中的项上创建一个迭代器。这段代码本身并没有做任何有用的事情。
The iterator is stored in the v1_iter
variable. Once we’ve created an
iterator, we can use it in a variety of ways. In Listing 3-5 in Chapter 3, we
iterated over an array using a for
loop to execute some code on each of its
items. Under the hood this implicitly created and then consumed an iterator,
but we glossed over how exactly that works until now.
迭代器存储在v1_iter
变量中。创建迭代器后,我们可以通过多种方式使用它。在第 3 章的清单 3-5 中,我们使用for
循环迭代一个数组,以对其每个项目执行一些代码。在幕后,这隐式地创建然后消耗了一个迭代器,但我们到目前为止还掩盖了它到底是如何工作的。
In the example in Listing 13-11, we separate the creation of the iterator from
the use of the iterator in the for
loop. When the for
loop is called using
the iterator in v1_iter
, each element in the iterator is used in one
iteration of the loop, which prints out each value.
在清单 13-11 的示例中,我们将迭代器的创建与for
循环中迭代器的使用分开。当使用v1_iter
中的迭代器调用for
循环时,迭代器中的每个元素都会在循环的一次迭代中使用,从而打印出每个值。
In languages that don’t have iterators provided by their standard libraries,
you would likely write this same functionality by starting a variable at index
0, using that variable to index into the vector to get a value, and
incrementing the variable value in a loop until it reached the total number of
items in the vector.
在标准库没有提供迭代器的语言中,您可能会通过以下方式编写相同的功能:在索引 0 处启动变量,使用该变量索引到向量中以获取值,然后在循环中递增变量值直到达到向量中的项目总数。
Iterators handle all that logic for you, cutting down on repetitive code you
could potentially mess up. Iterators give you more flexibility to use the same
logic with many different kinds of sequences, not just data structures you can
index into, like vectors. Let’s examine how iterators do that.
迭代器为您处理所有逻辑,减少可能会造成混乱的重复代码。迭代器使您能够更灵活地对许多不同类型的序列使用相同的逻辑,而不仅仅是可以索引的数据结构,例如向量。让我们看看迭代器是如何做到这一点的。
The Iterator
Trait and the next
Method
Iterator
特征和next
方法
All iterators implement a trait named Iterator
that is defined in the
standard library. The definition of the trait looks like this:
所有迭代器都实现了标准库中定义的名为Iterator
特征。特征的定义如下所示:
Notice this definition uses some new syntax: type Item
and Self::Item
,
which are defining an associated type with this trait. We’ll talk about
associated types in depth in Chapter 19. For now, all you need to know is that
this code says implementing the Iterator
trait requires that you also define
an Item
type, and this Item
type is used in the return type of the next
method. In other words, the Item
type will be the type returned from the
iterator.
请注意,此定义使用了一些新语法: type Item
和Self::Item
,它们定义了与此特征相关联的类型。我们将在第 19 章中深入讨论关联类型。现在,您需要知道的是这段代码表示实现Iterator
特征要求您还定义一个Item
类型,并且该Item
类型用于返回类型next
方法。换句话说, Item
类型将是从迭代器返回的类型。
The Iterator
trait only requires implementors to define one method: the
next
method, which returns one item of the iterator at a time wrapped in
Some
and, when iteration is over, returns None
.Iterator
特征只需要实现者定义一个方法: next
方法,它一次返回迭代器的一项,包装在Some
中,当迭代结束时,返回None
。
We can call the next
method on iterators directly; Listing 13-12 demonstrates
what values are returned from repeated calls to next
on the iterator created
from the vector.
我们可以直接调用迭代器的next
方法;清单 13-12 演示了从向量创建的迭代器上重复调用next
会返回哪些值。
Filename: src/lib.rs 文件名:src/lib.rs
Note that we needed to make v1_iter
mutable: calling the next
method on an
iterator changes internal state that the iterator uses to keep track of where
it is in the sequence. In other words, this code consumes, or uses up, the
iterator. Each call to next
eats up an item from the iterator. We didn’t need
to make v1_iter
mutable when we used a for
loop because the loop took
ownership of v1_iter
and made it mutable behind the scenes.
请注意,我们需要使v1_iter
可变:在迭代器上调用next
方法会更改迭代器用于跟踪其在序列中位置的内部状态。换句话说,此代码消耗或用完迭代器。每次调用next
都会消耗迭代器中的一个项目。当我们使用for
循环时,我们不需要使v1_iter
可变,因为循环获取了v1_iter
的所有权并使其在幕后可变。
Also note that the values we get from the calls to next
are immutable
references to the values in the vector. The iter
method produces an iterator
over immutable references. If we want to create an iterator that takes
ownership of v1
and returns owned values, we can call into_iter
instead of
iter
. Similarly, if we want to iterate over mutable references, we can call
iter_mut
instead of iter
.
另请注意,我们从调用next
获得的值是对向量中值的不可变引用。 iter
方法在不可变引用上生成一个迭代器。如果我们想创建一个迭代器来获取v1
的所有权并返回拥有的值,我们可以调用into_iter
而不是iter
。类似地,如果我们想迭代可变引用,我们可以调用iter_mut
而不是iter
。
Methods that Consume the Iterator
使用迭代器的方法
The Iterator
trait has a number of different methods with default
implementations provided by the standard library; you can find out about these
methods by looking in the standard library API documentation for the Iterator
trait. Some of these methods call the next
method in their definition, which
is why you’re required to implement the next
method when implementing the
Iterator
trait.Iterator
特征有许多不同的方法,其默认实现由标准库提供;您可以通过查看Iterator
特征的标准库 API 文档来了解这些方法。其中一些方法在其定义中调用next
方法,这就是为什么在实现Iterator
特征时需要实现next
方法。
Methods that call next
are called consuming adaptors, because calling them
uses up the iterator. One example is the sum
method, which takes ownership of
the iterator and iterates through the items by repeatedly calling next
, thus
consuming the iterator. As it iterates through, it adds each item to a running
total and returns the total when iteration is complete. Listing 13-13 has a
test illustrating a use of the sum
method:
调用next
的方法称为消耗适配器,因为调用它们会耗尽迭代器。一个例子是sum
方法,它获取迭代器的所有权,并通过重复调用next
来迭代项目,从而消耗迭代器。在迭代时,它将每个项目添加到运行总计中,并在迭代完成时返回总计。清单 13-13 有一个测试说明了sum
方法的用法:
Filename: src/lib.rs 文件名:src/lib.rs
We aren’t allowed to use v1_iter
after the call to sum
because sum
takes
ownership of the iterator we call it on.
我们不允许在调用sum
之后使用v1_iter
,因为sum
拥有我们调用它的迭代器的所有权。
Methods that Produce Other Iterators
产生其他迭代器的方法
Iterator adaptors are methods defined on the Iterator
trait that don’t
consume the iterator. Instead, they produce different iterators by changing
some aspect of the original iterator.
迭代器适配器是在Iterator
特征上定义的方法,不消耗迭代器。相反,它们通过更改原始迭代器的某些方面来生成不同的迭代器。
Listing 13-14 shows an example of calling the iterator adaptor method map
,
which takes a closure to call on each item as the items are iterated through.
The map
method returns a new iterator that produces the modified items. The
closure here creates a new iterator in which each item from the vector will be
incremented by 1:
清单 13-14 显示了调用迭代器适配器方法map
的示例,该方法使用一个闭包来在迭代项目时调用每个项目。 map
方法返回一个新的迭代器,该迭代器生成修改后的项。这里的闭包创建了一个新的迭代器,其中向量中的每个项目都将增加 1:
Filename: src/main.rs 文件名:src/main.rs
However, this code produces a warning:
但是,此代码会产生警告:
$ cargo run
Compiling iterators v0.1.0 (file:///projects/iterators)
warning: unused `Map` that must be used
--> 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`
The code in Listing 13-14 doesn’t do anything; the closure we’ve specified
never gets called. The warning reminds us why: iterator adaptors are lazy, and
we need to consume the iterator here.
清单 13-14 中的代码不执行任何操作;我们指定的闭包永远不会被调用。该警告提醒我们原因:迭代器适配器是惰性的,我们需要在这里使用迭代器。
To fix this warning and consume the iterator, we’ll use the collect
method,
which we used in Chapter 12 with env::args
in Listing 12-1. This method
consumes the iterator and collects the resulting values into a collection data
type.
为了修复这个警告并使用迭代器,我们将使用collect
方法,我们在第12章中使用了该方法以及清单12-1中的env::args
。此方法使用迭代器并将结果值收集到集合数据类型中。
In Listing 13-15, we collect the results of iterating over the iterator that’s
returned from the call to map
into a vector. This vector will end up
containing each item from the original vector incremented by 1.
在清单 13-15 中,我们收集了对map
到向量的调用返回的迭代器进行迭代的结果。该向量最终将包含原始向量中每一项加 1。
Filename: src/main.rs 文件名:src/main.rs
Because map
takes a closure, we can specify any operation we want to perform
on each item. This is a great example of how closures let you customize some
behavior while reusing the iteration behavior that the Iterator
trait
provides.
因为map
采用闭包,所以我们可以指定要对每个项目执行的任何操作。这是一个很好的例子,说明了闭包如何让您在重用Iterator
Trait 提供的迭代行为的同时自定义某些行为。
You can chain multiple calls to iterator adaptors to perform complex actions in
a readable way. But because all iterators are lazy, you have to call one of the
consuming adaptor methods to get results from calls to iterator adaptors.
您可以链接对迭代器适配器的多个调用,以可读的方式执行复杂的操作。但由于所有迭代器都是惰性的,因此您必须调用使用适配器方法之一才能从迭代器适配器的调用中获取结果。
Using Closures that Capture Their Environment
使用捕获环境的闭包
Many iterator adapters take closures as arguments, and commonly the closures
we’ll specify as arguments to iterator adapters will be closures that capture
their environment.
许多迭代器适配器将闭包作为参数,通常我们指定为迭代器适配器参数的闭包将是捕获其环境的闭包。
For this example, we’ll use the filter
method that takes a closure. The
closure gets an item from the iterator and returns a bool
. If the closure
returns true
, the value will be included in the iteration produced by
filter
. If the closure returns false
, the value won’t be included.
对于这个例子,我们将使用带有闭包的filter
方法。闭包从迭代器获取一个项目并返回一个bool
。如果闭包返回true
,则该值将包含在filter
生成的迭代中。如果闭包返回false
,则不会包含该值。
In Listing 13-16, we use filter
with a closure that captures the shoe_size
variable from its environment to iterate over a collection of Shoe
struct
instances. It will return only shoes that are the specified size.
在清单13-16中,我们使用带有闭包的filter
,从其环境中捕获shoe_size
变量来迭代Shoe
结构实例的集合。它将仅返回指定尺寸的鞋子。
Filename: src/lib.rs 文件名:src/lib.rs
#[derive(PartialEq, Debug)]
struct Shoe {
size: u32,
style: String,
}
fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
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")
},
]
);
}
}
The shoes_in_size
function takes ownership of a vector of shoes and a shoe
size as parameters. It returns a vector containing only shoes of the specified
size.shoes_in_size
函数将鞋子向量的所有权和鞋子尺寸作为参数。它返回一个仅包含指定尺寸鞋子的向量。
In the body of shoes_in_size
, we call into_iter
to create an iterator
that takes ownership of the vector. Then we call filter
to adapt that
iterator into a new iterator that only contains elements for which the closure
returns true
.
在shoes_in_size
的主体中,我们调用into_iter
来创建一个拥有向量所有权的迭代器。然后我们调用filter
将该迭代器调整为一个新的迭代器,该迭代器仅包含闭包返回true
元素。
The closure captures the shoe_size
parameter from the environment and
compares the value with each shoe’s size, keeping only shoes of the size
specified. Finally, calling collect
gathers the values returned by the
adapted iterator into a vector that’s returned by the function.
该闭包从环境中捕获shoe_size
参数,并将该值与每只鞋子的尺寸进行比较,仅保留指定尺寸的鞋子。最后,调用collect
将适应迭代器返回的值收集到函数返回的向量中。
The test shows that when we call shoes_in_size
, we get back only shoes
that have the same size as the value we specified.
测试表明,当我们调用shoes_in_size
时,我们只返回与我们指定的值相同尺寸的鞋子。
Improving Our I/O Project
改进我们的 I/O 项目
With this new knowledge about iterators, we can improve the I/O project in
Chapter 12 by using iterators to make places in the code clearer and more
concise. Let’s look at how iterators can improve our implementation of the
Config::build
function and the search
function.
有了关于迭代器的新知识,我们可以通过使用迭代器来改进第 12 章中的 I/O 项目,使代码中的位置更清晰、更简洁。让我们看看迭代器如何改进Config::build
函数和search
函数的实现。
Removing a clone
Using an Iterator
使用迭代器删除clone
In Listing 12-6, we added code that took a slice of String
values and created
an instance of the Config
struct by indexing into the slice and cloning the
values, allowing the Config
struct to own those values. In Listing 13-17,
we’ve reproduced the implementation of the Config::build
function as it was
in Listing 12-23:
在清单 12-6 中,我们添加了代码,该代码获取String
值的切片,并通过索引该切片并克隆值来创建Config
结构的实例,从而允许Config
结构拥有这些值。在清单 13-17 中,我们重现了Config::build
函数的实现,如清单 12-23 所示:
Filename: src/lib.rs 文件名:src/lib.rs
At the time, we said not to worry about the inefficient clone
calls because
we would remove them in the future. Well, that time is now!
当时,我们说不要担心低效的clone
调用,因为我们将来会删除它们。嗯,就是现在了!
We needed clone
here because we have a slice with String
elements in the
parameter args
, but the build
function doesn’t own args
. To return
ownership of a Config
instance, we had to clone the values from the query
and file_path
fields of Config
so the Config
instance can own its values.
我们在这里需要clone
,因为我们在参数args
中有一个包含String
元素的切片,但build
函数不拥有args
。要返回Config
实例的所有权,我们必须从Config
的query
和file_path
字段克隆值,以便Config
实例可以拥有其值。
With our new knowledge about iterators, we can change the build
function to
take ownership of an iterator as its argument instead of borrowing a slice.
We’ll use the iterator functionality instead of the code that checks the length
of the slice and indexes into specific locations. This will clarify what the
Config::build
function is doing because the iterator will access the values.
有了关于迭代器的新知识,我们可以更改build
函数以将迭代器的所有权作为其参数,而不是借用切片。我们将使用迭代器功能,而不是检查切片长度和特定位置索引的代码。这将澄清Config::build
函数正在做什么,因为迭代器将访问这些值。
Once Config::build
takes ownership of the iterator and stops using indexing
operations that borrow, we can move the String
values from the iterator into
Config
rather than calling clone
and making a new allocation.
一旦Config::build
获得迭代器的所有权并停止使用借用的索引操作,我们就可以将String
值从迭代器移动到Config
中,而不是调用clone
并进行新的分配。
Using the Returned Iterator Directly
直接使用返回的迭代器
Open your I/O project’s src/main.rs file, which should look like this:
打开 I/O 项目的src/main.rs文件,该文件应如下所示:
Filename: src/main.rs 文件名:src/main.rs
We’ll first change the start of the main
function that we had in Listing
12-24 to the code in Listing 13-18, which this time uses an iterator. This
won’t compile until we update Config::build
as well.
我们首先将清单 12-24 中的main
函数的开头更改为清单 13-18 中的代码,这次使用了迭代器。在我们更新Config::build
之前,这不会编译。
Filename: src/main.rs 文件名:src/main.rs
The env::args
function returns an iterator! Rather than collecting the
iterator values into a vector and then passing a slice to Config::build
, now
we’re passing ownership of the iterator returned from env::args
to
Config::build
directly.env::args
函数返回一个迭代器!现在我们不是将迭代器值收集到向量中,然后将切片传递给Config::build
,而是将从env::args
返回的迭代器的所有权直接传递给Config::build
。
Next, we need to update the definition of Config::build
. In your I/O
project’s src/lib.rs file, let’s change the signature of Config::build
to
look like Listing 13-19. This still won’t compile because we need to update the
function body.
接下来,我们需要更新Config::build
的定义。在 I/O 项目的src/lib.rs文件中,我们将Config::build
的签名更改为如清单 13-19 所示。这仍然无法编译,因为我们需要更新函数体。
Filename: src/lib.rs 文件名:src/lib.rs
The standard library documentation for the env::args
function shows that the
type of the iterator it returns is std::env::Args
, and that type implements
the Iterator
trait and returns String
values.env::args
函数的标准库文档显示,它返回的迭代器的类型是std::env::Args
,并且该类型实现Iterator
特征并返回String
值。
We’ve updated the signature of the Config::build
function so the parameter
args
has a generic type with the trait bounds impl Iterator<Item = String>
instead of &[String]
. This usage of the impl Trait
syntax we discussed in
the “Traits as Parameters” section of Chapter 10
means that args
can be any type that implements the Iterator
trait and
returns String
items.
我们更新了Config::build
函数的签名,因此参数args
具有通用类型,其特征边界impl Iterator<Item = String>
而不是&[String]
。我们在第 10 章的“作为参数的特征”忽略部分中讨论的impl Trait
语法的用法意味着args
可以是实现Iterator
特征并返回String
项的任何类型。
Because we’re taking ownership of args
and we’ll be mutating args
by
iterating over it, we can add the mut
keyword into the specification of the
args
parameter to make it mutable.
因为我们正在获取args
的所有权,并且我们将通过迭代来改变args
,所以我们可以将mut
关键字添加到args
参数的规范中以使其可变。
Using Iterator
Trait Methods Instead of Indexing
使用Iterator
特征方法而不是索引
Next, we’ll fix the body of Config::build
. Because args
implements the
Iterator
trait, we know we can call the next
method on it! Listing 13-20
updates the code from Listing 12-23 to use the next
method:
接下来,我们将修复Config::build
的主体。因为args
实现了Iterator
特性,所以我们知道我们可以调用它的next
方法!清单 13-20 更新了清单 12-23 中的代码以使用next
方法:
Filename: src/lib.rs 文件名:src/lib.rs
Remember that the first value in the return value of env::args
is the name of
the program. We want to ignore that and get to the next value, so first we call
next
and do nothing with the return value. Second, we call next
to get the
value we want to put in the query
field of Config
. If next
returns a
Some
, we use a match
to extract the value. If it returns None
, it means
not enough arguments were given and we return early with an Err
value. We do
the same thing for the file_path
value.
请记住, env::args
返回值中的第一个值是程序的名称。我们想忽略它并获取下一个值,因此首先我们调用next
并对返回值不执行任何操作。其次,我们调用next
来获取我们想要放入Config
的query
字段中的值。如果next
返回Some
,我们使用match
来提取值。如果它返回None
,则意味着没有给出足够的参数,我们会提前返回Err
值。我们对file_path
值执行相同的操作。
Making Code Clearer with Iterator Adaptors
使用迭代器适配器使代码更清晰
We can also take advantage of iterators in the search
function in our I/O
project, which is reproduced here in Listing 13-21 as it was in Listing 12-19:
我们还可以在 I/O 项目的search
函数中利用迭代器,清单 13-21 中重现了该项目,就像清单 12-19 中一样:
Filename: src/lib.rs 文件名:src/lib.rs
We can write this code in a more concise way using iterator adaptor methods.
Doing so also lets us avoid having a mutable intermediate results
vector. The
functional programming style prefers to minimize the amount of mutable state to
make code clearer. Removing the mutable state might enable a future enhancement
to make searching happen in parallel, because we wouldn’t have to manage
concurrent access to the results
vector. Listing 13-22 shows this change:
我们可以使用迭代器适配器方法以更简洁的方式编写此代码。这样做还可以让我们避免出现可变的中间results
向量。函数式编程风格更喜欢最小化可变状态的数量以使代码更清晰。删除可变状态可能会启用未来的增强功能,使搜索并行发生,因为我们不必管理对results
向量的并发访问。清单 13-22 显示了这一更改:
Filename: src/lib.rs 文件名:src/lib.rs
Recall that the purpose of the search
function is to return all lines in
contents
that contain the query
. Similar to the filter
example in Listing
13-16, this code uses the filter
adaptor to keep only the lines that
line.contains(query)
returns true
for. We then collect the matching lines
into another vector with collect
. Much simpler! Feel free to make the same
change to use iterator methods in the search_case_insensitive
function as
well.
回想一下, search
函数的目的是返回contents
中包含query
所有行。与清单 13-16 中的filter
示例类似,此代码使用filter
适配器仅保留line.contains(query)
返回true
行。然后我们使用collect
将匹配的线收集到另一个向量中。简单多了!您也可以随意进行相同的更改,以在search_case_insensitive
函数中使用迭代器方法。
Choosing Between Loops or Iterators
在循环或迭代器之间进行选择
The next logical question is which style you should choose in your own code and
why: the original implementation in Listing 13-21 or the version using
iterators in Listing 13-22. Most Rust programmers prefer to use the iterator
style. It’s a bit tougher to get the hang of at first, but once you get a feel
for the various iterator adaptors and what they do, iterators can be easier to
understand. Instead of fiddling with the various bits of looping and building
new vectors, the code focuses on the high-level objective of the loop. This
abstracts away some of the commonplace code so it’s easier to see the concepts
that are unique to this code, such as the filtering condition each element in
the iterator must pass.
下一个逻辑问题是您应该在自己的代码中选择哪种样式以及原因:清单 13-21 中的原始实现或清单 13-22 中使用迭代器的版本。大多数 Rust 程序员更喜欢使用迭代器风格。一开始掌握窍门有点困难,但是一旦您了解了各种迭代器适配器及其用途,迭代器就会更容易理解。该代码不是摆弄循环的各个部分和构建新向量,而是专注于循环的高级目标。这抽象了一些常见的代码,因此更容易看到该代码特有的概念,例如迭代器中每个元素必须通过的过滤条件。
But are the two implementations truly equivalent? The intuitive assumption
might be that the more low-level loop will be faster. Let’s talk about
performance.
但这两种实现真的等效吗?直观的假设可能是越低级的循环会越快。我们来谈谈性能。
Comparing Performance: Loops vs. Iterators
性能比较:循环与迭代器
To determine whether to use loops or iterators, you need to know which
implementation is faster: the version of the search
function with an explicit
for
loop or the version with iterators.
要确定是使用循环还是迭代器,您需要知道哪种实现更快:具有显式for
循环的search
函数版本或具有迭代器的版本。
We ran a benchmark by loading the entire contents of The Adventures of
Sherlock Holmes by Sir Arthur Conan Doyle into a String
and looking for the
word the in the contents. Here are the results of the benchmark on the
version of search
using the for
loop and the version using iterators:
我们通过将阿瑟·柯南道尔爵士所著的《夏洛克·福尔摩斯历险记》的全部内容加载到String
中并在内容中查找单词the来运行基准测试。以下是使用for
循环的search
版本和使用迭代器的版本的基准测试结果:
test bench_search_for ... bench: 19,620,300 ns/iter (+/- 915,700)
test bench_search_iter ... bench: 19,234,900 ns/iter (+/- 657,200)
The iterator version was slightly faster! We won’t explain the benchmark code
here, because the point is not to prove that the two versions are equivalent
but to get a general sense of how these two implementations compare
performance-wise.
迭代器版本稍微快一些!我们不会在这里解释基准测试代码,因为重点不是证明这两个版本是等效的,而是为了大致了解这两个实现在性能方面的比较。
For a more comprehensive benchmark, you should check using various texts of
various sizes as the contents
, different words and words of different lengths
as the query
, and all kinds of other variations. The point is this:
iterators, although a high-level abstraction, get compiled down to roughly the
same code as if you’d written the lower-level code yourself. Iterators are one
of Rust’s zero-cost abstractions, by which we mean using the abstraction
imposes no additional runtime overhead. This is analogous to how Bjarne
Stroustrup, the original designer and implementor of C++, defines
zero-overhead in “Foundations of C++” (2012):
为了获得更全面的基准,您应该检查使用不同大小的各种文本作为contents
,不同的单词和不同长度的单词作为query
,以及各种其他变体。要点是:迭代器虽然是高级抽象,但它会被编译为大致相同的代码,就像您自己编写较低级代码一样。迭代器是 Rust 的零成本抽象之一,我们的意思是使用该抽象不会带来额外的运行时开销。这类似于 C++ 的原始设计者和实现者 Bjarne Stroustrup 在《C++ 基础》(2012 年)中定义零开销的方式:
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.
一般来说,C++ 实现遵循零开销原则:不使用的东西,就不需要付费。更进一步:你所使用的东西,你无法更好地手工编码。
As another example, the following code is taken from an audio decoder. The
decoding algorithm uses the linear prediction mathematical operation to
estimate future values based on a linear function of the previous samples. This
code uses an iterator chain to do some math on three variables in scope: a
buffer
slice of data, an array of 12 coefficients
, and an amount by which
to shift data in qlp_shift
. We’ve declared the variables within this example
but not given them any values; although this code doesn’t have much meaning
outside of its context, it’s still a concise, real-world example of how Rust
translates high-level ideas to low-level code.
作为另一个示例,以下代码取自音频解码器。解码算法使用线性预测数学运算,根据先前样本的线性函数来估计未来值。此代码使用迭代器链对范围内的三个变量进行一些数学运算:数据buffer
切片、12 个coefficients
的数组以及qlp_shift
中数据的移位量。我们在这个例子中声明了变量,但没有给它们任何值;尽管这段代码在其上下文之外没有太多意义,但它仍然是 Rust 如何将高级思想转化为低级代码的简洁、真实的示例。
let buffer: &mut [i32];
let coefficients: [i64; 12];
let qlp_shift: i16;
for i in 12..buffer.len() {
let prediction = coefficients.iter()
.zip(&buffer[i - 12..i])
.map(|(&c, &s)| c * s as i64)
.sum::<i64>() >> qlp_shift;
let delta = buffer[i];
buffer[i] = prediction as i32 + delta;
}
To calculate the value of prediction
, this code iterates through each of the
12 values in coefficients
and uses the zip
method to pair the coefficient
values with the previous 12 values in buffer
. Then, for each pair, we
multiply the values together, sum all the results, and shift the bits in the
sum qlp_shift
bits to the right.
为了计算prediction
值,此代码迭代了coefficients
中的12个值中的每一个,并使用zip
方法将系数值与buffer
中的前12个值配对。然后,对于每一对,我们将这些值相乘,对所有结果求和,并将总和qlp_shift
位中的位向右移动。
Calculations in applications like audio decoders often prioritize performance
most highly. Here, we’re creating an iterator, using two adaptors, and then
consuming the value. What assembly code would this Rust code compile to? Well,
as of this writing, it compiles down to the same assembly you’d write by hand.
There’s no loop at all corresponding to the iteration over the values in
coefficients
: Rust knows that there are 12 iterations, so it “unrolls” the
loop. Unrolling is an optimization that removes the overhead of the loop
controlling code and instead generates repetitive code for each iteration of
the loop.
音频解码器等应用中的计算通常最优先考虑性能。在这里,我们使用两个适配器创建一个迭代器,然后使用该值。该 Rust 代码会编译成什么汇编代码?嗯,在撰写本文时,它编译成与您手动编写的程序集相同的程序集。根本没有对应于coefficients
迭代的循环:Rust 知道有 12 次迭代,因此它“展开”循环。展开是一种优化,它消除了循环控制代码的开销,而是为循环的每次迭代生成重复的代码。
All of the coefficients get stored in registers, which means accessing the
values is very fast. There are no bounds checks on the array access at runtime.
All these optimizations that Rust is able to apply make the resulting code
extremely efficient. Now that you know this, you can use iterators and closures
without fear! They make code seem like it’s higher level but don’t impose a
runtime performance penalty for doing so.
所有系数都存储在寄存器中,这意味着访问这些值非常快。运行时对数组访问没有边界检查。 Rust 能够应用的所有这些优化使生成的代码极其高效。现在您知道了这一点,您可以毫无恐惧地使用迭代器和闭包!它们使代码看起来更高级别,但不会因此而造成运行时性能损失。
Summary 概括
Closures and iterators are Rust features inspired by functional programming
language ideas. They contribute to Rust’s capability to clearly express
high-level ideas at low-level performance. The implementations of closures and
iterators are such that runtime performance is not affected. This is part of
Rust’s goal to strive to provide zero-cost abstractions.
闭包和迭代器是受函数式编程语言思想启发的 Rust 功能。它们有助于 Rust 以低级性能清楚地表达高级思想的能力。闭包和迭代器的实现不会影响运行时性能。这是 Rust 努力提供零成本抽象的目标的一部分。
Now that we’ve improved the expressiveness of our I/O project, let’s look at
some more features of cargo
that will help us share the project with the
world.
现在我们已经提高了 I/O 项目的表现力,让我们看看cargo
的更多功能,这些功能将帮助我们与世界分享该项目。
More About Cargo and Crates.io
关于 Cargo 和 Crates.io 的更多信息
So far we’ve used only the most basic features of Cargo to build, run, and test
our code, but it can do a lot more. In this chapter, we’ll discuss some of its
other, more advanced features to show you how to do the following:
到目前为止,我们只使用了 Cargo 最基本的功能来构建、运行和测试我们的代码,但它可以做更多的事情。在本章中,我们将讨论它的一些其他更高级的功能,以向您展示如何执行以下操作:
- Customize your build through release profiles
通过发布配置文件自定义您的构建 - Publish libraries on crates.io
在crates.io上发布库 - Organize large projects with workspaces
使用工作区组织大型项目 - Install binaries from crates.io
从crates.io安装二进制文件 - Extend Cargo using custom commands
使用自定义命令扩展 Cargo
Cargo can do even more than the functionality we cover in this chapter, so for
a full explanation of all its features, see its
documentation.
Cargo 的功能甚至比我们在本章中介绍的功能还要多,因此有关其所有功能的完整说明,请参阅其文档。
Customizing Builds with Release Profiles
使用发布配置文件自定义构建
In Rust, release profiles are predefined and customizable profiles with
different configurations that allow a programmer to have more control over
various options for compiling code. Each profile is configured independently of
the others.
在 Rust 中,发布配置文件是预定义和可定制的配置文件,具有不同的配置,允许程序员更好地控制编译代码的各种选项。每个配置文件的配置均独立于其他配置文件。
Cargo has two main profiles: the dev
profile Cargo uses when you run cargo build
and the release
profile Cargo uses when you run cargo build --release
. The dev
profile is defined with good defaults for development,
and the release
profile has good defaults for release builds.
Cargo 有两个主要配置文件:运行cargo build
时 Cargo 使用的dev
配置文件和运行cargo build --release
时 Cargo 使用的release
配置文件。 dev
配置文件定义了良好的开发默认值, release
配置文件定义了良好的发布版本默认值。
These profile names might be familiar from the output of your builds:
从构建的输出中,这些配置文件名称可能很熟悉:
$ cargo build
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
$ cargo build --release
Finished release [optimized] target(s) in 0.0s
The dev
and release
are these different profiles used by the compiler.dev
和release
是编译器使用的不同配置文件。
Cargo has default settings for each of the profiles that apply when you haven’t
explicitly added any [profile.*]
sections in the project’s Cargo.toml file.
By adding [profile.*]
sections for any profile you want to customize, you
override any subset of the default settings. For example, here are the default
values for the opt-level
setting for the dev
and release
profiles:
当您未在项目的Cargo.toml文件中显式添加任何[profile.*]
部分时,Cargo 对每个配置文件都有默认设置。通过为您想要自定义的任何配置文件添加[profile.*]
部分,您可以覆盖默认设置的任何子集。例如,以下是dev
和release
配置文件的opt-level
设置的默认值:
Filename: Cargo.toml 文件名:Cargo.toml
[profile.dev]
opt-level = 0
[profile.release]
opt-level = 3
The opt-level
setting controls the number of optimizations Rust will apply to
your code, with a range of 0 to 3. Applying more optimizations extends
compiling time, so if you’re in development and compiling your code often,
you’ll want fewer optimizations to compile faster even if the resulting code
runs slower. The default opt-level
for dev
is therefore 0
. When you’re
ready to release your code, it’s best to spend more time compiling. You’ll only
compile in release mode once, but you’ll run the compiled program many times,
so release mode trades longer compile time for code that runs faster. That is
why the default opt-level
for the release
profile is 3
.opt-level
设置控制 Rust 将应用于您的代码的优化数量,范围为 0 到 3。应用更多优化会延长编译时间,因此,如果您经常进行开发和编译代码,则需要更少的优化即使生成的代码运行速度较慢,也可以进行优化以加快编译速度。因此dev
的默认opt-level
是0
。当您准备好发布代码时,最好花更多时间进行编译。您只会在发布模式下编译一次,但会多次运行编译后的程序,因此发布模式会用更长的编译时间换取运行速度更快的代码。这就是为什么release
文件的默认opt-level
是3
。
You can override a default setting by adding a different value for it in
Cargo.toml. For example, if we want to use optimization level 1 in the
development profile, we can add these two lines to our project’s Cargo.toml
file:
您可以通过在Cargo.toml中添加不同的值来覆盖默认设置。例如,如果我们想在开发配置文件中使用优化级别 1,我们可以将这两行添加到项目的Cargo.toml文件中:
Filename: Cargo.toml 文件名:Cargo.toml
[profile.dev]
opt-level = 1
This code overrides the default setting of 0
. Now when we run cargo build
,
Cargo will use the defaults for the dev
profile plus our customization to
opt-level
. Because we set opt-level
to 1
, Cargo will apply more
optimizations than the default, but not as many as in a release build.
此代码覆盖默认设置0
。现在,当我们运行cargo build
时,Cargo 将使用dev
配置文件的默认值以及我们对opt-level
的自定义。因为我们将opt-level
设置为1
,所以 Cargo 将应用比默认值更多的优化,但不会像发布版本中那么多。
For the full list of configuration options and defaults for each profile, see
Cargo’s documentation.
有关每个配置文件的配置选项和默认值的完整列表,请参阅Cargo 的文档。
Publishing a Crate to Crates.io
将 Crate 发布到 Crates.io
We’ve used packages from crates.io as
dependencies of our project, but you can also share your code with other people
by publishing your own packages. The crate registry at
crates.io distributes the source code of
your packages, so it primarily hosts code that is open source.
我们使用crates.io中的包来忽略作为我们项目的依赖项,但您也可以通过发布您自己的包来与其他人共享您的代码。 crates.ioignore上的板条箱注册表分发了软件包的源代码,因此它主要托管开源代码。
Rust and Cargo have features that make your published package easier for people
to find and use. We’ll talk about some of these features next and then explain
how to publish a package.
Rust 和 Cargo 的功能可以使您发布的包更容易被人们找到和使用。接下来我们将讨论其中一些功能,然后解释如何发布包。
Making Useful Documentation Comments
做出有用的文档注释
Accurately documenting your packages will help other users know how and when to
use them, so it’s worth investing the time to write documentation. In Chapter
3, we discussed how to comment Rust code using two slashes, //
. Rust also has
a particular kind of comment for documentation, known conveniently as a
documentation comment, that will generate HTML documentation. The HTML
displays the contents of documentation comments for public API items intended
for programmers interested in knowing how to use your crate as opposed to how
your crate is implemented.
准确记录您的包将帮助其他用户了解如何以及何时使用它们,因此值得投入时间编写文档。在第 3 章中,我们讨论了如何使用两个斜杠//
来注释 Rust 代码。 Rust 还有一种特殊类型的文档注释,方便地称为文档注释,它将生成 HTML 文档。 HTML 显示公共 API 项目的文档注释内容,供有兴趣了解如何使用您的 crate 而不是如何实现您的 crate 的程序员使用。
Documentation comments use three slashes, ///
, instead of two and support
Markdown notation for formatting the text. Place documentation comments just
before the item they’re documenting. Listing 14-1 shows documentation comments
for an add_one
function in a crate named my_crate
.
文档注释使用三个斜杠///
而不是两个,并支持 Markdown 表示法来格式化文本。将文档注释放在他们正在记录的项目之前。清单 14-1 显示了名为my_crate
的 crate 中add_one
函数的文档注释。
Filename: src/lib.rs 文件名:src/lib.rs
/// 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) -> i32 {
x + 1
}
Here, we give a description of what the add_one
function does, start a
section with the heading Examples
, and then provide code that demonstrates
how to use the add_one
function. We can generate the HTML documentation from
this documentation comment by running cargo doc
. This command runs the
rustdoc
tool distributed with Rust and puts the generated HTML documentation
in the target/doc directory.
在这里,我们描述了add_one
函数的作用,以标题Examples
开始一个部分,然后提供演示如何使用add_one
函数的代码。我们可以通过运行cargo doc
从此文档注释生成 HTML 文档。此命令运行随 Rust 一起分发的rustdoc
工具,并将生成的 HTML 文档放入target/doc目录中。
For convenience, running cargo doc --open
will build the HTML for your
current crate’s documentation (as well as the documentation for all of your
crate’s dependencies) and open the result in a web browser. Navigate to the
add_one
function and you’ll see how the text in the documentation comments is
rendered, as shown in Figure 14-1:
为方便起见,运行cargo doc --open
将为当前 crate 的文档(以及所有 crate 依赖项的文档)构建 HTML,并在 Web 浏览器中打开结果。导航到add_one
函数,您将看到文档注释中的文本是如何呈现的,如图 14-1 所示:
Commonly Used Sections 常用部分
We used the # Examples
Markdown heading in Listing 14-1 to create a section
in the HTML with the title “Examples.” Here are some other sections that crate
authors commonly use in their documentation:
我们使用清单 14-1 中的# Examples
Markdown 标题在 HTML 中创建一个标题为“Examples”的部分。以下是 crate 作者在其文档中常用的其他一些部分:
- Panics: The scenarios in which the function being documented could
panic. Callers of the function who don’t want their programs to panic should
make sure they don’t call the function in these situations.
恐慌:正在记录的函数可能会出现恐慌的情况。不希望程序出现恐慌的函数调用者应确保在这些情况下不会调用该函数。 - Errors: If the function returns a
Result
, describing the kinds of errors that might occur and what conditions might cause those errors to be returned can be helpful to callers so they can write code to handle the different kinds of errors in different ways.
错误:如果函数返回Result
,则描述可能发生的错误类型以及可能导致返回这些错误的条件对调用者很有帮助,以便他们可以编写代码以不同的方式处理不同类型的错误。 - Safety: If the function is
unsafe
to call (we discuss unsafety in Chapter 19), there should be a section explaining why the function is unsafe and covering the invariants that the function expects callers to uphold.
安全性:如果函数调用unsafe
(我们在第 19 章中讨论不安全性),应该有一个部分解释为什么该函数不安全并涵盖该函数期望调用者维护的不变量。
Most documentation comments don’t need all of these sections, but this is a
good checklist to remind you of the aspects of your code users will be
interested in knowing about.
大多数文档注释不需要所有这些部分,但这是一个很好的清单,可以提醒您用户有兴趣了解代码的哪些方面。
Documentation Comments as Tests
文档注释作为测试
Adding example code blocks in your documentation comments can help demonstrate
how to use your library, and doing so has an additional bonus: running cargo test
will run the code examples in your documentation as tests! Nothing is
better than documentation with examples. But nothing is worse than examples
that don’t work because the code has changed since the documentation was
written. If we run cargo test
with the documentation for the add_one
function from Listing 14-1, we will see a section in the test results like this:
在文档注释中添加示例代码块可以帮助演示如何使用您的库,这样做还有一个额外的好处:运行cargo test
将运行文档中的代码示例作为测试!没有什么比带有示例的文档更好的了。但没有什么比示例无法工作更糟糕的了,因为自文档编写以来代码已发生更改。如果我们使用清单 14-1 中add_one
函数的文档运行cargo test
,我们将在测试结果中看到如下部分:
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
Now if we change either the function or the example so the assert_eq!
in the
example panics and run cargo test
again, we’ll see that the doc tests catch
that the example and the code are out of sync with each other!
现在,如果我们更改函数或示例,则assert_eq!
在示例恐慌并再次运行cargo test
中,我们将看到文档测试发现示例和代码彼此不同步!
Commenting Contained Items
评论所含项目
The style of doc comment //!
adds documentation to the item that contains the
comments rather than to the items following the comments. We typically use
these doc comments inside the crate root file (src/lib.rs by convention) or
inside a module to document the crate or the module as a whole.
文档注释的风格//!
将文档添加到包含注释的项目,而不是添加到注释后面的项目。我们通常在 crate 根文件(按照惯例src/lib.rs )或模块内部使用这些文档注释来记录 crate 或整个模块。
For example, to add documentation that describes the purpose of the my_crate
crate that contains the add_one
function, we add documentation comments that
start with //!
to the beginning of the src/lib.rs file, as shown in Listing
14-2:
例如,要添加描述包含add_one
函数的my_crate
箱用途的文档,我们添加以//!
开头的文档注释。到src/lib.rs文件的开头,如清单 14-2 所示:
Filename: src/lib.rs 文件名:src/lib.rs
Notice there isn’t any code after the last line that begins with //!
. Because
we started the comments with //!
instead of ///
, we’re documenting the item
that contains this comment rather than an item that follows this comment. In
this case, that item is the src/lib.rs file, which is the crate root. These
comments describe the entire crate.
请注意,以//!
。因为我们以//!
我们记录的是包含此评论的项目,而不是///
,而不是此评论后面的项目。在本例中,该项目是src/lib.rs文件,它是 crate 根目录。这些评论描述了整个箱子。
When we run cargo doc --open
, these comments will display on the front
page of the documentation for my_crate
above the list of public items in the
crate, as shown in Figure 14-2:
当我们运行cargo doc --open
时,这些注释将显示在my_crate
文档的首页上,位于 crate 中公共项目列表的上方,如图 14-2 所示:
Documentation comments within items are useful for describing crates and
modules especially. Use them to explain the overall purpose of the container to
help your users understand the crate’s organization.
项目中的文档注释对于描述包和模块尤其有用。使用它们来解释容器的总体用途,以帮助您的用户了解包的组织。
Exporting a Convenient Public API with pub use
通过pub use
导出便捷的公共 API
The structure of your public API is a major consideration when publishing a
crate. People who use your crate are less familiar with the structure than you
are and might have difficulty finding the pieces they want to use if your crate
has a large module hierarchy.
发布 crate 时,公共 API 的结构是一个主要考虑因素。使用你的板条箱的人不像你那么熟悉结构,如果你的板条箱有一个很大的模块层次结构,他们可能很难找到他们想要使用的部分。
In Chapter 7, we covered how to make items public using the pub
keyword, and
bring items into a scope with the use
keyword. However, the structure that
makes sense to you while you’re developing a crate might not be very convenient
for your users. You might want to organize your structs in a hierarchy
containing multiple levels, but then people who want to use a type you’ve
defined deep in the hierarchy might have trouble finding out that type exists.
They might also be annoyed at having to enter use
my_crate::some_module::another_module::UsefulType;
rather than use
my_crate::UsefulType;
.
在第 7 章中,我们介绍了如何使用pub
关键字将项目公开,以及如何使用use
关键字将项目引入范围。但是,在开发 crate 时对您有意义的结构可能对您的用户来说不太方便。您可能希望在包含多个级别的层次结构中组织结构体,但是想要使用您在层次结构深处定义的类型的人可能很难发现该类型的存在。他们可能还会因为必须输入use
my_crate::some_module::another_module::UsefulType;
感到恼火。而不是use
my_crate::UsefulType;
。
The good news is that if the structure isn’t convenient for others to use
from another library, you don’t have to rearrange your internal organization:
instead, you can re-export items to make a public structure that’s different
from your private structure by using pub use
. Re-exporting takes a public
item in one location and makes it public in another location, as if it were
defined in the other location instead.
好消息是,如果该结构不方便其他人从另一个库使用,您不必重新安排您的内部组织:相反,您可以重新导出项目以创建与您的私有结构不同的公共结构通过使用pub use
.重新导出会在一个位置获取公共项目,并将其在另一个位置公开,就像它是在另一个位置定义的一样。
For example, say we made a library named art
for modeling artistic concepts.
Within this library are two modules: a kinds
module containing two enums
named PrimaryColor
and SecondaryColor
and a utils
module containing a
function named mix
, as shown in Listing 14-3:
例如,假设我们创建了一个名为art
库来建模艺术概念。该库中有两个模块:一个kinds
模块,包含两个名为PrimaryColor
和SecondaryColor
的枚举;一个utils
模块,包含一个名为mix
函数,如清单 14-3 所示:
Filename: src/lib.rs 文件名:src/lib.rs
Figure 14-3 shows what the front page of the documentation for this crate
generated by cargo doc
would look like:
图14-3显示了由cargo doc
生成的这个crate的文档的首页是什么样子的:
Note that the PrimaryColor
and SecondaryColor
types aren’t listed on the
front page, nor is the mix
function. We have to click kinds
and utils
to
see them.
请注意, PrimaryColor
和SecondaryColor
类型未在首页上列出, mix
函数也未列出。我们必须单击kinds
和utils
才能看到它们。
Another crate that depends on this library would need use
statements that
bring the items from art
into scope, specifying the module structure that’s
currently defined. Listing 14-4 shows an example of a crate that uses the
PrimaryColor
and mix
items from the art
crate:
依赖于该库的另一个板条箱将需要use
语句将art
中的项目带入范围,指定当前定义的模块结构。清单 14-4 显示了一个使用PrimaryColor
并mix
art
crate 中项目的 crate 示例:
Filename: src/main.rs 文件名:src/main.rs
use art::kinds::PrimaryColor;
use art::utils::mix;
fn main() {
let red = PrimaryColor::Red;
let yellow = PrimaryColor::Yellow;
mix(red, yellow);
}
The author of the code in Listing 14-4, which uses the art
crate, had to
figure out that PrimaryColor
is in the kinds
module and mix
is in the
utils
module. The module structure of the art
crate is more relevant to
developers working on the art
crate than to those using it. The internal
structure doesn’t contain any useful information for someone trying to
understand how to use the art
crate, but rather causes confusion because
developers who use it have to figure out where to look, and must specify the
module names in the use
statements.
清单 14-4 中使用art
crate 的代码的作者必须弄清楚PrimaryColor
位于kinds
模块中, mix
位于utils
模块中。 art
crate 的模块结构与处理art
crate 的开发人员比与使用 Art crate 的开发人员更相关。对于试图了解如何使用art
crate 的人来说,内部结构不包含任何有用的信息,反而会造成混乱,因为使用它的开发人员必须弄清楚在哪里查看,并且必须在use
语句中指定模块名称。
To remove the internal organization from the public API, we can modify the
art
crate code in Listing 14-3 to add pub use
statements to re-export the
items at the top level, as shown in Listing 14-5:
要从公共 API 中删除内部组织,我们可以修改清单 14-3 中的art
crate 代码,添加pub use
语句以重新导出顶层的项目,如清单 14-5 所示:
Filename: src/lib.rs 文件名:src/lib.rs
The API documentation that cargo doc
generates for this crate will now list
and link re-exports on the front page, as shown in Figure 14-4, making the
PrimaryColor
and SecondaryColor
types and the mix
function easier to find.cargo doc
为此 crate 生成的 API 文档现在将在首页上列出并链接重新导出,如图 14-4 所示,使得PrimaryColor
和SecondaryColor
类型以及mix
函数更容易找到。
The art
crate users can still see and use the internal structure from Listing
14-3 as demonstrated in Listing 14-4, or they can use the more convenient
structure in Listing 14-5, as shown in Listing 14-6:art
crate 用户仍然可以看到并使用清单 14-3 中的内部结构,如清单 14-4 所示,或者他们可以使用清单 14-5 中更方便的结构,如清单 14-6 所示:
Filename: src/main.rs 文件名:src/main.rs
In cases where there are many nested modules, re-exporting the types at the top
level with pub use
can make a significant difference in the experience of
people who use the crate. Another common use of pub use
is to re-export
definitions of a dependency in the current crate to make that crate’s
definitions part of your crate’s public API.
在有许多嵌套模块的情况下,使用pub use
在顶层重新导出类型可以对使用 crate 的人的体验产生显着影响。 pub use
的另一个常见用途是重新导出当前 crate 中依赖项的定义,以使该 crate 的定义成为 crate 公共 API 的一部分。
Creating a useful public API structure is more of an art than a science, and
you can iterate to find the API that works best for your users. Choosing pub use
gives you flexibility in how you structure your crate internally and
decouples that internal structure from what you present to your users. Look at
some of the code of crates you’ve installed to see if their internal structure
differs from their public API.
创建有用的公共 API 结构与其说是一门科学,不如说是一门艺术,您可以迭代找到最适合您的用户的 API。选择pub use
可以让您灵活地在内部构建您的 crate,并将内部结构与您向用户呈现的内容分离。查看您安装的 crate 的一些代码,看看它们的内部结构是否与其公共 API 不同。
Setting Up a Crates.io Account
设置 Crates.io 帐户
Before you can publish any crates, you need to create an account on
crates.io and get an API token. To do so,
visit the home page at crates.io and log
in via a GitHub account. (The GitHub account is currently a requirement, but
the site might support other ways of creating an account in the future.) Once
you’re logged in, visit your account settings at
https://crates.io/me/ and retrieve your
API key. Then run the cargo login
command and paste your API key when prompted, like this:
在发布任何 crate 之前,您需要在crates.ioignore上创建一个帐户并获取 API 令牌。为此,请访问crates.io主页忽略并通过 GitHub 帐户登录。 (目前需要 GitHub 帐户,但该网站将来可能支持其他创建帐户的方式。)登录后,请访问您的帐户设置: https://crates.io/me/忽略并检索您的 API 密钥。然后运行cargo login
命令并在出现提示时粘贴您的 API 密钥,如下所示:
$ cargo login
abcdefghijklmnopqrstuvwxyz012345
This command will inform Cargo of your API token and store it locally in
~/.cargo/credentials. Note that this token is a secret: do not share it
with anyone else. If you do share it with anyone for any reason, you should
revoke it and generate a new token on crates.io.
此命令将通知 Cargo 您的 API 令牌并将其本地存储在~/.cargo/credentials中。请注意,此令牌是一个秘密:请勿与其他任何人共享。如果您出于任何原因与任何人共享它,您应该撤销它并在crates.ioignore上生成一个新令牌。
Adding Metadata to a New Crate
将元数据添加到新 crate
Let’s say you have a crate you want to publish. Before publishing, you’ll need
to add some metadata in the [package]
section of the crate’s Cargo.toml
file.
假设您有一个想要发布的箱子。在发布之前,您需要在包的Cargo.toml文件的[package]
部分添加一些元数据。
Your crate will need a unique name. While you’re working on a crate locally,
you can name a crate whatever you’d like. However, crate names on
crates.io are allocated on a first-come,
first-served basis. Once a crate name is taken, no one else can publish a crate
with that name. Before attempting to publish a crate, search for the name you
want to use. If the name has been used, you will need to find another name and
edit the name
field in the Cargo.toml file under the [package]
section to
use the new name for publishing, like so:
您的板条箱需要一个唯一的名称。当您在本地处理板条箱时,您可以根据自己的喜好命名板条箱。然而, crates.ioignore上的板条箱名称是按照先到先得的原则分配的。一旦使用了 crate 名称,其他人就无法发布具有该名称的 crate。在尝试发布 crate 之前,请搜索您要使用的名称。如果该名称已被使用,您需要找到另一个名称并编辑Cargo.toml文件中[package]
部分下的name
字段,以使用新名称进行发布,如下所示:
Filename: Cargo.toml 文件名:Cargo.toml
[package]
name = "guessing_game"
Even if you’ve chosen a unique name, when you run cargo publish
to publish
the crate at this point, you’ll get a warning and then an error:
即使您选择了唯一的名称,当您此时运行cargo publish
来发布箱子时,您也会收到警告,然后收到错误:
$ 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
This errors because you’re missing some crucial information: a description and
license are required so people will know what your crate does and under what
terms they can use it. In Cargo.toml, add a description that’s just a
sentence or two, because it will appear with your crate in search results. For
the license
field, you need to give a license identifier value. The Linux
Foundation’s Software Package Data Exchange (SPDX) lists the identifiers
you can use for this value. For example, to specify that you’ve licensed your
crate using the MIT License, add the MIT
identifier:
出现此错误是因为您缺少一些关键信息:需要描述和许可证,以便人们知道您的板条箱的用途以及他们可以在什么条款下使用它。在Cargo.toml中,添加一两句话的描述,因为它将与您的箱子一起出现在搜索结果中。对于license
字段,您需要提供许可证标识符值。 Linux 基金会的软件包数据交换 (SPDX)列出了可用于该值的标识符。例如,要指定您已使用 MIT 许可证对您的包进行许可,请添加MIT
标识符:
Filename: Cargo.toml 文件名:Cargo.toml
[package]
name = "guessing_game"
license = "MIT"
If you want to use a license that doesn’t appear in the SPDX, you need to place
the text of that license in a file, include the file in your project, and then
use license-file
to specify the name of that file instead of using the
license
key.
如果您想使用 SPDX 中未出现的许可证,则需要将该许可证的文本放入文件中,将该文件包含在您的项目中,然后使用license-file
来指定该文件的名称使用license
密钥。
Guidance on which license is appropriate for your project is beyond the scope
of this book. Many people in the Rust community license their projects in the
same way as Rust by using a dual license of MIT OR Apache-2.0
. This practice
demonstrates that you can also specify multiple license identifiers separated
by OR
to have multiple licenses for your project.
关于哪种许可证适合您的项目的指导超出了本书的范围。 Rust 社区中的许多人使用MIT OR Apache-2.0
的双重许可证,以与 Rust 相同的方式许可他们的项目。此实践表明,您还可以指定由OR
分隔的多个许可证标识符,以便为您的项目拥有多个许可证。
With a unique name, the version, your description, and a license added, the
Cargo.toml file for a project that is ready to publish might look like this:
使用唯一的名称、版本、描述和添加的许可证后,准备发布的项目的Cargo.toml文件可能如下所示:
Filename: Cargo.toml 文件名:Cargo.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]
Cargo’s documentation describes other
metadata you can specify to ensure others can discover and use your crate more
easily.
Cargo 的文档描述了您可以指定的其他元数据,以确保其他人可以更轻松地发现和使用您的 crate。
Publishing to Crates.io 发布到 Crates.io
Now that you’ve created an account, saved your API token, chosen a name for
your crate, and specified the required metadata, you’re ready to publish!
Publishing a crate uploads a specific version to
crates.io for others to use.
现在您已经创建了一个帐户,保存了 API 令牌,为您的 crate 选择了名称,并指定了所需的元数据,您就可以发布了!发布 crate 会将特定版本上传到crates.io,忽略以供其他人使用。
Be careful, because a publish is permanent. The version can never be
overwritten, and the code cannot be deleted. One major goal of
crates.io is to act as a permanent archive
of code so that builds of all projects that depend on crates from
crates.io will continue to work. Allowing
version deletions would make fulfilling that goal impossible. However, there is
no limit to the number of crate versions you can publish.
请小心,因为发布是永久性的。版本永远无法被覆盖,代码也无法被删除。 crates.ioignore的一个主要目标是充当代码的永久存档,以便依赖crates.ioignore的 crate 的所有项目的构建都将继续工作。允许版本删除将使实现该目标变得不可能。但是,您可以发布的 crate 版本数量没有限制。
Run the cargo publish
command again. It should succeed now:
再次运行cargo publish
命令。现在应该成功了:
$ 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)
Congratulations! You’ve now shared your code with the Rust community, and
anyone can easily add your crate as a dependency of their project.
恭喜!您现在已经与 Rust 社区共享了您的代码,任何人都可以轻松地将您的板条箱添加为其项目的依赖项。
Publishing a New Version of an Existing Crate
发布现有 crate 的新版本
When you’ve made changes to your crate and are ready to release a new version,
you change the version
value specified in your Cargo.toml file and
republish. Use the Semantic Versioning rules to decide what an
appropriate next version number is based on the kinds of changes you’ve made.
Then run cargo publish
to upload the new version.
当您对 crate 进行更改并准备发布新版本时,您可以更改Cargo.toml文件中指定的version
值并重新发布。使用语义版本控制规则根据您所做的更改类型来决定合适的下一个版本号。然后运行cargo publish
来上传新版本。
Deprecating Versions from Crates.io with cargo yank
使用cargo yank
弃用来自 Crates.io 的版本
Although you can’t remove previous versions of a crate, you can prevent any
future projects from adding them as a new dependency. This is useful when a
crate version is broken for one reason or another. In such situations, Cargo
supports yanking a crate version.
尽管您无法删除包的早期版本,但您可以防止任何未来的项目将它们添加为新的依赖项。当板条箱版本由于某种原因被破坏时,这非常有用。在这种情况下,Cargo 支持拉取crate 版本。
Yanking a version prevents new projects from depending on that version while
allowing all existing projects that depend on it to continue. Essentially, a
yank means that all projects with a Cargo.lock will not break, and any future
Cargo.lock files generated will not use the yanked version.
拉取版本可防止新项目依赖于该版本,同时允许依赖于该版本的所有现有项目继续。本质上,yank 意味着所有具有Cargo.lock的项目都不会中断,并且将来生成的任何Cargo.lock文件都不会使用 yank 版本。
To yank a version of a crate, in the directory of the crate that you’ve
previously published, run cargo yank
and specify which version you want to
yank. For example, if we’ve published a crate named guessing_game
version
1.0.1 and we want to yank it, in the project directory for guessing_game
we’d
run:
要拉取 crate 的版本,请在您之前发布的 crate 的目录中运行cargo yank
并指定要拉取的版本。例如,如果我们发布了一个名为guessing_game
version 1.0.1的包,并且想要将其拉出,则在guessing_game
的项目目录中运行:
$ cargo yank --vers 1.0.1
Updating crates.io index
Yank guessing_game@1.0.1
By adding --undo
to the command, you can also undo a yank and allow projects
to start depending on a version again:
通过在命令中添加--undo
,您还可以撤消 yank 并允许项目再次根据版本启动:
$ cargo yank --vers 1.0.1 --undo
Updating crates.io index
Unyank guessing_game@1.0.1
A yank does not delete any code. It cannot, for example, delete accidentally
uploaded secrets. If that happens, you must reset those secrets immediately.
猛拉不会删除任何代码。例如,它无法删除意外上传的机密。如果发生这种情况,您必须立即重置这些机密。
Cargo Workspaces 货物工作空间
In Chapter 12, we built a package that included a binary crate and a library
crate. As your project develops, you might find that the library crate
continues to get bigger and you want to split your package further into
multiple library crates. Cargo offers a feature called workspaces that can
help manage multiple related packages that are developed in tandem.
在第 12 章中,我们构建了一个包含二进制 crate 和库 crate 的包。随着项目的发展,您可能会发现库 crate 不断变大,并且您希望将包进一步拆分为多个库 crate。 Cargo 提供了一个称为工作区的功能,可以帮助管理串联开发的多个相关包。
Creating a Workspace 创建工作空间
A workspace is a set of packages that share the same Cargo.lock and output
directory. Let’s make a project using a workspace—we’ll use trivial code so we
can concentrate on the structure of the workspace. There are multiple ways to
structure a workspace, so we’ll just show one common way. We’ll have a
workspace containing a binary and two libraries. The binary, which will provide
the main functionality, will depend on the two libraries. One library will
provide an add_one
function, and a second library an add_two
function.
These three crates will be part of the same workspace. We’ll start by creating
a new directory for the workspace:
工作空间是一组共享相同Cargo.lock和输出目录的包。让我们使用工作区创建一个项目 - 我们将使用简单的代码,以便我们可以专注于工作区的结构。构建工作区的方法有多种,因此我们仅展示一种常见的方法。我们将有一个包含二进制文件和两个库的工作区。提供主要功能的二进制文件将依赖于这两个库。第一个库将提供add_one
函数,第二个库将提供add_two
函数。这三个板条箱将属于同一工作区。我们首先为工作区创建一个新目录:
$ mkdir add
$ cd add
Next, in the add directory, we create the Cargo.toml file that will
configure the entire workspace. This file won’t have a [package]
section.
Instead, it will start with a [workspace]
section that will allow us to add
members to the workspace by specifying the path to the package with our binary
crate; in this case, that path is adder:
接下来,在add目录中,我们创建将配置整个工作区的Cargo.toml文件。该文件不会有[package]
部分。相反,它将以[workspace]
部分开头,该部分允许我们通过指定二进制板条箱的包路径来将成员添加到工作区;在本例中,该路径是adder :
Filename: Cargo.toml 文件名:Cargo.toml
[workspace]
members = [
"adder",
]
Next, we’ll create the adder
binary crate by running cargo new
within the
add directory:
接下来,我们将通过在add目录中运行cargo new
来创建adder
二进制包:
$ cargo new adder
Created binary (application) `adder` package
At this point, we can build the workspace by running cargo build
. The files
in your add directory should look like this:
此时,我们可以通过运行cargo build
来构建工作区。添加目录中的文件应如下所示:
├── Cargo.lock
├── Cargo.toml
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
The workspace has one target directory at the top level that the compiled
artifacts will be placed into; the adder
package doesn’t have its own
target directory. Even if we were to run cargo build
from inside the
adder directory, the compiled artifacts would still end up in add/target
rather than add/adder/target. Cargo structures the target directory in a
workspace like this because the crates in a workspace are meant to depend on
each other. If each crate had its own target directory, each crate would have
to recompile each of the other crates in the workspace to place the artifacts
in its own target directory. By sharing one target directory, the crates
can avoid unnecessary rebuilding.
工作区在顶层有一个目标目录,已编译的工件将被放置到其中; adder
包没有自己的目标目录。即使我们要从adder目录内部运行cargo build
,编译后的工件仍然会出现在add/target而不是add/adder/target中。 Cargo 像这样在工作区中构建目标目录,因为工作区中的 crate 意味着相互依赖。如果每个 crate 都有自己的目标目录,则每个 crate 都必须重新编译工作区中的其他每个 crate,以将工件放入其自己的目标目录中。通过共享一个目标目录,包可以避免不必要的重建。
Creating the Second Package in the Workspace
在工作区中创建第二个包
Next, let’s create another member package in the workspace and call it
add_one
. Change the top-level Cargo.toml to specify the add_one path in
the members
list:
接下来,我们在工作区中创建另一个成员包并将其命名为add_one
。更改顶级Cargo.toml以指定members
列表中的add_one路径:
Filename: Cargo.toml 文件名:Cargo.toml
[workspace]
members = [
"adder",
"add_one",
]
Then generate a new library crate named add_one
:
然后生成一个名为add_one
的新库箱:
$ cargo new add_one --lib
Created library `add_one` package
Your add directory should now have these directories and files:
您的添加目录现在应该包含以下目录和文件:
├── Cargo.lock
├── Cargo.toml
├── add_one
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
In the add_one/src/lib.rs file, let’s add an add_one
function:
在add_one/src/lib.rs文件中,我们添加一个add_one
函数:
Filename: add_one/src/lib.rs
文件名:add_one/src/lib.rs
pub fn add_one(x: i32) -> i32 {
x + 1
}
Now we can have the adder
package with our binary depend on the add_one
package that has our library. First, we’ll need to add a path dependency on
add_one
to adder/Cargo.toml.
现在我们可以让adder
包与我们的二进制文件依赖于具有我们的库的add_one
包。首先,我们需要将add_one
的路径依赖添加到adder/Cargo.toml 。
Filename: adder/Cargo.toml
文件名:adder/Cargo.toml
[dependencies]
add_one = { path = "../add_one" }
Cargo doesn’t assume that crates in a workspace will depend on each other, so
we need to be explicit about the dependency relationships.
Cargo 并不假设工作区中的 crate 会相互依赖,因此我们需要明确依赖关系。
Next, let’s use the add_one
function (from the add_one
crate) in the
adder
crate. Open the adder/src/main.rs file and add a use
line at the
top to bring the new add_one
library crate into scope. Then change the main
function to call the add_one
function, as in Listing 14-7.
接下来,让我们在adder
crate 中使用add_one
函数(来自add_one
crate)。打开adder/src/main.rs文件并在顶部添加use
行,将新的add_one
库箱纳入范围。然后更改main
函数以调用add_one
函数,如清单 14-7 所示。
Filename: adder/src/main.rs
文件名:adder/src/main.rs
use add_one;
fn main() {
let num = 10;
println!("Hello, world! {num} plus one is {}!", add_one::add_one(num));
}
Let’s build the workspace by running cargo build
in the top-level add
directory!
让我们通过在顶级添加目录中运行cargo build
来构建工作区!
$ 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
To run the binary crate from the add directory, we can specify which
package in the workspace we want to run by using the -p
argument and the
package name with cargo run
:
要从add目录运行二进制包,我们可以通过使用-p
参数和带有cargo run
包名称来指定要运行工作区中的哪个包:
$ cargo run -p adder
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/adder`
Hello, world! 10 plus one is 11!
This runs the code in adder/src/main.rs, which depends on the add_one
crate.
这将运行adder/src/main.rs中的代码,这取决于add_one
板条箱。
Depending on an External Package in a Workspace
依赖于工作区中的外部包
Notice that the workspace has only one Cargo.lock file at the top level,
rather than having a Cargo.lock in each crate’s directory. This ensures that
all crates are using the same version of all dependencies. If we add the rand
package to the adder/Cargo.toml and add_one/Cargo.toml files, Cargo will
resolve both of those to one version of rand
and record that in the one
Cargo.lock. Making all crates in the workspace use the same dependencies
means the crates will always be compatible with each other. Let’s add the
rand
crate to the [dependencies]
section in the add_one/Cargo.toml file
so we can use the rand
crate in the add_one
crate:
请注意,工作区在顶层只有一个Cargo.lock文件,而不是在每个 crate 的目录中都有一个Cargo.lock 文件。这可确保所有包都使用所有依赖项的相同版本。如果我们将rand
包添加到adder/Cargo.toml和add_one/Cargo.toml文件中,Cargo 会将这两个文件解析为一种版本的rand
并将其记录在一个Cargo.lock中。使工作区中的所有 crate 使用相同的依赖项意味着 crate 将始终相互兼容。让我们将rand
箱添加到add_one/Cargo.toml文件中的[dependencies]
部分,以便我们可以在add_one
箱中使用rand
箱:
Filename: add_one/Cargo.toml
文件名:add_one/Cargo.toml
[dependencies]
rand = "0.8.5"
We can now add use rand;
to the add_one/src/lib.rs file, and building the
whole workspace by running cargo build
in the add directory will bring in
and compile the rand
crate. We will get one warning because we aren’t
referring to the rand
we brought into scope:
我们现在可以添加use rand;
添加到add_one/src/lib.rs文件,并通过在add目录中运行cargo build
构建整个工作区,将引入并编译rand
箱。我们将收到一个警告,因为我们没有引用我们纳入范围的rand
:
$ 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`
--> 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
The top-level Cargo.lock now contains information about the dependency of
add_one
on rand
. However, even though rand
is used somewhere in the
workspace, we can’t use it in other crates in the workspace unless we add
rand
to their Cargo.toml files as well. For example, if we add use rand;
to the adder/src/main.rs file for the adder
package, we’ll get an error:
顶级Cargo.lock现在包含有关add_one
对rand
的依赖关系的信息。然而,即使rand
在工作区的某个地方使用,我们也不能在工作区的其他 crate 中使用它,除非我们也将rand
添加到它们的Cargo.toml文件中。例如,如果我们添加use rand;
添加到adder
包的adder/src/main.rs文件中,我们会得到一个错误:
$ cargo build
--snip--
Compiling adder v0.1.0 (file:///projects/add/adder)
error[E0432]: unresolved import `rand`
--> adder/src/main.rs:2:5
|
2 | use rand;
| ^^^^ no external crate `rand`
To fix this, edit the Cargo.toml file for the adder
package and indicate
that rand
is a dependency for it as well. Building the adder
package will
add rand
to the list of dependencies for adder
in Cargo.lock, but no
additional copies of rand
will be downloaded. Cargo will ensure that every
crate in every package in the workspace using the rand
package will be using
the same version as long as they specify compatible versions of rand
, saving
us space and ensuring that the crates in the workspace will be compatible with
each other.
要解决此问题,请编辑adder
包的Cargo.toml文件并指示rand
也是它的依赖项。构建adder
包会将rand
添加到Cargo.lock中adder
的依赖项列表中,但不会下载rand
的其他副本。 Cargo 将确保工作区中使用rand
包的每个包中的每个板条箱都将使用相同的版本,只要它们指定兼容版本的rand
即可,从而节省我们的空间并确保工作区中的板条箱彼此兼容。
If crates in the workspace specify incompatible versions of the same dependency,
Cargo will resolve each of them, but will still try to resolve as few versions
as possible.
如果工作区中的板条箱指定了同一依赖项的不兼容版本,Cargo 将解析每个版本,但仍会尝试解析尽可能少的版本。
Adding a Test to a Workspace
将测试添加到工作区
For another enhancement, let’s add a test of the add_one::add_one
function
within the add_one
crate:
对于另一个增强功能,让我们在add_one
箱中添加对add_one::add_one
函数的测试:
Filename: add_one/src/lib.rs
文件名:add_one/src/lib.rs
pub fn add_one(x: i32) -> i32 {
x + 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(3, add_one(2));
}
}
Now run cargo test
in the top-level add directory. Running cargo test
in
a workspace structured like this one will run the tests for all the crates in
the workspace:
现在在顶级添加目录中运行cargo test
。在像这样结构的工作区中运行cargo test
将为工作区中的所有板条箱运行测试:
$ 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
The first section of the output shows that the it_works
test in the add_one
crate passed. The next section shows that zero tests were found in the adder
crate, and then the last section shows zero documentation tests were found in
the add_one
crate.
输出的第一部分显示add_one
箱中的it_works
测试已通过。下一部分显示在adder
箱中找到零个测试,然后最后一部分显示在add_one
箱中找到零个文档测试。
We can also run tests for one particular crate in a workspace from the
top-level directory by using the -p
flag and specifying the name of the crate
we want to test:
我们还可以通过使用-p
标志并指定我们要测试的包的名称,从顶级目录中对工作区中的一个特定包运行测试:
$ 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
This output shows cargo test
only ran the tests for the add_one
crate and
didn’t run the adder
crate tests.
此输出显示cargo test
仅运行了add_one
箱的测试,而没有运行adder
箱的测试。
If you publish the crates in the workspace to crates.io,
each crate in the workspace will need to be published separately. Like cargo test
, we can publish a particular crate in our workspace by using the -p
flag and specifying the name of the crate we want to publish.
如果您将工作区中的 crate 发布到crates.io ,则工作区中的每个 crate 都需要单独发布。与cargo test
一样,我们可以通过使用-p
标志并指定我们要发布的包的名称来在工作区中发布特定的包。
For additional practice, add an add_two
crate to this workspace in a similar
way as the add_one
crate!
如需额外练习,请以与add_one
箱类似的方式将add_two
箱添加到此工作区!
As your project grows, consider using a workspace: it’s easier to understand
smaller, individual components than one big blob of code. Furthermore, keeping
the crates in a workspace can make coordination between crates easier if they
are often changed at the same time.
随着项目的增长,请考虑使用工作区:与一大堆代码相比,理解较小的单个组件更容易。此外,如果板条箱经常同时更改,则将板条箱保留在工作空间中可以使板条箱之间的协调变得更容易。
Installing Binaries with cargo install
使用cargo install
安装二进制文件
The cargo install
command allows you to install and use binary crates
locally. This isn’t intended to replace system packages; it’s meant to be a
convenient way for Rust developers to install tools that others have shared on
crates.io. Note that you can only install
packages that have binary targets. A binary target is the runnable program
that is created if the crate has a src/main.rs file or another file specified
as a binary, as opposed to a library target that isn’t runnable on its own but
is suitable for including within other programs. Usually, crates have
information in the README file about whether a crate is a library, has a
binary target, or both.cargo install
命令允许您在本地安装和使用二进制包。这并不是为了取代系统软件包;而是为了取代系统软件包。它旨在为 Rust 开发人员提供一种便捷的方式来安装其他人在crates.ioignore上共享的工具。请注意,您只能安装具有二进制目标的软件包。二进制目标是在包具有src/main.rs文件或指定为二进制的其他文件时创建的可运行程序,而不是单独运行但适合包含在其他文件中的库目标。程序。通常,包的README文件中包含有关包是否是库、是否具有二进制目标或两者的信息。
All binaries installed with cargo install
are stored in the installation
root’s bin folder. If you installed Rust using rustup.rs and don’t have any
custom configurations, this directory will be $HOME/.cargo/bin. Ensure that
directory is in your $PATH
to be able to run programs you’ve installed with
cargo install
.
使用cargo install
安装的所有二进制文件都存储在安装根目录的bin文件夹中。如果您使用rustup.rs安装了 Rust 并且没有任何自定义配置,则此目录将为$HOME/.cargo/bin 。确保该目录位于您的$PATH
中,以便能够运行您使用cargo install
安装的程序。
For example, in Chapter 12 we mentioned that there’s a Rust implementation of
the grep
tool called ripgrep
for searching files. To install ripgrep
, we
can run the following:
例如,在第 12 章中我们提到有一个名为ripgrep
的grep
工具的 Rust 实现,用于搜索文件。要安装ripgrep
,我们可以运行以下命令:
$ 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`)
The second-to-last line of the output shows the location and the name of the
installed binary, which in the case of ripgrep
is rg
. As long as the
installation directory is in your $PATH
, as mentioned previously, you can
then run rg --help
and start using a faster, rustier tool for searching files!
输出的倒数第二行显示已安装二进制文件的位置和名称,在ripgrep
的情况下为rg
。只要安装目录位于您的$PATH
中,如前所述,您就可以运行rg --help
并开始使用更快、更可靠的工具来搜索文件!
Extending Cargo with Custom Commands
使用自定义命令扩展 Cargo
Cargo is designed so you can extend it with new subcommands without having to
modify Cargo. If a binary in your $PATH
is named cargo-something
, you can
run it as if it was a Cargo subcommand by running cargo something
. Custom
commands like this are also listed when you run cargo --list
. Being able to
use cargo install
to install extensions and then run them just like the
built-in Cargo tools is a super convenient benefit of Cargo’s design!
Cargo 的设计使您可以使用新的子命令对其进行扩展,而无需修改 Cargo。如果$PATH
中的二进制文件名为cargo-something
,则可以通过运行cargo something
来运行它,就好像它是 Cargo 子命令一样。当您运行cargo --list
时,也会列出这样的自定义命令。能够使用cargo install
来安装扩展,然后像内置 Cargo 工具一样运行它们,这是 Cargo 设计的一个超级方便的好处!
Summary 概括
Sharing code with Cargo and crates.io is
part of what makes the Rust ecosystem useful for many different tasks. Rust’s
standard library is small and stable, but crates are easy to share, use, and
improve on a timeline different from that of the language. Don’t be shy about
sharing code that’s useful to you on crates.io; it’s likely that it will be useful to someone else as well!
与 Cargo 和crates.ioignore共享代码是 Rust 生态系统对许多不同任务有用的一部分。 Rust 的标准库小而稳定,但 crate 很容易在与该语言不同的时间线上共享、使用和改进。不要羞于在crates.ioignore上分享对你有用的代码;它很可能对其他人也有用!
Smart Pointers 智能指针
A pointer is a general concept for a variable that contains an address in
memory. This address refers to, or “points at,” some other data. The most
common kind of pointer in Rust is a reference, which you learned about in
Chapter 4. References are indicated by the &
symbol and borrow the value they
point to. They don’t have any special capabilities other than referring to
data, and have no overhead.
指针是包含内存地址的变量的一般概念。该地址引用或“指向”一些其他数据。 Rust 中最常见的指针类型是引用,您在第 4 章中了解过它。引用由&
符号表示,并借用它们指向的值。除了引用数据之外,它们没有任何特殊功能,并且没有开销。
Smart pointers, on the other hand, are data structures that act like a
pointer but also have additional metadata and capabilities. The concept of
smart pointers isn’t unique to Rust: smart pointers originated in C++ and exist
in other languages as well. Rust has a variety of smart pointers defined in the
standard library that provide functionality beyond that provided by references.
To explore the general concept, we’ll look at a couple of different examples of
smart pointers, including a reference counting smart pointer type. This
pointer enables you to allow data to have multiple owners by keeping track of
the number of owners and, when no owners remain, cleaning up the data.
另一方面,智能指针是一种类似于指针的数据结构,但还具有附加的元数据和功能。智能指针的概念并不是 Rust 独有的:智能指针起源于 C++,也存在于其他语言中。 Rust 在标准库中定义了各种智能指针,它们提供的功能超出了引用所提供的功能。为了探讨一般概念,我们将看几个不同的智能指针示例,包括引用计数智能指针类型。通过该指针,您可以通过跟踪所有者数量来允许数据拥有多个所有者,并在没有所有者剩余时清理数据。
Rust, with its concept of ownership and borrowing, has an additional difference
between references and smart pointers: while references only borrow data, in
many cases, smart pointers own the data they point to.
Rust 具有所有权和借用的概念,因此引用和智能指针之间还有一个额外的区别:虽然引用仅借用数据,但在许多情况下,智能指针拥有它们指向的数据。
Though we didn’t call them as such at the time, we’ve already encountered a few
smart pointers in this book, including String
and Vec<T>
in Chapter 8. Both
these types count as smart pointers because they own some memory and allow you
to manipulate it. They also have metadata and extra capabilities or guarantees.
String
, for example, stores its capacity as metadata and has the extra
ability to ensure its data will always be valid UTF-8.
虽然我们当时没有这样称呼它们,但我们已经在本书中遇到了一些智能指针,包括第 8 章中的String
和Vec<T>
这两种类型都算作智能指针,因为它们拥有一些内存并允许你操纵它。它们还具有元数据和额外的功能或保证。例如, String
将其容量存储为元数据,并具有额外的能力来确保其数据始终是有效的 UTF-8。
Smart pointers are usually implemented using structs. Unlike an ordinary
struct, smart pointers implement the Deref
and Drop
traits. The Deref
trait allows an instance of the smart pointer struct to behave like a reference
so you can write your code to work with either references or smart pointers.
The Drop
trait allows you to customize the code that’s run when an instance
of the smart pointer goes out of scope. In this chapter, we’ll discuss both
traits and demonstrate why they’re important to smart pointers.
智能指针通常使用结构体来实现。与普通结构不同,智能指针实现Deref
和Drop
特征。 Deref
特征允许智能指针结构体的实例表现得像引用,因此您可以编写代码以使用引用或智能指针。 Drop
特征允许您自定义智能指针实例超出范围时运行的代码。在本章中,我们将讨论这两个特征并演示为什么它们对智能指针很重要。
Given that the smart pointer pattern is a general design pattern used
frequently in Rust, this chapter won’t cover every existing smart pointer. Many
libraries have their own smart pointers, and you can even write your own. We’ll
cover the most common smart pointers in the standard library:
鉴于智能指针模式是 Rust 中经常使用的通用设计模式,本章不会涵盖所有现有的智能指针。许多库都有自己的智能指针,您甚至可以编写自己的智能指针。我们将介绍标准库中最常见的智能指针:
Box<T>
for allocating values on the heapBox<T>
用于在堆上分配值Rc<T>
, a reference counting type that enables multiple ownershipRc<T>
,一种支持多重所有权的引用计数类型Ref<T>
andRefMut<T>
, accessed throughRefCell<T>
, a type that enforces the borrowing rules at runtime instead of compile timeRef<T>
和RefMut<T>
,通过RefCell<T>
访问,这是一种在运行时而不是编译时强制执行借用规则的类型
In addition, we’ll cover the interior mutability pattern where an immutable
type exposes an API for mutating an interior value. We’ll also discuss
reference cycles: how they can leak memory and how to prevent them.
此外,我们还将介绍内部可变性模式,其中不可变类型公开用于改变内部值的 API。我们还将讨论引用循环:它们如何泄漏内存以及如何防止它们。
Let’s dive in! 让我们深入了解吧!
Using Box<T>
to Point to Data on the Heap
使用Box<T>
指向堆上的数据
The most straightforward smart pointer is a box, whose type is written
Box<T>
. Boxes allow you to store data on the heap rather than the stack. What
remains on the stack is the pointer to the heap data. Refer to Chapter 4 to
review the difference between the stack and the heap.
最直接的智能指针是一个box ,其类型写为Box<T>
。盒子允许您将数据存储在堆上而不是堆栈上。保留在堆栈上的是指向堆数据的指针。参考第4章回顾栈和堆的区别。
Boxes don’t have performance overhead, other than storing their data on the
heap instead of on the stack. But they don’t have many extra capabilities
either. You’ll use them most often in these situations:
除了将数据存储在堆而不是堆栈上之外,盒子没有性能开销。但他们也没有太多额外的能力。在这些情况下您最常使用它们:
- When you have a type whose size can’t be known at compile time and you want
to use a value of that type in a context that requires an exact size
当您的类型在编译时无法知道其大小并且您希望在需要精确大小的上下文中使用该类型的值时 - When you have a large amount of data and you want to transfer ownership but
ensure the data won’t be copied when you do so
当您拥有大量数据并且想要转移所有权但要确保这样做时数据不会被复制 - When you want to own a value and you care only that it’s a type that
implements a particular trait rather than being of a specific type
当您想拥有一个值并且只关心它是实现特定特征的类型而不是特定类型时
We’ll demonstrate the first situation in the “Enabling Recursive Types with
Boxes” section. In the
second case, transferring ownership of a large amount of data can take a long
time because the data is copied around on the stack. To improve performance in
this situation, we can store the large amount of data on the heap in a box.
Then, only the small amount of pointer data is copied around on the stack,
while the data it references stays in one place on the heap. The third case is
known as a trait object, and Chapter 17 devotes an entire section, “Using
Trait Objects That Allow for Values of Different Types,” just to that topic. So what you learn here you’ll apply again in
Chapter 17!
我们将在“使用框启用递归类型”忽略部分演示第一种情况。在第二种情况下,转移大量数据的所有权可能需要很长时间,因为数据是在堆栈上复制的。为了提高这种情况下的性能,我们可以将堆上的大量数据存储在一个盒子中。然后,只有少量的指针数据在堆栈上复制,而它引用的数据保留在堆上的一个位置。第三种情况称为特征对象,第 17 章用了整整一节“使用允许不同类型值的特征对象”,忽略该主题。所以你在这里学到的东西将在第 17 章中再次应用!
Using a Box<T>
to Store Data on the Heap
使用Box<T>
在堆上存储数据
Before we discuss the heap storage use case for Box<T>
, we’ll cover the
syntax and how to interact with values stored within a Box<T>
.
在讨论Box<T>
的堆存储用例之前,我们将介绍语法以及如何与Box<T>
中存储的值进行交互。
Listing 15-1 shows how to use a box to store an i32
value on the heap:
清单 15-1 展示了如何使用 box 在堆上存储i32
值:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let b = Box::new(5);
println!("b = {b}");
}
We define the variable b
to have the value of a Box
that points to the
value 5
, which is allocated on the heap. This program will print b = 5
; in
this case, we can access the data in the box similar to how we would if this
data were on the stack. Just like any owned value, when a box goes out of
scope, as b
does at the end of main
, it will be deallocated. The
deallocation happens both for the box (stored on the stack) and the data it
points to (stored on the heap).
我们将变量b
定义为具有指向值5
的Box
的值,该值分配在堆上。该程序将打印b = 5
;在这种情况下,我们可以访问框中的数据,就像这些数据位于堆栈上一样。就像任何拥有的值一样,当一个盒子超出范围时,就像b
在main
末尾所做的那样,它将被释放。释放对于盒子(存储在堆栈上)和它指向的数据(存储在堆上)都会发生。
Putting a single value on the heap isn’t very useful, so you won’t use boxes by
themselves in this way very often. Having values like a single i32
on the
stack, where they’re stored by default, is more appropriate in the majority of
situations. Let’s look at a case where boxes allow us to define types that we
wouldn’t be allowed to if we didn’t have boxes.
将单个值放在堆上并不是很有用,因此您不会经常以这种方式使用框本身。在大多数情况下,将像单个i32
这样的值默认存储在堆栈上更合适。让我们看一个例子,盒子允许我们定义类型,如果没有盒子,我们就不能定义类型。
Enabling Recursive Types with Boxes
使用框启用递归类型
A value of recursive type can have another value of the same type as part of
itself. Recursive types pose an issue because at compile time Rust needs to
know how much space a type takes up. However, the nesting of values of
recursive types could theoretically continue infinitely, so Rust can’t know how
much space the value needs. Because boxes have a known size, we can enable
recursive types by inserting a box in the recursive type definition.
递归类型的值可以有另一个相同类型的值作为其自身的一部分。递归类型会带来一个问题,因为在编译时 Rust 需要知道类型占用了多少空间。然而,递归类型的值的嵌套理论上可以无限继续,因此 Rust 无法知道该值需要多少空间。由于框的大小已知,因此我们可以通过在递归类型定义中插入框来启用递归类型。
As an example of a recursive type, let’s explore the cons list. This is a data
type commonly found in functional programming languages. The cons list type
we’ll define is straightforward except for the recursion; therefore, the
concepts in the example we’ll work with will be useful any time you get into
more complex situations involving recursive types.
作为递归类型的示例,让我们探讨一下cons list 。这是函数式编程语言中常见的数据类型。除了递归之外,我们将定义的 cons 列表类型很简单;因此,每当您遇到涉及递归类型的更复杂的情况时,我们将使用的示例中的概念都会很有用。
More Information About the Cons List
有关缺点列表的更多信息
A cons list is a data structure that comes from the Lisp programming language
and its dialects and is made up of nested pairs, and is the Lisp version of a
linked list. Its name comes from the cons
function (short for “construct
function”) in Lisp that constructs a new pair from its two arguments. By
calling cons
on a pair consisting of a value and another pair, we can
construct cons lists made up of recursive pairs.
cons 列表是一种来自 Lisp 编程语言及其方言的数据结构,由嵌套对组成,是链表的 Lisp 版本。它的名字来自 Lisp 中的cons
函数(“构造函数”的缩写),该函数根据两个参数构造一个新的对。通过在由一个值和另一对组成的对上调用cons
,我们可以构造由递归对组成的 cons 列表。
For example, here’s a pseudocode representation of a cons list containing the
list 1, 2, 3 with each pair in parentheses:
例如,下面是 cons 列表的伪代码表示,其中包含列表 1、2、3,每对都放在括号中:
(1, (2, (3, Nil)))
Each item in a cons list contains two elements: the value of the current item
and the next item. The last item in the list contains only a value called Nil
without a next item. A cons list is produced by recursively calling the cons
function. The canonical name to denote the base case of the recursion is Nil
.
Note that this is not the same as the “null” or “nil” concept in Chapter 6,
which is an invalid or absent value.
cons 列表中的每个项目都包含两个元素:当前项目的值和下一个项目的值。列表中的最后一项仅包含一个名为Nil
的值,没有下一项。 cons 列表是通过递归调用cons
函数生成的。表示递归基本情况的规范名称是Nil
。请注意,这与第 6 章中的“null”或“nil”概念不同,后者是无效或不存在的值。
The cons list isn’t a commonly used data structure in Rust. Most of the time
when you have a list of items in Rust, Vec<T>
is a better choice to use.
Other, more complex recursive data types are useful in various situations,
but by starting with the cons list in this chapter, we can explore how boxes
let us define a recursive data type without much distraction.
cons 列表不是 Rust 中常用的数据结构。大多数时候,当您有 Rust 中的项目列表时, Vec<T>
是更好的选择。其他更复杂的递归数据类型在各种情况下都很有用,但是从本章中的缺点列表开始,我们可以探索框如何让我们定义递归数据类型而不会造成太多干扰。
Listing 15-2 contains an enum definition for a cons list. Note that this code
won’t compile yet because the List
type doesn’t have a known size, which
we’ll demonstrate.
清单 15-2 包含 cons 列表的枚举定义。请注意,此代码尚未编译,因为List
类型没有已知的大小,我们将对此进行演示。
Filename: src/main.rs 文件名:src/main.rs
Note: We’re implementing a cons list that holds only i32
values for the
purposes of this example. We could have implemented it using generics, as we
discussed in Chapter 10, to define a cons list type that could store values of
any type.
注意:出于本示例的目的,我们正在实现一个仅包含i32
值的 cons 列表。我们可以使用泛型来实现它,正如我们在第 10 章中讨论的那样,定义一个可以存储任何类型值的 cons 列表类型。
Using the List
type to store the list 1, 2, 3
would look like the code in
Listing 15-3:
使用List
类型存储列表1, 2, 3
代码如清单 15-3 所示:
Filename: src/main.rs 文件名:src/main.rs
The first Cons
value holds 1
and another List
value. This List
value is
another Cons
value that holds 2
and another List
value. This List
value
is one more Cons
value that holds 3
and a List
value, which is finally
Nil
, the non-recursive variant that signals the end of the list.
第一个Cons
值包含1
和另一个List
值。该List
值是另一个包含2
和另一个List
值的Cons
值。这个List
值又是一个包含3
Cons
值和一个List
值,最后是Nil
,这是一种表示列表结束的非递归变体。
If we try to compile the code in Listing 15-3, we get the error shown in
Listing 15-4:
如果我们尝试编译清单 15-3 中的代码,我们会得到清单 15-4 中所示的错误:
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0072]: recursive type `List` has infinite size
--> 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 `&`) to break the cycle
|
2 | Cons(i32, Box<List>),
| ++++ +
error[E0391]: cycle detected when computing when `List` needs drop
--> 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
The error shows this type “has infinite size.” The reason is that we’ve defined
List
with a variant that is recursive: it holds another value of itself
directly. As a result, Rust can’t figure out how much space it needs to store a
List
value. Let’s break down why we get this error. First, we’ll look at how
Rust decides how much space it needs to store a value of a non-recursive type.
该错误表明该类型“具有无限大小”。原因是我们用递归的变体定义了List
:它直接保存自身的另一个值。因此,Rust 无法计算出存储List
值需要多少空间。让我们来分析一下为什么会出现这个错误。首先,我们将了解 Rust 如何决定存储非递归类型的值需要多少空间。
Computing the Size of a Non-Recursive Type
计算非递归类型的大小
Recall the Message
enum we defined in Listing 6-2 when we discussed enum
definitions in Chapter 6:
回想一下我们在第 6 章中讨论枚举定义时在清单 6-2 中定义的Message
枚举:
To determine how much space to allocate for a Message
value, Rust goes
through each of the variants to see which variant needs the most space. Rust
sees that Message::Quit
doesn’t need any space, Message::Move
needs enough
space to store two i32
values, and so forth. Because only one variant will be
used, the most space a Message
value will need is the space it would take to
store the largest of its variants.
为了确定为Message
值分配多少空间,Rust 会遍历每个变体以查看哪个变体需要最多空间。 Rust 认为Message::Quit
不需要任何空间, Message::Move
需要足够的空间来存储两个i32
值,依此类推。由于仅使用一种变体,因此Message
值所需的最大空间就是存储其最大变体所需的空间。
Contrast this with what happens when Rust tries to determine how much space a
recursive type like the List
enum in Listing 15-2 needs. The compiler starts
by looking at the Cons
variant, which holds a value of type i32
and a value
of type List
. Therefore, Cons
needs an amount of space equal to the size of
an i32
plus the size of a List
. To figure out how much memory the List
type needs, the compiler looks at the variants, starting with the Cons
variant. The Cons
variant holds a value of type i32
and a value of type
List
, and this process continues infinitely, as shown in Figure 15-1.
将此与 Rust 尝试确定递归类型(如清单 15-2 中的List
枚举)需要多少空间时发生的情况进行对比。编译器首先查看Cons
变体,它包含一个i32
类型的值和一个List
类型的值。因此, Cons
需要的空间量等于i32
的大小加上List
的大小。为了弄清楚List
类型需要多少内存,编译器会从Cons
变体开始查看变体。 Cons
变量保存一个i32
类型的值和一个List
类型的值,并且这个过程无限地继续下去,如图 15-1 所示。
Using Box<T>
to Get a Recursive Type with a Known Size
使用Box<T>
获取具有已知大小的递归类型
Because Rust can’t figure out how much space to allocate for recursively
defined types, the compiler gives an error with this helpful suggestion:
因为 Rust 无法计算出要为递归定义的类型分配多少空间,所以编译器会给出一个错误并给出以下有用的建议:
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
|
2 | Cons(i32, Box<List>),
| ++++ +
In this suggestion, “indirection” means that instead of storing a value
directly, we should change the data structure to store the value indirectly by
storing a pointer to the value instead.
在这个建议中,“间接”意味着我们不应该直接存储值,而是应该改变数据结构,通过存储指向该值的指针来间接存储该值。
Because a Box<T>
is a pointer, Rust always knows how much space a Box<T>
needs: a pointer’s size doesn’t change based on the amount of data it’s
pointing to. This means we can put a Box<T>
inside the Cons
variant instead
of another List
value directly. The Box<T>
will point to the next List
value that will be on the heap rather than inside the Cons
variant.
Conceptually, we still have a list, created with lists holding other lists, but
this implementation is now more like placing the items next to one another
rather than inside one another.
因为Box<T>
是一个指针,Rust 总是知道Box<T>
需要多少空间:指针的大小不会根据它指向的数据量而改变。这意味着我们可以将Box<T>
放入Cons
变量中,而不是直接将另一个List
值放入其中。 Box<T>
将指向堆上而不是Cons
变量内部的下一个List
值。从概念上讲,我们仍然有一个列表,是用包含其他列表的列表创建的,但这种实现现在更像是将项目彼此相邻放置,而不是彼此放在一起。
We can change the definition of the List
enum in Listing 15-2 and the usage
of the List
in Listing 15-3 to the code in Listing 15-5, which will compile:
我们可以将清单 15-2 中List
枚举的定义和清单 15-3 中List
的用法更改为清单 15-5 中的代码,它将编译:
Filename: src/main.rs 文件名:src/main.rs
enum List {
Cons(i32, Box<List>),
Nil,
}
use crate::List::{Cons, Nil};
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
}
The Cons
variant needs the size of an i32
plus the space to store the
box’s pointer data. The Nil
variant stores no values, so it needs less space
than the Cons
variant. We now know that any List
value will take up the
size of an i32
plus the size of a box’s pointer data. By using a box, we’ve
broken the infinite, recursive chain, so the compiler can figure out the size
it needs to store a List
value. Figure 15-2 shows what the Cons
variant
looks like now.Cons
变体需要i32
的大小加上存储框指针数据的空间。 Nil
变体不存储任何值,因此它比Cons
变体需要更少的空间。我们现在知道任何List
值都会占用i32
的大小加上框指针数据的大小。通过使用盒子,我们打破了无限的递归链,因此编译器可以计算出存储List
值所需的大小。图 15-2 显示了Cons
变体现在的样子。
Boxes provide only the indirection and heap allocation; they don’t have any
other special capabilities, like those we’ll see with the other smart pointer
types. They also don’t have the performance overhead that these special
capabilities incur, so they can be useful in cases like the cons list where the
indirection is the only feature we need. We’ll look at more use cases for boxes
in Chapter 17, too.
盒子仅提供间接和堆分配;它们没有任何其他特殊功能,就像我们将在其他智能指针类型中看到的那样。它们也没有这些特殊功能所产生的性能开销,因此它们在像 cons 列表这样的情况下非常有用,其中间接是我们唯一需要的功能。我们还将在第 17 章中讨论更多盒子的用例。
The Box<T>
type is a smart pointer because it implements the Deref
trait,
which allows Box<T>
values to be treated like references. When a Box<T>
value goes out of scope, the heap data that the box is pointing to is cleaned
up as well because of the Drop
trait implementation. These two traits will be
even more important to the functionality provided by the other smart pointer
types we’ll discuss in the rest of this chapter. Let’s explore these two traits
in more detail.Box<T>
类型是智能指针,因为它实现了Deref
特征,该特征允许将Box<T>
值视为引用。当Box<T>
值超出范围时,由于Drop
特征实现,该框指向的堆数据也会被清除。这两个特征对于我们将在本章其余部分讨论的其他智能指针类型提供的功能甚至更为重要。让我们更详细地探讨这两个特征。
Treating Smart Pointers Like Regular References with the Deref
Trait
使用Deref
Trait 将智能指针视为常规引用
Implementing the Deref
trait allows you to customize the behavior of the
dereference operator *
(not to be confused with the multiplication or glob
operator). By implementing Deref
in such a way that a smart pointer can be
treated like a regular reference, you can write code that operates on
references and use that code with smart pointers too.
实现Deref
特征允许您自定义取消引用运算符*
的行为(不要与乘法或 glob 运算符混淆)。通过以智能指针被视为常规引用的方式实现Deref
,您可以编写对引用进行操作的代码,并将该代码与智能指针一起使用。
Let’s first look at how the dereference operator works with regular references.
Then we’ll try to define a custom type that behaves like Box<T>
, and see why
the dereference operator doesn’t work like a reference on our newly defined
type. We’ll explore how implementing the Deref
trait makes it possible for
smart pointers to work in ways similar to references. Then we’ll look at
Rust’s deref coercion feature and how it lets us work with either references
or smart pointers.
让我们首先看看取消引用运算符如何与常规引用一起使用。然后,我们将尝试定义一个行为类似于Box<T>
自定义类型,并了解为什么取消引用运算符不像我们新定义的类型的引用那样工作。我们将探讨如何实现Deref
特征使智能指针能够以类似于引用的方式工作。然后我们将了解 Rust 的deref 强制转换功能以及它如何让我们使用引用或智能指针。
Note: There’s one big difference between the MyBox<T>
type we’re about to
build and the real Box<T>
: our version will not store its data on the heap.
We are focusing this example on Deref
, so where the data is actually stored
is less important than the pointer-like behavior.
注意:我们要构建的MyBox<T>
类型和真正的Box<T>
之间有一个很大的区别:我们的版本不会将其数据存储在堆上。我们将这个示例的重点放在Deref
上,因此数据的实际存储位置不如类似指针的行为重要。
Following the Pointer to the Value
跟随指向值的指针
A regular reference is a type of pointer, and one way to think of a pointer is
as an arrow to a value stored somewhere else. In Listing 15-6, we create a
reference to an i32
value and then use the dereference operator to follow the
reference to the value:
常规引用是一种指针,将指针视为指向存储在其他位置的值的箭头。在清单 15-6 中,我们创建了对i32
值的引用,然后使用取消引用运算符来跟踪对该值的引用:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = 5;
let y = &x;
assert_eq!(5, x);
assert_eq!(5, *y);
}
The variable x
holds an i32
value 5
. We set y
equal to a reference to
x
. We can assert that x
is equal to 5
. However, if we want to make an
assertion about the value in y
, we have to use *y
to follow the reference
to the value it’s pointing to (hence dereference) so the compiler can compare
the actual value. Once we dereference y
, we have access to the integer value
y
is pointing to that we can compare with 5
.
变量x
保存i32
值5
。我们将y
设置为等于对x
的引用。我们可以断言x
等于5
。但是,如果我们想对y
中的值进行断言,则必须使用*y
来跟踪对其所指向的值的引用(因此取消引用),以便编译器可以比较实际值。一旦我们取消引用y
,我们就可以访问y
指向的整数值,我们可以将其与5
进行比较。
If we tried to write assert_eq!(5, y);
instead, we would get this compilation
error:
如果我们尝试编写assert_eq!(5, y);
相反,我们会得到这个编译错误:
$ cargo run
Compiling deref-example v0.1.0 (file:///projects/deref-example)
error[E0277]: can't compare `{integer}` with `&{integer}`
--> src/main.rs:6:5
|
6 | assert_eq!(5, y);
| ^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`
|
= help: the trait `PartialEq<&{integer}>` 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
Comparing a number and a reference to a number isn’t allowed because they’re
different types. We must use the dereference operator to follow the reference
to the value it’s pointing to.
不允许比较数字和对数字的引用,因为它们是不同的类型。我们必须使用解引用运算符来跟踪对其所指向的值的引用。
Using Box<T>
Like a Reference
像引用一样使用Box<T>
We can rewrite the code in Listing 15-6 to use a Box<T>
instead of a
reference; the dereference operator used on the Box<T>
in Listing 15-7
functions in the same way as the dereference operator used on the reference in
Listing 15-6:
我们可以重写清单 15-6 中的代码以使用Box<T>
而不是引用;清单 15-7 中Box<T>
上使用的解引用运算符的功能与清单 15-6 中引用上使用的解引用运算符的功能相同:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = 5;
let y = Box::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);
}
The main difference between Listing 15-7 and Listing 15-6 is that here we set
y
to be an instance of a Box<T>
pointing to a copied value of x
rather
than a reference pointing to the value of x
. In the last assertion, we can
use the dereference operator to follow the pointer of the Box<T>
in the same
way that we did when y
was a reference. Next, we’ll explore what is special
about Box<T>
that enables us to use the dereference operator by defining our
own type.
清单 15-7 和清单 15-6 之间的主要区别在于,这里我们将y
设置为Box<T>
的实例,指向x
的复制值,而不是指向x
值的引用。在最后一个断言中,我们可以使用取消引用运算符来跟踪Box<T>
的指针,就像y
是引用时所做的那样。接下来,我们将探讨Box<T>
的特殊之处,它使我们能够通过定义自己的类型来使用取消引用运算符。
Defining Our Own Smart Pointer
定义我们自己的智能指针
Let’s build a smart pointer similar to the Box<T>
type provided by the
standard library to experience how smart pointers behave differently from
references by default. Then we’ll look at how to add the ability to use the
dereference operator.
让我们构建一个类似于标准库提供的Box<T>
类型的智能指针,来体验智能指针默认情况下与引用的行为有何不同。然后我们将了解如何添加使用取消引用运算符的功能。
The Box<T>
type is ultimately defined as a tuple struct with one element, so
Listing 15-8 defines a MyBox<T>
type in the same way. We’ll also define a
new
function to match the new
function defined on Box<T>
.Box<T>
类型最终被定义为具有一个元素的元组结构,因此清单 15-8 以相同的方式定义了MyBox<T>
类型。我们还将定义一个new
函数来匹配Box<T>
上定义的new
函数。
Filename: src/main.rs 文件名:src/main.rs
We define a struct named MyBox
and declare a generic parameter T
, because
we want our type to hold values of any type. The MyBox
type is a tuple struct
with one element of type T
. The MyBox::new
function takes one parameter of
type T
and returns a MyBox
instance that holds the value passed in.
我们定义一个名为MyBox
结构体并声明一个泛型参数T
,因为我们希望我们的类型能够保存任何类型的值。 MyBox
类型是一种元组结构,其中一个元素的类型为T
。 MyBox::new
函数采用一个类型为T
的参数,并返回一个保存传入值的MyBox
实例。
Let’s try adding the main
function in Listing 15-7 to Listing 15-8 and
changing it to use the MyBox<T>
type we’ve defined instead of Box<T>
. The
code in Listing 15-9 won’t compile because Rust doesn’t know how to dereference
MyBox
.
让我们尝试将清单 15-7 中的main
函数添加到清单 15-8 中,并将其更改为使用我们定义的MyBox<T>
类型,而不是Box<T>
。清单 15-9 中的代码无法编译,因为 Rust 不知道如何取消引用MyBox
。
Filename: src/main.rs 文件名:src/main.rs
Here’s the resulting compilation error:
这是产生的编译错误:
$ cargo run
Compiling deref-example v0.1.0 (file:///projects/deref-example)
error[E0614]: type `MyBox<{integer}>` cannot be dereferenced
--> 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
Our MyBox<T>
type can’t be dereferenced because we haven’t implemented that
ability on our type. To enable dereferencing with the *
operator, we
implement the Deref
trait.
我们的MyBox<T>
类型无法取消引用,因为我们尚未在我们的类型上实现该功能。为了使用*
运算符取消引用,我们实现了Deref
特征。
Treating a Type Like a Reference by Implementing the Deref
Trait
通过实现Deref
Trait 将类型视为引用
As discussed in the “Implementing a Trait on a Type” section of Chapter 10, to implement a trait, we need to provide
implementations for the trait’s required methods. The Deref
trait, provided
by the standard library, requires us to implement one method named deref
that
borrows self
and returns a reference to the inner data. Listing 15-10
contains an implementation of Deref
to add to the definition of MyBox
:
正如第 10 章“在类型上实现 Trait”忽略部分所讨论的,为了实现 Trait,我们需要为 Trait 所需的方法提供实现。标准库提供的Deref
特征要求我们实现一种名为deref
的方法,该方法借用self
并返回对内部数据的引用。清单 15-10 包含添加到MyBox
定义中的Deref
实现:
Filename: src/main.rs 文件名:src/main.rs
The type Target = T;
syntax defines an associated type for the Deref
trait to use. Associated types are a slightly different way of declaring a
generic parameter, but you don’t need to worry about them for now; we’ll cover
them in more detail in Chapter 19.type Target = T;
语法定义了要使用的Deref
特征的关联类型。关联类型是声明泛型参数的一种稍微不同的方式,但您现在不需要担心它们;我们将在第 19 章中更详细地介绍它们。
We fill in the body of the deref
method with &self.0
so deref
returns a
reference to the value we want to access with the *
operator; recall from the
“Using Tuple Structs without Named Fields to Create Different
Types” section of Chapter 5 that .0
accesses
the first value in a tuple struct. The main
function in Listing 15-9 that
calls *
on the MyBox<T>
value now compiles, and the assertions pass!
我们用&self.0
填充deref
方法的主体,因此deref
返回我们想要使用*
运算符访问的值的引用;回想一下第 5 章的“使用不带命名字段的元组结构创建不同类型”忽略部分, .0
访问元组结构中的第一个值。清单 15-9 中对MyBox<T>
值调用*
的main
函数现在可以编译,并且断言通过!
Without the Deref
trait, the compiler can only dereference &
references.
The deref
method gives the compiler the ability to take a value of any type
that implements Deref
and call the deref
method to get a &
reference that
it knows how to dereference.
如果没有Deref
特征,编译器只能取消引用&
引用。 deref
方法使编译器能够获取实现Deref
的任何类型的值,并调用deref
方法来获取它知道如何取消引用的&
引用。
When we entered *y
in Listing 15-9, behind the scenes Rust actually ran this
code:
当我们在清单 15-9 中输入*y
时,Rust 在幕后实际上运行了以下代码:
*(y.deref())
Rust substitutes the *
operator with a call to the deref
method and then a
plain dereference so we don’t have to think about whether or not we need to
call the deref
method. This Rust feature lets us write code that functions
identically whether we have a regular reference or a type that implements
Deref
.
Rust 将*
运算符替换为调用deref
方法,然后进行简单的取消引用,因此我们不必考虑是否需要调用deref
方法。这个 Rust 功能让我们可以编写功能相同的代码,无论我们有常规引用还是实现Deref
的类型。
The reason the deref
method returns a reference to a value, and that the
plain dereference outside the parentheses in *(y.deref())
is still necessary,
is to do with the ownership system. If the deref
method returned the value
directly instead of a reference to the value, the value would be moved out of
self
. We don’t want to take ownership of the inner value inside MyBox<T>
in
this case or in most cases where we use the dereference operator.deref
方法返回对值的引用,并且*(y.deref())
中括号外的普通取消引用仍然是必要的,这与所有权系统有关。如果deref
方法直接返回值而不是对该值的引用,则该值将被移出self
。在这种情况下或在我们使用解引用运算符的大多数情况下,我们不想取得MyBox<T>
内部值的所有权。
Note that the *
operator is replaced with a call to the deref
method and
then a call to the *
operator just once, each time we use a *
in our code.
Because the substitution of the *
operator does not recurse infinitely, we
end up with data of type i32
, which matches the 5
in assert_eq!
in
Listing 15-9.
请注意,每次我们在代码中使用*
时, *
运算符都会替换为对deref
方法的调用,然后仅调用一次*
运算符。因为*
运算符的替换不会无限递归,所以我们最终得到i32
类型的数据,它与assert_eq!
中的5
匹配!如清单 15-9 所示。
Implicit Deref Coercions with Functions and Methods
使用函数和方法进行隐式 Deref 强制转换
Deref coercion converts a reference to a type that implements the Deref
trait into a reference to another type. For example, deref coercion can convert
&String
to &str
because String
implements the Deref
trait such that it
returns &str
. Deref coercion is a convenience Rust performs on arguments to
functions and methods, and works only on types that implement the Deref
trait. It happens automatically when we pass a reference to a particular type’s
value as an argument to a function or method that doesn’t match the parameter
type in the function or method definition. A sequence of calls to the deref
method converts the type we provided into the type the parameter needs.
Deref 强制将对实现Deref
特征的类型的引用转换为对另一种类型的引用。例如, deref 强制转换可以将&String
转换为&str
因为String
实现了Deref
特征,因此它返回&str
。 Deref 强制是 Rust 对函数和方法的参数执行的一种便利方法,并且仅适用于实现Deref
特征的类型。当我们将对特定类型值的引用作为参数传递给与函数或方法定义中的参数类型不匹配的函数或方法时,它会自动发生。对deref
方法的一系列调用会将我们提供的类型转换为参数所需的类型。
Deref coercion was added to Rust so that programmers writing function and
method calls don’t need to add as many explicit references and dereferences
with &
and *
. The deref coercion feature also lets us write more code that
can work for either references or smart pointers.
Rust 中添加了 Deref 强制,以便编写函数和方法调用的程序员不需要使用&
和*
添加尽可能多的显式引用和取消引用。 deref 强制转换功能还允许我们编写更多可用于引用或智能指针的代码。
To see deref coercion in action, let’s use the MyBox<T>
type we defined in
Listing 15-8 as well as the implementation of Deref
that we added in Listing
15-10. Listing 15-11 shows the definition of a function that has a string slice
parameter:
要查看 deref 强制转换的实际效果,让我们使用清单 15-8 中定义的MyBox<T>
类型以及清单 15-10 中添加的Deref
实现。清单 15-11 显示了具有字符串切片参数的函数的定义:
Filename: src/main.rs 文件名:src/main.rs
We can call the hello
function with a string slice as an argument, such as
hello("Rust");
for example. Deref coercion makes it possible to call hello
with a reference to a value of type MyBox<String>
, as shown in Listing 15-12:
我们可以使用字符串切片作为参数来调用hello
函数,例如hello("Rust");
例如。 Deref 强制使得可以通过引用MyBox<String>
类型的值来调用hello
,如清单 15-12 所示:
Filename: src/main.rs 文件名:src/main.rs
Here we’re calling the hello
function with the argument &m
, which is a
reference to a MyBox<String>
value. Because we implemented the Deref
trait
on MyBox<T>
in Listing 15-10, Rust can turn &MyBox<String>
into &String
by calling deref
. The standard library provides an implementation of Deref
on String
that returns a string slice, and this is in the API documentation
for Deref
. Rust calls deref
again to turn the &String
into &str
, which
matches the hello
function’s definition.
这里我们使用参数&m
调用hello
函数,它是对MyBox<String>
值的引用。因为我们在清单 15-10 中的MyBox<T>
上实现了Deref
特征,所以 Rust 可以通过调用deref
将&MyBox<String>
转换为&String
。标准库提供了Deref
on String
的实现,它返回字符串切片,这位于Deref
的 API 文档中。 Rust 再次调用deref
将&String
转换为&str
,它与hello
函数的定义匹配。
If Rust didn’t implement deref coercion, we would have to write the code in
Listing 15-13 instead of the code in Listing 15-12 to call hello
with a value
of type &MyBox<String>
.
如果 Rust 没有实现 deref 强制转换,我们就必须编写清单 15-13 中的代码而不是清单 15-12 中的代码来使用&MyBox<String>
类型的值调用hello
。
Filename: src/main.rs 文件名:src/main.rs
The (*m)
dereferences the MyBox<String>
into a String
. Then the &
and
[..]
take a string slice of the String
that is equal to the whole string to
match the signature of hello
. This code without deref coercions is harder to
read, write, and understand with all of these symbols involved. Deref coercion
allows Rust to handle these conversions for us automatically.(*m)
将MyBox<String>
取消引用为String
。然后&
和[..]
获取String
的字符串切片,该切片等于整个字符串以匹配hello
的签名。由于涉及所有这些符号,没有解引用强制的代码更难以阅读、编写和理解。 Deref 强制允许 Rust 自动为我们处理这些转换。
When the Deref
trait is defined for the types involved, Rust will analyze the
types and use Deref::deref
as many times as necessary to get a reference to
match the parameter’s type. The number of times that Deref::deref
needs to be
inserted is resolved at compile time, so there is no runtime penalty for taking
advantage of deref coercion!
当为涉及的类型定义Deref
特征时,Rust 将分析类型并根据需要多次使用Deref::deref
来获取与参数类型匹配的引用。 Deref::deref
需要插入的次数在编译时确定,因此利用 deref 强制不会产生运行时损失!
How Deref Coercion Interacts with Mutability
Deref 强制如何与可变性相互作用
Similar to how you use the Deref
trait to override the *
operator on
immutable references, you can use the DerefMut
trait to override the *
operator on mutable references.
与使用Deref
特征覆盖不可变引用上的*
运算符类似,您可以使用DerefMut
特征覆盖可变引用上的*
运算符。
Rust does deref coercion when it finds types and trait implementations in three
cases:
Rust 在三种情况下找到类型和特征实现时会进行 deref 强制转换:
- From
&T
to&U
whenT: Deref<Target=U>
当 T 时从&T
到&U
T: Deref<Target=U>
- From
&mut T
to&mut U
whenT: DerefMut<Target=U>
当 T 时从&mut T
到&mut U
T: DerefMut<Target=U>
- From
&mut T
to&U
whenT: Deref<Target=U>
当 T 时从&mut T
到&U
T: Deref<Target=U>
The first two cases are the same as each other except that the second
implements mutability. The first case states that if you have a &T
, and T
implements Deref
to some type U
, you can get a &U
transparently. The
second case states that the same deref coercion happens for mutable references.
前两种情况彼此相同,只是第二种情况实现了可变性。第一种情况表明,如果您有一个&T
,并且T
实现了对某种类型U
Deref
,您可以透明地获得&U
。第二种情况表明,可变引用也会发生相同的 deref 强制转换。
The third case is trickier: Rust will also coerce a mutable reference to an
immutable one. But the reverse is not possible: immutable references will
never coerce to mutable references. Because of the borrowing rules, if you have
a mutable reference, that mutable reference must be the only reference to that
data (otherwise, the program wouldn’t compile). Converting one mutable
reference to one immutable reference will never break the borrowing rules.
Converting an immutable reference to a mutable reference would require that the
initial immutable reference is the only immutable reference to that data, but
the borrowing rules don’t guarantee that. Therefore, Rust can’t make the
assumption that converting an immutable reference to a mutable reference is
possible.
第三种情况比较棘手:Rust 还会将可变引用强制指向不可变引用。但反过来是不可能的:不可变引用永远不会强制可变引用。由于借用规则,如果您有可变引用,则该可变引用必须是对该数据的唯一引用(否则,程序将无法编译)。将一个可变引用转换为一个不可变引用永远不会违反借用规则。将不可变引用转换为可变引用将要求初始不可变引用是对该数据的唯一不可变引用,但借用规则并不保证这一点。因此,Rust 不能假设将不可变引用转换为可变引用是可能的。
Running Code on Cleanup with the Drop
Trait
使用Drop
Trait 在清理时运行代码
The second trait important to the smart pointer pattern is Drop
, which lets
you customize what happens when a value is about to go out of scope. You can
provide an implementation for the Drop
trait on any type, and that code can
be used to release resources like files or network connections.
对于智能指针模式重要的第二个特征是Drop
,它允许您自定义当值即将超出范围时会发生的情况。您可以为任何类型的Drop
特征提供实现,并且该代码可用于释放文件或网络连接等资源。
We’re introducing Drop
in the context of smart pointers because the
functionality of the Drop
trait is almost always used when implementing a
smart pointer. For example, when a Box<T>
is dropped it will deallocate the
space on the heap that the box points to.
我们在智能指针的上下文中引入Drop
因为在实现智能指针时几乎总是使用Drop
特征的功能。例如,当删除Box<T>
时,它将释放该框指向的堆上的空间。
In some languages, for some types, the programmer must call code to free memory
or resources every time they finish using an instance of those types. Examples
include file handles, sockets, or locks. If they forget, the system might
become overloaded and crash. In Rust, you can specify that a particular bit of
code be run whenever a value goes out of scope, and the compiler will insert
this code automatically. As a result, you don’t need to be careful about
placing cleanup code everywhere in a program that an instance of a particular
type is finished with—you still won’t leak resources!
在某些语言中,对于某些类型,程序员每次使用完这些类型的实例时都必须调用代码来释放内存或资源。示例包括文件句柄、套接字或锁。如果他们忘记了,系统可能会过载并崩溃。在 Rust 中,您可以指定每当值超出范围时运行特定的代码位,编译器将自动插入此代码。因此,您无需小心地将清理代码放置在特定类型实例完成的程序中的任何位置 - 您仍然不会泄漏资源!
You specify the code to run when a value goes out of scope by implementing the
Drop
trait. The Drop
trait requires you to implement one method named
drop
that takes a mutable reference to self
. To see when Rust calls drop
,
let’s implement drop
with println!
statements for now.
您可以通过实现Drop
特征来指定当值超出范围时要运行的代码。 Drop
特征要求您实现一个名为drop
的方法,该方法采用对self
的可变引用。要查看 Rust 何时调用drop
,让我们用 println 实现drop
println!
暂时发表声明。
Listing 15-14 shows a CustomSmartPointer
struct whose only custom
functionality is that it will print Dropping CustomSmartPointer!
when the
instance goes out of scope, to show when Rust runs the drop
function.
清单 15-14 显示了一个CustomSmartPointer
结构,其唯一的自定义功能是它将打印Dropping CustomSmartPointer!
当实例超出范围时,显示 Rust 何时运行drop
函数。
Filename: src/main.rs 文件名:src/main.rs
struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&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.");
}
The Drop
trait is included in the prelude, so we don’t need to bring it into
scope. We implement the Drop
trait on CustomSmartPointer
and provide an
implementation for the drop
method that calls println!
. The body of the
drop
function is where you would place any logic that you wanted to run when
an instance of your type goes out of scope. We’re printing some text here to
demonstrate visually when Rust will call drop
.Drop
特征包含在前奏中,因此我们不需要将其纳入范围。我们在CustomSmartPointer
上实现Drop
特征,并提供调用println!
的drop
方法的实现! 。 drop
函数的主体是您可以放置当您的类型的实例超出范围时要运行的任何逻辑的位置。我们在这里打印一些文本来直观地演示 Rust 何时调用drop
。
In main
, we create two instances of CustomSmartPointer
and then print
CustomSmartPointers created
. At the end of main
, our instances of
CustomSmartPointer
will go out of scope, and Rust will call the code we put
in the drop
method, printing our final message. Note that we didn’t need to
call the drop
method explicitly.
在main
中,我们创建了两个CustomSmartPointer
实例,然后打印CustomSmartPointers created
。在main
的末尾,我们的CustomSmartPointer
实例将超出范围,Rust 将调用我们放入drop
方法中的代码,打印我们的最终消息。请注意,我们不需要显式调用drop
方法。
When we run this program, we’ll see the following output:
当我们运行这个程序时,我们将看到以下输出:
$ 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`!
Rust automatically called drop
for us when our instances went out of scope,
calling the code we specified. Variables are dropped in the reverse order of
their creation, so d
was dropped before c
. This example’s purpose is to
give you a visual guide to how the drop
method works; usually you would
specify the cleanup code that your type needs to run rather than a print
message.
当我们的实例超出范围时,Rust 会自动为我们调用drop
,调用我们指定的代码。变量按照其创建的相反顺序被删除,因此d
在c
之前被删除。此示例的目的是为您提供drop
方法如何工作的直观指南;通常,您会指定您的类型需要运行的清理代码,而不是打印消息。
Dropping a Value Early with std::mem::drop
使用std::mem::drop
提前删除值
Unfortunately, it’s not straightforward to disable the automatic drop
functionality. Disabling drop
isn’t usually necessary; the whole point of the
Drop
trait is that it’s taken care of automatically. Occasionally, however,
you might want to clean up a value early. One example is when using smart
pointers that manage locks: you might want to force the drop
method that
releases the lock so that other code in the same scope can acquire the lock.
Rust doesn’t let you call the Drop
trait’s drop
method manually; instead
you have to call the std::mem::drop
function provided by the standard library
if you want to force a value to be dropped before the end of its scope.
不幸的是,禁用自动drop
功能并不简单。通常不需要禁用drop
; Drop
特征的全部要点在于它是自动处理的。然而,有时您可能希望尽早清理某个值。一个例子是使用管理锁的智能指针时:您可能希望强制释放锁的drop
方法,以便同一范围内的其他代码可以获得锁。 Rust 不允许您手动调用Drop
特征的drop
方法;相反,如果您想强制在其范围结束之前删除某个值,则必须调用标准库提供的std::mem::drop
函数。
If we try to call the Drop
trait’s drop
method manually by modifying the
main
function from Listing 15-14, as shown in Listing 15-15, we’ll get a
compiler error:
如果我们尝试通过修改清单 15-14 中的main
函数来手动调用Drop
特征的drop
方法,如清单 15-15 所示,我们将收到编译器错误:
Filename: src/main.rs 文件名:src/main.rs
When we try to compile this code, we’ll get this error:
当我们尝试编译此代码时,我们会收到以下错误:
$ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
error[E0040]: explicit use of destructor method
--> 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
This error message states that we’re not allowed to explicitly call drop
. The
error message uses the term destructor, which is the general programming term
for a function that cleans up an instance. A destructor is analogous to a
constructor, which creates an instance. The drop
function in Rust is one
particular destructor.
此错误消息表明我们不允许显式调用drop
。该错误消息使用术语析构函数,这是清理实例的函数的通用编程术语。析构函数类似于构造函数,它创建一个实例。 Rust 中的drop
函数是一种特殊的析构函数。
Rust doesn’t let us call drop
explicitly because Rust would still
automatically call drop
on the value at the end of main
. This would cause a
double free error because Rust would be trying to clean up the same value
twice.
Rust 不允许我们显式调用drop
,因为 Rust 仍然会自动对main
末尾的值调用drop
。这会导致双重释放错误,因为 Rust 会尝试两次清理相同的值。
We can’t disable the automatic insertion of drop
when a value goes out of
scope, and we can’t call the drop
method explicitly. So, if we need to force
a value to be cleaned up early, we use the std::mem::drop
function.
当值超出范围时,我们无法禁用drop
的自动插入,并且无法显式调用drop
方法。因此,如果我们需要强制尽早清除某个值,我们可以使用std::mem::drop
函数。
The std::mem::drop
function is different from the drop
method in the Drop
trait. We call it by passing as an argument the value we want to force drop.
The function is in the prelude, so we can modify main
in Listing 15-15 to
call the drop
function, as shown in Listing 15-16:std::mem::drop
函数与Drop
特征中的drop
方法不同。我们通过将要强制删除的值作为参数传递来调用它。该函数位于prelude中,因此我们可以修改清单15-15中的main
来调用drop
函数,如清单15-16所示:
Filename: src/main.rs 文件名:src/main.rs
Running this code will print the following:
运行此代码将打印以下内容:
$ 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.
The text Dropping CustomSmartPointer with data `some data`!
is printed
between the CustomSmartPointer created.
and CustomSmartPointer dropped before the end of main.
text, showing that the drop
method code is called to
drop c
at that point.
文本Dropping CustomSmartPointer with data `some data`!
在CustomSmartPointer created.
和CustomSmartPointer dropped before the end of main.
文本,显示在该点调用drop
方法代码来删除c
。
You can use code specified in a Drop
trait implementation in many ways to
make cleanup convenient and safe: for instance, you could use it to create your
own memory allocator! With the Drop
trait and Rust’s ownership system, you
don’t have to remember to clean up because Rust does it automatically.
您可以通过多种方式使用Drop
特征实现中指定的代码,以使清理方便且安全:例如,您可以使用它来创建自己的内存分配器!借助Drop
特征和 Rust 的所有权系统,您不必记得清理,因为 Rust 会自动执行此操作。
You also don’t have to worry about problems resulting from accidentally
cleaning up values still in use: the ownership system that makes sure
references are always valid also ensures that drop
gets called only once when
the value is no longer being used.
您也不必担心因意外清理仍在使用的值而导致的问题:确保引用始终有效的所有权系统还确保仅在不再使用该值时调用drop
一次。
Now that we’ve examined Box<T>
and some of the characteristics of smart
pointers, let’s look at a few other smart pointers defined in the standard
library.
现在我们已经研究了Box<T>
和智能指针的一些特征,让我们看看标准库中定义的其他一些智能指针。
Rc<T>
, the Reference Counted Smart Pointer
Rc<T>
,引用计数智能指针
In the majority of cases, ownership is clear: you know exactly which variable
owns a given value. However, there are cases when a single value might have
multiple owners. For example, in graph data structures, multiple edges might
point to the same node, and that node is conceptually owned by all of the edges
that point to it. A node shouldn’t be cleaned up unless it doesn’t have any
edges pointing to it and so has no owners.
在大多数情况下,所有权是明确的:您确切地知道哪个变量拥有给定值。但是,在某些情况下,单个值可能有多个所有者。例如,在图数据结构中,多个边可能指向同一个节点,并且该节点在概念上由指向它的所有边所拥有。一个节点不应该被清理,除非它没有任何边指向它并且没有所有者。
You have to enable multiple ownership explicitly by using the Rust type
Rc<T>
, which is an abbreviation for reference counting. The Rc<T>
type
keeps track of the number of references to a value to determine whether or not
the value is still in use. If there are zero references to a value, the value
can be cleaned up without any references becoming invalid.
您必须使用 Rust 类型Rc<T>
(引用计数的缩写)显式启用多重所有权。 Rc<T>
类型跟踪对某个值的引用次数,以确定该值是否仍在使用中。如果对某个值的引用为零,则可以清除该值,而不会导致任何引用无效。
Imagine Rc<T>
as a TV in a family room. When one person enters to watch TV,
they turn it on. Others can come into the room and watch the TV. When the last
person leaves the room, they turn off the TV because it’s no longer being used.
If someone turns off the TV while others are still watching it, there would be
uproar from the remaining TV watchers!
将Rc<T>
想象为家庭房间中的电视。当一个人进来看电视时,他们就会打开电视。其他人可以进入房间看电视。当最后一个人离开房间时,他们会关掉电视,因为电视不再被使用。如果有人在其他人还在看电视的时候关掉电视,剩下的电视观众就会哗然!
We use the Rc<T>
type when we want to allocate some data on the heap for
multiple parts of our program to read and we can’t determine at compile time
which part will finish using the data last. If we knew which part would finish
last, we could just make that part the data’s owner, and the normal ownership
rules enforced at compile time would take effect.
当我们想要在堆上分配一些数据供程序的多个部分读取并且我们无法在编译时确定哪个部分最后使用这些数据时,我们使用Rc<T>
类型。如果我们知道哪个部分将最后完成,我们可以将该部分设为数据的所有者,并且在编译时强制执行的正常所有权规则将生效。
Note that Rc<T>
is only for use in single-threaded scenarios. When we discuss
concurrency in Chapter 16, we’ll cover how to do reference counting in
multithreaded programs.
请注意, Rc<T>
仅适用于单线程场景。当我们在第 16 章讨论并发时,我们将讨论如何在多线程程序中进行引用计数。
Using Rc<T>
to Share Data
使用Rc<T>
共享数据
Let’s return to our cons list example in Listing 15-5. Recall that we defined
it using Box<T>
. This time, we’ll create two lists that both share ownership
of a third list. Conceptually, this looks similar to Figure 15-3:
让我们回到清单 15-5 中的 cons 列表示例。回想一下,我们使用Box<T>
定义了它。这次,我们将创建两个列表,它们共享第三个列表的所有权。从概念上讲,这看起来类似于图 15-3:
We’ll create list a
that contains 5 and then 10. Then we’ll make two more
lists: b
that starts with 3 and c
that starts with 4. Both b
and c
lists will then continue on to the first a
list containing 5 and 10. In other
words, both lists will share the first list containing 5 and 10.
我们将创建包含 5 和 10 的列表a
。然后我们将再创建两个列表:以 3 开头的b
和以 4 开头的c
。然后b
和c
列表将继续到第一个包含 5 的a
和 10。换句话说,两个列表将共享第一个包含 5 和 10 的列表。
Trying to implement this scenario using our definition of List
with Box<T>
won’t work, as shown in Listing 15-17:
尝试使用带有Box<T>
的List
定义来实现此场景是行不通的,如清单 15-17 所示:
Filename: src/main.rs 文件名:src/main.rs
enum List {
Cons(i32, Box<List>),
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));
}
When we compile this code, we get this error:
当我们编译这段代码时,我们得到这个错误:
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0382]: use of moved value: `a`
--> 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
The Cons
variants own the data they hold, so when we create the b
list, a
is moved into b
and b
owns a
. Then, when we try to use a
again when
creating c
, we’re not allowed to because a
has been moved.Cons
变体拥有它们所保存的数据,因此当我们创建b
列表时, a
被移动到b
中,并且b
拥有a
。然后,当我们在创建c
时尝试再次使用a
时,我们将不允许这样做,因为a
已被移动。
We could change the definition of Cons
to hold references instead, but then
we would have to specify lifetime parameters. By specifying lifetime
parameters, we would be specifying that every element in the list will live at
least as long as the entire list. This is the case for the elements and lists
in Listing 15-17, but not in every scenario.
我们可以更改Cons
的定义来保存引用,但随后我们必须指定生命周期参数。通过指定生命周期参数,我们将指定列表中的每个元素的生存时间至少与整个列表一样长。清单 15-17 中的元素和列表就是这种情况,但并非在所有情况下都是如此。
Instead, we’ll change our definition of List
to use Rc<T>
in place of
Box<T>
, as shown in Listing 15-18. Each Cons
variant will now hold a value
and an Rc<T>
pointing to a List
. When we create b
, instead of taking
ownership of a
, we’ll clone the Rc<List>
that a
is holding, thereby
increasing the number of references from one to two and letting a
and b
share ownership of the data in that Rc<List>
. We’ll also clone a
when
creating c
, increasing the number of references from two to three. Every time
we call Rc::clone
, the reference count to the data within the Rc<List>
will
increase, and the data won’t be cleaned up unless there are zero references to
it.
相反,我们将更改List
的定义,以使用Rc<T>
代替Box<T>
,如清单 15-18 所示。每个Cons
变体现在将保存一个值和一个指向List
Rc<T>
。当我们创建b
时,我们不会获取a
的所有权,而是克隆a
所持有的Rc<List>
,从而将引用数量从 1 个增加到 2 个,并让a
和b
共享该Rc<List>
中数据的所有权Rc<List>
。我们还将在创建c
时克隆a
,将引用数量从两个增加到三个。每次调用Rc::clone
时,对Rc<List>
中数据的引用计数都会增加,除非对数据的引用为零,否则数据不会被清理。
Filename: src/main.rs 文件名:src/main.rs
enum List {
Cons(i32, Rc<List>),
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(&a));
let c = Cons(4, Rc::clone(&a));
}
We need to add a use
statement to bring Rc<T>
into scope because it’s not
in the prelude. In main
, we create the list holding 5 and 10 and store it in
a new Rc<List>
in a
. Then when we create b
and c
, we call the
Rc::clone
function and pass a reference to the Rc<List>
in a
as an
argument.
我们需要添加一条use
语句将Rc<T>
纳入作用域,因为它不在前奏中。在main
中,我们创建包含 5 和 10 的列表,并将其存储在a
中的新Rc<List>
中。然后,当我们创建b
和c
时,我们调用Rc::clone
函数并将a
中的Rc<List>
引用作为参数传递。
We could have called a.clone()
rather than Rc::clone(&a)
, but Rust’s
convention is to use Rc::clone
in this case. The implementation of
Rc::clone
doesn’t make a deep copy of all the data like most types’
implementations of clone
do. The call to Rc::clone
only increments the
reference count, which doesn’t take much time. Deep copies of data can take a
lot of time. By using Rc::clone
for reference counting, we can visually
distinguish between the deep-copy kinds of clones and the kinds of clones that
increase the reference count. When looking for performance problems in the
code, we only need to consider the deep-copy clones and can disregard calls to
Rc::clone
.
我们可以调用a.clone()
而不是Rc::clone(&a)
,但 Rust 的约定是在这种情况下使用Rc::clone
。 Rc::clone
的实现并不像大多数类型的clone
实现那样对所有数据进行深层复制。对Rc::clone
调用仅增加引用计数,这并不需要太多时间。数据的深层复制可能会花费大量时间。通过使用Rc::clone
进行引用计数,我们可以直观地区分深拷贝类型的克隆和增加引用计数的克隆类型。在查找代码中的性能问题时,我们只需要考虑深拷贝克隆,可以忽略对Rc::clone
的调用。
Cloning an Rc<T>
Increases the Reference Count
克隆Rc<T>
会增加引用计数
Let’s change our working example in Listing 15-18 so we can see the reference
counts changing as we create and drop references to the Rc<List>
in a
.
让我们更改清单 15-18 中的工作示例,以便在创建和删除对a
中的Rc<List>
的引用时看到引用计数发生变化。
In Listing 15-19, we’ll change main
so it has an inner scope around list c
;
then we can see how the reference count changes when c
goes out of scope.
在清单 15-19 中,我们将更改main
,使其具有围绕列表c
的内部作用域;然后我们可以看到当c
超出范围时引用计数如何变化。
Filename: src/main.rs 文件名:src/main.rs
At each point in the program where the reference count changes, we print the
reference count, which we get by calling the Rc::strong_count
function. This
function is named strong_count
rather than count
because the Rc<T>
type
also has a weak_count
; we’ll see what weak_count
is used for in the
“Preventing Reference Cycles: Turning an Rc<T>
into a
Weak<T>
” section.
在程序中引用计数发生变化的每个点,我们都会打印引用计数,这是通过调用Rc::strong_count
函数获得的。该函数被命名为strong_count
而不是count
因为Rc<T>
类型也有一个weak_count
;我们将在“防止引用循环:将Rc<T>
转换为Weak<T>
”忽略部分中了解weak_count
的用途。
This code prints the following:
此代码打印以下内容:
$ 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
We can see that the Rc<List>
in a
has an initial reference count of 1; then
each time we call clone
, the count goes up by 1. When c
goes out of scope,
the count goes down by 1. We don’t have to call a function to decrease the
reference count like we have to call Rc::clone
to increase the reference
count: the implementation of the Drop
trait decreases the reference count
automatically when an Rc<T>
value goes out of scope.
我们可以看到a
中的Rc<List>
初始引用计数为1;然后每次我们调用clone
,计数就会增加1。当c
超出范围时,计数就会减少1。我们不必像调用Rc::clone
以增加引用计数:当Rc<T>
值超出范围时, Drop
特征的实现会自动减少引用计数。
What we can’t see in this example is that when b
and then a
go out of scope
at the end of main
, the count is then 0, and the Rc<List>
is cleaned up
completely. Using Rc<T>
allows a single value to have multiple owners, and
the count ensures that the value remains valid as long as any of the owners
still exist.
在此示例中我们看不到的是,当b
和a
在main
末尾超出范围时,计数为 0,并且Rc<List>
被完全清理。使用Rc<T>
允许单个值拥有多个所有者,并且计数可确保只要任何所有者仍然存在,该值就保持有效。
Via immutable references, Rc<T>
allows you to share data between multiple
parts of your program for reading only. If Rc<T>
allowed you to have multiple
mutable references too, you might violate one of the borrowing rules discussed
in Chapter 4: multiple mutable borrows to the same place can cause data races
and inconsistencies. But being able to mutate data is very useful! In the next
section, we’ll discuss the interior mutability pattern and the RefCell<T>
type that you can use in conjunction with an Rc<T>
to work with this
immutability restriction.
通过不可变引用, Rc<T>
允许您在程序的多个部分之间共享数据以进行只读。如果Rc<T>
也允许您拥有多个可变引用,则可能会违反第 4 章中讨论的借用规则之一:对同一位置的多个可变借用可能会导致数据争用和不一致。但能够改变数据是非常有用的!在下一节中,我们将讨论内部可变性模式和RefCell<T>
类型,您可以将其与Rc<T>
结合使用以处理此不变性限制。
RefCell<T>
and the Interior Mutability Pattern
RefCell<T>
和内部可变性模式
Interior mutability is a design pattern in Rust that allows you to mutate
data even when there are immutable references to that data; normally, this
action is disallowed by the borrowing rules. To mutate data, the pattern uses
unsafe
code inside a data structure to bend Rust’s usual rules that govern
mutation and borrowing. Unsafe code indicates to the compiler that we’re
checking the rules manually instead of relying on the compiler to check them
for us; we will discuss unsafe code more in Chapter 19.
内部可变性是 Rust 中的一种设计模式,即使存在对该数据的不可变引用,也允许您改变数据;通常,借贷规则不允许这种行为。为了改变数据,该模式在数据结构内使用unsafe
代码来改变 Rust 管理突变和借用的通常规则。不安全代码向编译器表明我们正在手动检查规则,而不是依赖编译器为我们检查规则;我们将在第 19 章详细讨论不安全代码。
We can use types that use the interior mutability pattern only when we can
ensure that the borrowing rules will be followed at runtime, even though the
compiler can’t guarantee that. The unsafe
code involved is then wrapped in a
safe API, and the outer type is still immutable.
仅当我们可以确保在运行时遵循借用规则时,我们才能使用使用内部可变性模式的类型,即使编译器无法保证这一点。然后,涉及的unsafe
代码被包装在安全的 API 中,并且外部类型仍然是不可变的。
Let’s explore this concept by looking at the RefCell<T>
type that follows the
interior mutability pattern.
让我们通过查看遵循内部可变性模式的RefCell<T>
类型来探索这个概念。
Enforcing Borrowing Rules at Runtime with RefCell<T>
使用RefCell<T>
在运行时强制执行借用规则
Unlike Rc<T>
, the RefCell<T>
type represents single ownership over the data
it holds. So, what makes RefCell<T>
different from a type like Box<T>
?
Recall the borrowing rules you learned in Chapter 4:
与Rc<T>
不同, RefCell<T>
类型表示对其所持有的数据的单一所有权。那么,是什么让RefCell<T>
与Box<T>
这样的类型不同呢?回想一下您在第 4 章中学到的借用规则:
- At any given time, you can have either (but not both) one mutable reference
or any number of immutable references.
在任何给定时间,您可以拥有(但不能同时拥有)一个可变引用或任意数量的不可变引用。 - References must always be valid.
参考文献必须始终有效。
With references and Box<T>
, the borrowing rules’ invariants are enforced at
compile time. With RefCell<T>
, these invariants are enforced at runtime.
With references, if you break these rules, you’ll get a compiler error. With
RefCell<T>
, if you break these rules, your program will panic and exit.
通过引用和Box<T>
,借用规则的不变量在编译时强制执行。使用RefCell<T>
,这些不变量在运行时强制执行。对于引用,如果违反这些规则,则会出现编译器错误。使用RefCell<T>
,如果您违反这些规则,您的程序将出现恐慌并退出。
The advantages of checking the borrowing rules at compile time are that errors
will be caught sooner in the development process, and there is no impact on
runtime performance because all the analysis is completed beforehand. For those
reasons, checking the borrowing rules at compile time is the best choice in the
majority of cases, which is why this is Rust’s default.
在编译时检查借用规则的优点是可以在开发过程中更快地捕获错误,并且不会影响运行时性能,因为所有分析都已提前完成。出于这些原因,在大多数情况下,在编译时检查借用规则是最佳选择,这就是为什么这是 Rust 的默认设置。
The advantage of checking the borrowing rules at runtime instead is that
certain memory-safe scenarios are then allowed, where they would’ve been
disallowed by the compile-time checks. Static analysis, like the Rust compiler,
is inherently conservative. Some properties of code are impossible to detect by
analyzing the code: the most famous example is the Halting Problem, which is
beyond the scope of this book but is an interesting topic to research.
相反,在运行时检查借用规则的优点是允许某些内存安全的场景,而编译时检查将不允许这些场景。静态分析与 Rust 编译器一样,本质上是保守的。代码的某些属性无法通过分析代码来检测:最著名的例子是停止问题,这超出了本书的范围,但却是一个有趣的研究主题。
Because some analysis is impossible, if the Rust compiler can’t be sure the
code complies with the ownership rules, it might reject a correct program; in
this way, it’s conservative. If Rust accepted an incorrect program, users
wouldn’t be able to trust in the guarantees Rust makes. However, if Rust
rejects a correct program, the programmer will be inconvenienced, but nothing
catastrophic can occur. The RefCell<T>
type is useful when you’re sure your
code follows the borrowing rules but the compiler is unable to understand and
guarantee that.
因为有些分析是不可能的,如果 Rust 编译器不能确定代码符合所有权规则,它可能会拒绝正确的程序;这样看来,还是保守的。如果 Rust 接受了不正确的程序,用户将无法信任 Rust 所做的保证。然而,如果 Rust 拒绝正确的程序,程序员会感到不便,但不会发生灾难性的情况。当您确定代码遵循借用规则但编译器无法理解和保证这一点时, RefCell<T>
类型非常有用。
Similar to Rc<T>
, RefCell<T>
is only for use in single-threaded scenarios
and will give you a compile-time error if you try using it in a multithreaded
context. We’ll talk about how to get the functionality of RefCell<T>
in a
multithreaded program in Chapter 16.
与Rc<T>
类似, RefCell<T>
仅适用于单线程场景,如果您尝试在多线程上下文中使用它,则会出现编译时错误。我们将在第 16 章讨论如何在多线程程序中获取RefCell<T>
的功能。
Here is a recap of the reasons to choose Box<T>
, Rc<T>
, or RefCell<T>
:
以下是选择Box<T>
、 Rc<T>
或RefCell<T>
的原因的回顾:
Rc<T>
enables multiple owners of the same data;Box<T>
andRefCell<T>
have single owners.Rc<T>
允许同一数据有多个所有者;Box<T>
和RefCell<T>
具有单一所有者。Box<T>
allows immutable or mutable borrows checked at compile time;Rc<T>
allows only immutable borrows checked at compile time;RefCell<T>
allows immutable or mutable borrows checked at runtime.Box<T>
允许在编译时检查不可变或可变借用;Rc<T>
只允许在编译时检查不可变借用;RefCell<T>
允许在运行时检查不可变或可变借用。- Because
RefCell<T>
allows mutable borrows checked at runtime, you can mutate the value inside theRefCell<T>
even when theRefCell<T>
is immutable.
由于RefCell<T>
允许在运行时检查可变借用,因此即使RefCell<T>
RefCell<T>
内的值。
Mutating the value inside an immutable value is the interior mutability
pattern. Let’s look at a situation in which interior mutability is useful and
examine how it’s possible.
改变不可变值内部的值是内部可变性模式。让我们看一下内部可变性有用的情况,并研究它是如何实现的。
Interior Mutability: A Mutable Borrow to an Immutable Value
内部可变性:对不可变值的可变借用
A consequence of the borrowing rules is that when you have an immutable value,
you can’t borrow it mutably. For example, this code won’t compile:
借用规则的一个结果是,当你有一个不可变的值时,你就不能可变地借用它。例如,以下代码将无法编译:
fn main() {
let x = 5;
let y = &mut x;
}
If you tried to compile this code, you’d get the following error:
如果您尝试编译此代码,您会收到以下错误:
$ cargo run
Compiling borrowing v0.1.0 (file:///projects/borrowing)
error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable
--> src/main.rs:3:13
|
3 | let y = &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
However, there are situations in which it would be useful for a value to mutate
itself in its methods but appear immutable to other code. Code outside the
value’s methods would not be able to mutate the value. Using RefCell<T>
is
one way to get the ability to have interior mutability, but RefCell<T>
doesn’t get around the borrowing rules completely: the borrow checker in the
compiler allows this interior mutability, and the borrowing rules are checked
at runtime instead. If you violate the rules, you’ll get a panic!
instead of
a compiler error.
然而,在某些情况下,一个值在其方法中改变自身是有用的,但对于其他代码来说似乎是不可变的。值方法之外的代码将无法更改该值。使用RefCell<T>
是获得内部可变性能力的一种方法,但RefCell<T>
并不能完全绕过借用规则:编译器中的借用检查器允许这种内部可变性,并且借用规则是相反,在运行时检查。如果你违反了规则,你会感到panic!
而不是编译器错误。
Let’s work through a practical example where we can use RefCell<T>
to mutate
an immutable value and see why that is useful.
让我们看一个实际的例子,我们可以使用RefCell<T>
来改变一个不可变的值,并看看为什么它是有用的。
A Use Case for Interior Mutability: Mock Objects
内部可变性的用例:模拟对象
Sometimes during testing a programmer will use a type in place of another type,
in order to observe particular behavior and assert it’s implemented correctly.
This placeholder type is called a test double. Think of it in the sense of a
“stunt double” in filmmaking, where a person steps in and substitutes for an
actor to do a particular tricky scene. Test doubles stand in for other types
when we’re running tests. Mock objects are specific types of test doubles
that record what happens during a test so you can assert that the correct
actions took place.
有时,在测试过程中,程序员会使用一种类型代替另一种类型,以便观察特定行为并断言其实现正确。这种占位符类型称为测试双精度。可以把它想象成电影制作中的“替身”,一个人介入并替代演员来完成一个特定的棘手场景。当我们运行测试时,测试替身代表其他类型。模拟对象是特定类型的测试替身,用于记录测试期间发生的情况,以便您可以断言发生了正确的操作。
Rust doesn’t have objects in the same sense as other languages have objects,
and Rust doesn’t have mock object functionality built into the standard library
as some other languages do. However, you can definitely create a struct that
will serve the same purposes as a mock object.
Rust 不具有与其他语言具有对象相同意义上的对象,并且 Rust 没有像其他语言那样将模拟对象功能内置到标准库中。但是,您绝对可以创建一个与模拟对象具有相同用途的结构。
Here’s the scenario we’ll test: we’ll create a library that tracks a value
against a maximum value and sends messages based on how close to the maximum
value the current value is. This library could be used to keep track of a
user’s quota for the number of API calls they’re allowed to make, for example.
这是我们要测试的场景:我们将创建一个库,该库根据最大值跟踪某个值,并根据当前值与最大值的接近程度发送消息。例如,该库可用于跟踪用户允许进行的 API 调用数量的配额。
Our library will only provide the functionality of tracking how close to the
maximum a value is and what the messages should be at what times. Applications
that use our library will be expected to provide the mechanism for sending the
messages: the application could put a message in the application, send an
email, send a text message, or something else. The library doesn’t need to know
that detail. All it needs is something that implements a trait we’ll provide
called Messenger
. Listing 15-20 shows the library code:
我们的库将仅提供跟踪值与最大值的接近程度以及消息应该在什么时间发出的功能。使用我们的库的应用程序预计将提供发送消息的机制:应用程序可以在应用程序中放置消息、发送电子邮件、发送文本消息或其他内容。图书馆不需要知道这个细节。它所需要的只是实现我们将提供的称为Messenger
特征。清单 15-20 显示了库代码:
Filename: src/lib.rs 文件名:src/lib.rs
pub trait Messenger {
fn send(&self, msg: &str);
}
pub struct LimitTracker<'a, T: Messenger> {
messenger: &'a T,
value: usize,
max: usize,
}
impl<'a, T> LimitTracker<'a, T>
where
T: Messenger,
{
pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
LimitTracker {
messenger,
value: 0,
max,
}
}
pub fn set_value(&mut self, value: usize) {
self.value = value;
let percentage_of_max = self.value as f64 / self.max as f64;
if percentage_of_max >= 1.0 {
self.messenger.send("Error: You are over your quota!");
} else if percentage_of_max >= 0.9 {
self.messenger
.send("Urgent warning: You've used up over 90% of your quota!");
} else if percentage_of_max >= 0.75 {
self.messenger
.send("Warning: You've used up over 75% of your quota!");
}
}
}
One important part of this code is that the Messenger
trait has one method
called send
that takes an immutable reference to self
and the text of the
message. This trait is the interface our mock object needs to implement so that
the mock can be used in the same way a real object is. The other important part
is that we want to test the behavior of the set_value
method on the
LimitTracker
. We can change what we pass in for the value
parameter, but
set_value
doesn’t return anything for us to make assertions on. We want to be
able to say that if we create a LimitTracker
with something that implements
the Messenger
trait and a particular value for max
, when we pass different
numbers for value
, the messenger is told to send the appropriate messages.
此代码的一个重要部分是Messenger
特征有一种名为send
方法,该方法采用对self
和消息文本的不可变引用。这个特征是我们的模拟对象需要实现的接口,以便模拟可以像真实对象一样使用。另一个重要部分是我们想要测试LimitTracker
上set_value
方法的行为。我们可以更改为value
参数传递的内容,但set_value
不会返回任何内容供我们进行断言。我们希望能够说,如果我们使用实现Messenger
特征和max
特定值的东西创建一个LimitTracker
,那么当我们为value
传递不同的数字时,信使就会被告知发送适当的消息。
We need a mock object that, instead of sending an email or text message when we
call send
, will only keep track of the messages it’s told to send. We can
create a new instance of the mock object, create a LimitTracker
that uses the
mock object, call the set_value
method on LimitTracker
, and then check that
the mock object has the messages we expect. Listing 15-21 shows an attempt to
implement a mock object to do just that, but the borrow checker won’t allow it:
我们需要一个模拟对象,当我们调用send
时,它不会发送电子邮件或短信,而只会跟踪它被告知发送的消息。我们可以创建一个新的模拟对象实例,创建一个使用该模拟对象的LimitTracker
,调用LimitTracker
上的set_value
方法,然后检查该模拟对象是否具有我们期望的消息。清单 15-21 展示了尝试实现一个模拟对象来做到这一点,但借用检查器不允许这样做:
Filename: src/lib.rs 文件名:src/lib.rs
This test code defines a MockMessenger
struct that has a sent_messages
field with a Vec
of String
values to keep track of the messages it’s told
to send. We also define an associated function new
to make it convenient to
create new MockMessenger
values that start with an empty list of messages. We
then implement the Messenger
trait for MockMessenger
so we can give a
MockMessenger
to a LimitTracker
. In the definition of the send
method, we
take the message passed in as a parameter and store it in the MockMessenger
list of sent_messages
.
此测试代码定义了一个MockMessenger
结构,该结构具有一个sent_messages
字段,其中包含一个String
值的Vec
,用于跟踪被告知要发送的消息。我们还定义了一个关联函数new
以便于创建以空消息列表开头的新MockMessenger
值。然后,我们为MockMessenger
实现Messenger
特征,这样我们就可以将MockMessenger
提供给LimitTracker
。在send
方法的定义中,我们将传入的消息作为参数,并将其存储在MockMessenger
的sent_messages
列表中。
In the test, we’re testing what happens when the LimitTracker
is told to set
value
to something that is more than 75 percent of the max
value. First, we
create a new MockMessenger
, which will start with an empty list of messages.
Then we create a new LimitTracker
and give it a reference to the new
MockMessenger
and a max
value of 100. We call the set_value
method on the
LimitTracker
with a value of 80, which is more than 75 percent of 100. Then
we assert that the list of messages that the MockMessenger
is keeping track
of should now have one message in it.
在测试中,我们正在测试当LimitTracker
被告知将value
设置为大于max
75% 时会发生什么情况。首先,我们创建一个新的MockMessenger
,它将以空消息列表开始。然后我们创建一个新的LimitTracker
并给它一个新的MockMessenger
的引用和max
100。我们调用LimitTracker
上的set_value
方法,值为 80,超过 100 的 75%。然后我们断言MockMessenger
跟踪的消息列表现在应该包含一条消息。
However, there’s one problem with this test, as shown here:
但是,此测试有一个问题,如下所示:
$ 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 `&` reference
--> src/lib.rs:58:13
|
58 | self.sent_messages.push(String::from(message));
| ^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference
|
2 | fn send(&mut self, msg: &str);
| ~~~~~~~~~
For more information about this error, try `rustc --explain E0596`.
error: could not compile `limit-tracker` (lib test) due to 1 previous error
We can’t modify the MockMessenger
to keep track of the messages, because the
send
method takes an immutable reference to self
. We also can’t take the
suggestion from the error text to use &mut self
instead, because then the
signature of send
wouldn’t match the signature in the Messenger
trait
definition (feel free to try and see what error message you get).
我们无法修改MockMessenger
来跟踪消息,因为send
方法采用对self
的不可变引用。我们也无法从错误文本中获取建议来使用&mut self
来代替,因为这样send
的签名将与Messenger
特征定义中的签名不匹配(请随意尝试看看您会收到什么错误消息)。
This is a situation in which interior mutability can help! We’ll store the
sent_messages
within a RefCell<T>
, and then the send
method will be
able to modify sent_messages
to store the messages we’ve seen. Listing 15-22
shows what that looks like:
在这种情况下,内部可变性可以提供帮助!我们将sent_messages
存储在RefCell<T>
中,然后send
方法将能够修改sent_messages
以存储我们看到的消息。清单 15-22 显示了它的样子:
Filename: src/lib.rs 文件名:src/lib.rs
The sent_messages
field is now of type RefCell<Vec<String>>
instead of
Vec<String>
. In the new
function, we create a new RefCell<Vec<String>>
instance around the empty vector.sent_messages
字段现在的类型为RefCell<Vec<String>>
而不是Vec<String>
。在new
函数中,我们围绕空向量创建一个新的RefCell<Vec<String>>
实例。
For the implementation of the send
method, the first parameter is still an
immutable borrow of self
, which matches the trait definition. We call
borrow_mut
on the RefCell<Vec<String>>
in self.sent_messages
to get a
mutable reference to the value inside the RefCell<Vec<String>>
, which is the
vector. Then we can call push
on the mutable reference to the vector to keep
track of the messages sent during the test.
对于send
方法的实现,第一个参数仍然是self
的不可变借用,它与特征定义匹配。我们在self.sent_messages
中对RefCell<Vec<String>>
调用borrow_mut
,以获取对RefCell<Vec<String>>
内值(即向量)的可变引用。然后我们可以对向量的可变引用调用push
来跟踪测试期间发送的消息。
The last change we have to make is in the assertion: to see how many items are
in the inner vector, we call borrow
on the RefCell<Vec<String>>
to get an
immutable reference to the vector.
我们必须做的最后一个更改是在断言中:要查看内部向量中有多少项,我们对RefCell<Vec<String>>
调用borrow
以获取对该向量的不可变引用。
Now that you’ve seen how to use RefCell<T>
, let’s dig into how it works!
现在您已经了解了如何使用RefCell<T>
,让我们深入了解它是如何工作的!
Keeping Track of Borrows at Runtime with RefCell<T>
使用RefCell<T>
在运行时跟踪借用
When creating immutable and mutable references, we use the &
and &mut
syntax, respectively. With RefCell<T>
, we use the borrow
and borrow_mut
methods, which are part of the safe API that belongs to RefCell<T>
. The
borrow
method returns the smart pointer type Ref<T>
, and borrow_mut
returns the smart pointer type RefMut<T>
. Both types implement Deref
, so we
can treat them like regular references.
创建不可变和可变引用时,我们分别使用&
和&mut
语法。对于RefCell<T>
,我们使用borrow
和borrow_mut
方法,它们是属于RefCell<T>
的安全API的一部分。 borrow
方法返回智能指针类型Ref<T>
, borrow_mut
返回智能指针类型RefMut<T>
。两种类型都实现Deref
,因此我们可以将它们视为常规引用。
The RefCell<T>
keeps track of how many Ref<T>
and RefMut<T>
smart
pointers are currently active. Every time we call borrow
, the RefCell<T>
increases its count of how many immutable borrows are active. When a Ref<T>
value goes out of scope, the count of immutable borrows goes down by one. Just
like the compile-time borrowing rules, RefCell<T>
lets us have many immutable
borrows or one mutable borrow at any point in time.RefCell<T>
跟踪当前有多少Ref<T>
和RefMut<T>
智能指针处于活动状态。每次我们调用borrow
, RefCell<T>
都会增加活动的不可变借用的计数。当Ref<T>
值超出范围时,不可变借用计数将减少 1。就像编译时借用规则一样, RefCell<T>
允许我们在任何时间点拥有许多不可变借用或一个可变借用。
If we try to violate these rules, rather than getting a compiler error as we
would with references, the implementation of RefCell<T>
will panic at
runtime. Listing 15-23 shows a modification of the implementation of send
in
Listing 15-22. We’re deliberately trying to create two mutable borrows active
for the same scope to illustrate that RefCell<T>
prevents us from doing this
at runtime.
如果我们尝试违反这些规则, RefCell<T>
的实现将在运行时出现恐慌,而不是像引用引用那样出现编译器错误。清单 15-23 显示了清单 15-22 中send
实现的修改。我们故意尝试为同一范围创建两个活动的可变借用,以说明RefCell<T>
阻止我们在运行时执行此操作。
Filename: src/lib.rs 文件名:src/lib.rs
We create a variable one_borrow
for the RefMut<T>
smart pointer returned
from borrow_mut
. Then we create another mutable borrow in the same way in the
variable two_borrow
. This makes two mutable references in the same scope,
which isn’t allowed. When we run the tests for our library, the code in Listing
15-23 will compile without any errors, but the test will fail:
我们为从borrow_mut
返回的RefMut<T>
智能指针创建一个变量one_borrow
。然后我们以相同的方式在变量two_borrow
中创建另一个可变借用。这使得两个可变引用处于同一范围内,这是不允许的。当我们对我们的库运行测试时,清单 15-23 中的代码将编译没有任何错误,但测试将失败:
$ 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`
Notice that the code panicked with the message already borrowed: BorrowMutError
. This is how RefCell<T>
handles violations of the borrowing
rules at runtime.
请注意,代码因already borrowed: BorrowMutError
。这就是RefCell<T>
在运行时处理违反借用规则的方式。
Choosing to catch borrowing errors at runtime rather than compile time, as
we’ve done here, means you’d potentially be finding mistakes in your code later
in the development process: possibly not until your code was deployed to
production. Also, your code would incur a small runtime performance penalty as
a result of keeping track of the borrows at runtime rather than compile time.
However, using RefCell<T>
makes it possible to write a mock object that can
modify itself to keep track of the messages it has seen while you’re using it
in a context where only immutable values are allowed. You can use RefCell<T>
despite its trade-offs to get more functionality than regular references
provide.
选择在运行时而不是编译时捕获借用错误(正如我们在这里所做的那样),意味着您可能会在开发过程的后期发现代码中的错误:可能直到您的代码部署到生产环境后才会发现。此外,由于在运行时而不是编译时跟踪借用,您的代码会产生较小的运行时性能损失。但是,使用RefCell<T>
可以编写一个模拟对象,该对象可以修改自身以跟踪在仅允许不可变值的上下文中使用它时所看到的消息。您可以使用RefCell<T>
尽管它需要权衡以获得比常规引用提供的更多功能。
Having Multiple Owners of Mutable Data by Combining Rc<T>
and RefCell<T>
通过组合Rc<T>
和RefCell<T>
拥有可变数据的多个所有者
A common way to use RefCell<T>
is in combination with Rc<T>
. Recall that
Rc<T>
lets you have multiple owners of some data, but it only gives immutable
access to that data. If you have an Rc<T>
that holds a RefCell<T>
, you can
get a value that can have multiple owners and that you can mutate!
使用RefCell<T>
的常见方法是与Rc<T>
结合使用。回想一下, Rc<T>
允许您拥有某些数据的多个所有者,但它只提供对该数据的不可变访问。如果您有一个包含 RefCell Rc<T>
RefCell<T>
,您可以获得一个可以拥有多个所有者并且可以变异的值!
For example, recall the cons list example in Listing 15-18 where we used
Rc<T>
to allow multiple lists to share ownership of another list. Because
Rc<T>
holds only immutable values, we can’t change any of the values in the
list once we’ve created them. Let’s add in RefCell<T>
to gain the ability to
change the values in the lists. Listing 15-24 shows that by using a
RefCell<T>
in the Cons
definition, we can modify the value stored in all
the lists:
例如,回想一下清单 15-18 中的 cons 列表示例,其中我们使用Rc<T>
来允许多个列表共享另一个列表的所有权。由于Rc<T>
仅保存不可变值,因此一旦创建了列表中的任何值,我们就无法更改它们。让我们添加RefCell<T>
以获得更改列表中的值的能力。清单 15-24 显示,通过在Cons
定义中使用RefCell<T>
,我们可以修改存储在所有列表中的值:
Filename: src/main.rs 文件名:src/main.rs
#[derive(Debug)]
enum List {
Cons(Rc<RefCell<i32>>, Rc<List>),
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(&value), Rc::new(Nil)));
let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a));
let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a));
*value.borrow_mut() += 10;
println!("a after = {a:?}");
println!("b after = {b:?}");
println!("c after = {c:?}");
}
We create a value that is an instance of Rc<RefCell<i32>>
and store it in a
variable named value
so we can access it directly later. Then we create a
List
in a
with a Cons
variant that holds value
. We need to clone
value
so both a
and value
have ownership of the inner 5
value rather
than transferring ownership from value
to a
or having a
borrow from
value
.
我们创建一个作为Rc<RefCell<i32>>
实例的值,并将其存储在名为value
的变量中,以便稍后可以直接访问它。然后我们在a
中创建一个List
,其中包含一个包含value
的Cons
变体。我们需要克隆value
,以便a
和value
都拥有内部5
值的所有权,而不是将所有权从value
转移到a
或从value
a
。
We wrap the list a
in an Rc<T>
so when we create lists b
and c
, they
can both refer to a
, which is what we did in Listing 15-18.
我们将列表a
包装在Rc<T>
中,因此当我们创建列表b
和c
时,它们都可以引用a
,这就是我们在清单 15-18 中所做的。
After we’ve created the lists in a
, b
, and c
, we want to add 10 to the
value in value
. We do this by calling borrow_mut
on value
, which uses the
automatic dereferencing feature we discussed in Chapter 5 (see the section
“Where’s the ->
Operator?”) to
dereference the Rc<T>
to the inner RefCell<T>
value. The borrow_mut
method returns a RefMut<T>
smart pointer, and we use the dereference operator
on it and change the inner value.
在a
、 b
和c
中创建列表后,我们想要将value
中的值加 10。我们通过调用value
上的borrow_mut
来做到这一点,它使用我们在第5章中讨论的自动取消引用功能(请参阅“ ->
运算符在哪里?” ignore部分)将Rc<T>
取消引用到内部RefCell<T>
值。 borrow_mut
方法返回一个RefMut<T>
智能指针,我们对其使用解引用运算符并更改内部值。
When we print a
, b
, and c
, we can see that they all have the modified
value of 15 rather than 5:
当我们打印a
、 b
和c
时,我们可以看到它们的修改值都是 15 而不是 5:
$ 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))
This technique is pretty neat! By using RefCell<T>
, we have an outwardly
immutable List
value. But we can use the methods on RefCell<T>
that provide
access to its interior mutability so we can modify our data when we need to.
The runtime checks of the borrowing rules protect us from data races, and it’s
sometimes worth trading a bit of speed for this flexibility in our data
structures. Note that RefCell<T>
does not work for multithreaded code!
Mutex<T>
is the thread-safe version of RefCell<T>
and we’ll discuss
Mutex<T>
in Chapter 16.
这个技术非常巧妙!通过使用RefCell<T>
,我们有一个表面上不可变的List
值。但是我们可以使用RefCell<T>
上的方法来访问其内部可变性,以便我们可以在需要时修改数据。借用规则的运行时检查可以保护我们免受数据竞争的影响,有时为了数据结构的灵活性而牺牲一点速度是值得的。请注意, RefCell<T>
不适用于多线程代码! Mutex<T>
是RefCell<T>
的线程安全版本,我们将在第 16 章讨论Mutex<T>
。
Reference Cycles Can Leak Memory
引用循环可能会泄漏内存
Rust’s memory safety guarantees make it difficult, but not impossible, to
accidentally create memory that is never cleaned up (known as a memory leak).
Preventing memory leaks entirely is not one of Rust’s guarantees, meaning
memory leaks are memory safe in Rust. We can see that Rust allows memory leaks
by using Rc<T>
and RefCell<T>
: it’s possible to create references where
items refer to each other in a cycle. This creates memory leaks because the
reference count of each item in the cycle will never reach 0, and the values
will never be dropped.
Rust 的内存安全保证使得意外创建从未清理过的内存(称为内存泄漏)变得困难,但并非不可能。完全防止内存泄漏并不是 Rust 的保证之一,这意味着内存泄漏在 Rust 中是内存安全的。我们可以看到,Rust 通过使用Rc<T>
和RefCell<T>
允许内存泄漏:可以创建项目在循环中相互引用的引用。这会造成内存泄漏,因为循环中每个项目的引用计数永远不会达到 0,并且值永远不会被删除。
Creating a Reference Cycle
创建参考循环
Let’s look at how a reference cycle might happen and how to prevent it,
starting with the definition of the List
enum and a tail
method in Listing
15-25:
让我们从清单 15-25 中List
枚举和tail
方法的定义开始,看看引用循环是如何发生的以及如何防止它:
Filename: src/main.rs 文件名:src/main.rs
use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
enum List {
Cons(i32, RefCell<Rc<List>>),
Nil,
}
impl List {
fn tail(&self) -> Option<&RefCell<Rc<List>>> {
match self {
Cons(_, item) => Some(item),
Nil => None,
}
}
}
fn main() {}
We’re using another variation of the List
definition from Listing 15-5. The
second element in the Cons
variant is now RefCell<Rc<List>>
, meaning that
instead of having the ability to modify the i32
value as we did in Listing
15-24, we want to modify the List
value a Cons
variant is pointing to.
We’re also adding a tail
method to make it convenient for us to access the
second item if we have a Cons
variant.
我们使用清单 15-5 中List
定义的另一种变体。 Cons
变体中的第二个元素现在是RefCell<Rc<List>>
,这意味着我们不想像清单 15-24 中那样修改i32
值,而是希望将List
值修改为Cons
变体正在指向。我们还添加了一个tail
方法,以便在有Cons
变体时方便我们访问第二个项目。
In Listing 15-26, we’re adding a main
function that uses the definitions in
Listing 15-25. This code creates a list in a
and a list in b
that points to
the list in a
. Then it modifies the list in a
to point to b
, creating a
reference cycle. There are println!
statements along the way to show what the
reference counts are at various points in this process.
在清单 15-26 中,我们添加了一个使用清单 15-25 中的定义的main
函数。此代码在a
中创建一个列表,并在b
中创建一个指向a
中列表的列表。然后它修改a
中的列表以指向b
,创建一个引用循环。有println!
沿途的语句来显示在此过程中各个点的引用计数。
Filename: src/main.rs 文件名:src/main.rs
We create an Rc<List>
instance holding a List
value in the variable a
with an initial list of 5, Nil
. We then create an Rc<List>
instance holding
another List
value in the variable b
that contains the value 10 and points
to the list in a
.
我们创建一个Rc<List>
实例,在变量a
中保存一个List
值,初始列表为5, Nil
。然后,我们创建一个Rc<List>
实例,在变量b
中保存另一个List
值,该值包含值 10 并指向a
中的列表。
We modify a
so it points to b
instead of Nil
, creating a cycle. We do
that by using the tail
method to get a reference to the RefCell<Rc<List>>
in a
, which we put in the variable link
. Then we use the borrow_mut
method on the RefCell<Rc<List>>
to change the value inside from an Rc<List>
that holds a Nil
value to the Rc<List>
in b
.
我们修改a
使其指向b
而不是Nil
,从而创建一个循环。为此,我们使用tail
方法获取a
中对RefCell<Rc<List>>
的引用,并将其放入变量link
中。然后,我们对RefCell<Rc<List>>
使用borrow_mut
方法,将内部的值从保存Nil
值的Rc<List>
更改为b
中的Rc<List>
。
When we run this code, keeping the last println!
commented out for the
moment, we’ll get this output:
当我们运行这段代码时,保留最后的println!
暂时注释掉,我们将得到以下输出:
$ 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
The reference count of the Rc<List>
instances in both a
and b
are 2 after
we change the list in a
to point to b
. At the end of main
, Rust drops the
variable b
, which decreases the reference count of the b
Rc<List>
instance
from 2 to 1. The memory that Rc<List>
has on the heap won’t be dropped at
this point, because its reference count is 1, not 0. Then Rust drops a
, which
decreases the reference count of the a
Rc<List>
instance from 2 to 1 as
well. This instance’s memory can’t be dropped either, because the other
Rc<List>
instance still refers to it. The memory allocated to the list will
remain uncollected forever. To visualize this reference cycle, we’ve created a
diagram in Figure 15-4.
当我们将a
中的列表更改为指向b
后, a
和b
中的Rc<List>
实例的引用计数均为 2。在main
的末尾,Rust 删除了变量b
,这将b
Rc<List>
实例的引用计数从 2 减少到 1。 Rc<List>
在堆上的内存此时不会被删除点,因为它的引用计数是 1,而不是 0。然后 Rust 删除a
,这也会将a
Rc<List>
实例的引用计数从 2 减少到 1。该实例的内存也无法删除,因为另一个Rc<List>
实例仍然引用它。分配给列表的内存将永远保持未回收状态。为了形象化这个引用循环,我们创建了一个图,如图 15-4 所示。
If you uncomment the last println!
and run the program, Rust will try to
print this cycle with a
pointing to b
pointing to a
and so forth until it
overflows the stack.
如果取消最后一个println!
注释并运行程序,Rust 将尝试打印此循环,其中a
指向b
指向a
等等,直到溢出堆栈。
Compared to a real-world program, the consequences of creating a reference cycle
in this example aren’t very dire: right after we create the reference cycle,
the program ends. However, if a more complex program allocated lots of memory
in a cycle and held onto it for a long time, the program would use more memory
than it needed and might overwhelm the system, causing it to run out of
available memory.
与现实世界的程序相比,在这个例子中创建引用循环的后果并不是很可怕:在我们创建引用循环之后,程序就结束了。但是,如果更复杂的程序在一个周期中分配大量内存并长时间保留它,则该程序将使用超出其所需的内存,并可能压垮系统,导致可用内存耗尽。
Creating reference cycles is not easily done, but it’s not impossible either.
If you have RefCell<T>
values that contain Rc<T>
values or similar nested
combinations of types with interior mutability and reference counting, you must
ensure that you don’t create cycles; you can’t rely on Rust to catch them.
Creating a reference cycle would be a logic bug in your program that you should
use automated tests, code reviews, and other software development practices to
minimize.
创建参考循环并不容易,但也不是不可能。如果您的RefCell<T>
值包含Rc<T>
值或具有内部可变性和引用计数的类似嵌套类型组合,则必须确保不会创建循环;你不能依靠 Rust 来捕获它们。创建引用循环将是程序中的逻辑错误,您应该使用自动化测试、代码审查和其他软件开发实践来最大程度地减少该错误。
Another solution for avoiding reference cycles is reorganizing your data
structures so that some references express ownership and some references don’t.
As a result, you can have cycles made up of some ownership relationships and
some non-ownership relationships, and only the ownership relationships affect
whether or not a value can be dropped. In Listing 15-25, we always want Cons
variants to own their list, so reorganizing the data structure isn’t possible.
Let’s look at an example using graphs made up of parent nodes and child nodes
to see when non-ownership relationships are an appropriate way to prevent
reference cycles.
避免引用循环的另一个解决方案是重新组织数据结构,以便某些引用表示所有权,而某些引用则不表示所有权。因此,您可以拥有由一些所有权关系和一些非所有权关系组成的循环,并且只有所有权关系会影响是否可以删除值。在清单 15-25 中,我们总是希望Cons
变体拥有自己的列表,因此重新组织数据结构是不可能的。让我们看一个使用由父节点和子节点组成的图的示例,看看非所有权关系何时是防止引用循环的适当方法。
Preventing Reference Cycles: Turning an Rc<T>
into a Weak<T>
防止引用循环:将Rc<T>
转变为Weak<T>
So far, we’ve demonstrated that calling Rc::clone
increases the
strong_count
of an Rc<T>
instance, and an Rc<T>
instance is only cleaned
up if its strong_count
is 0. You can also create a weak reference to the
value within an Rc<T>
instance by calling Rc::downgrade
and passing a
reference to the Rc<T>
. Strong references are how you can share ownership of
an Rc<T>
instance. Weak references don’t express an ownership relationship,
and their count doesn’t affect when an Rc<T>
instance is cleaned up. They
won’t cause a reference cycle because any cycle involving some weak references
will be broken once the strong reference count of values involved is 0.
到目前为止,我们已经演示了调用Rc::clone
会增加Rc<T>
实例的strong_count
,并且Rc<T>
实例仅在其strong_count
为 0 时才会被清理。您还可以创建弱引用通过调用Rc::downgrade
并将引用传递给 Rc Rc<T>
Rc<T>
实例中的值。强引用是您如何共享Rc<T>
实例的所有权。弱引用不表示所有权关系,并且它们的计数不会影响清理Rc<T>
实例的时间。它们不会导致引用循环,因为一旦涉及的值的强引用计数为 0,任何涉及弱引用的循环都会被破坏。
When you call Rc::downgrade
, you get a smart pointer of type Weak<T>
.
Instead of increasing the strong_count
in the Rc<T>
instance by 1, calling
Rc::downgrade
increases the weak_count
by 1. The Rc<T>
type uses
weak_count
to keep track of how many Weak<T>
references exist, similar to
strong_count
. The difference is the weak_count
doesn’t need to be 0 for the
Rc<T>
instance to be cleaned up.
当您调用Rc::downgrade
时,您会得到一个Weak<T>
类型的智能指针。调用Rc::downgrade
不是将Rc<T>
实例中的strong_count
增加 1,而是将weak_count
增加1。Rc Rc<T>
类型使用weak_count
来跟踪存在多少个Weak<T>
引用,类似于strong_count
。不同之处在于,要清理Rc<T>
实例, weak_count
不需要为 0。
Because the value that Weak<T>
references might have been dropped, to do
anything with the value that a Weak<T>
is pointing to, you must make sure the
value still exists. Do this by calling the upgrade
method on a Weak<T>
instance, which will return an Option<Rc<T>>
. You’ll get a result of Some
if the Rc<T>
value has not been dropped yet and a result of None
if the
Rc<T>
value has been dropped. Because upgrade
returns an Option<Rc<T>>
,
Rust will ensure that the Some
case and the None
case are handled, and
there won’t be an invalid pointer.
由于Weak<T>
引用的值可能已被删除,因此要对Weak<T>
指向的值执行任何操作,必须确保该值仍然存在。通过在Weak<T>
实例上调用upgrade
方法来执行此操作,该方法将返回Option<Rc<T>>
。如果尚未删除Rc<T>
值,您将得到Some
结果;如果Rc<T>
值已被删除,您将得到None
结果。因为upgrade
返回Option<Rc<T>>
,Rust 将确保处理Some
情况和None
情况,并且不会出现无效指针。
As an example, rather than using a list whose items know only about the next
item, we’ll create a tree whose items know about their children items and
their parent items.
例如,我们将创建一个树,其中的项目了解其子项目和父项目,而不是使用其项目仅了解下一个项目的列表。
Creating a Tree Data Structure: a Node
with Child Nodes
创建树数据结构:具有子节点的Node
To start, we’ll build a tree with nodes that know about their child nodes.
We’ll create a struct named Node
that holds its own i32
value as well as
references to its children Node
values:
首先,我们将构建一棵树,其中的节点了解其子节点。我们将创建一个名为Node
结构体,它保存自己的i32
值以及对其子Node
值的引用:
Filename: src/main.rs 文件名:src/main.rs
We want a Node
to own its children, and we want to share that ownership with
variables so we can access each Node
in the tree directly. To do this, we
define the Vec<T>
items to be values of type Rc<Node>
. We also want to
modify which nodes are children of another node, so we have a RefCell<T>
in
children
around the Vec<Rc<Node>>
.
我们希望一个Node
拥有它的子节点,并且我们希望与变量共享该所有权,以便我们可以直接访问树中的每个Node
。为此,我们将Vec<T>
项定义为Rc<Node>
类型的值。我们还想修改哪些节点是另一个节点的子节点,因此我们在Vec<Rc<Node>>
周围的children
中有一个RefCell<T>
。
Next, we’ll use our struct definition and create one Node
instance named
leaf
with the value 3 and no children, and another instance named branch
with the value 5 and leaf
as one of its children, as shown in Listing 15-27:
接下来,我们将使用结构体定义创建一个名为leaf
的Node
实例,其值为 3,没有子节点,以及另一个名为branch
的实例,其值为 5,并且leaf
作为其子节点之一,如清单 15-27 所示:
Filename: src/main.rs 文件名:src/main.rs
We clone the Rc<Node>
in leaf
and store that in branch
, meaning the
Node
in leaf
now has two owners: leaf
and branch
. We can get from
branch
to leaf
through branch.children
, but there’s no way to get from
leaf
to branch
. The reason is that leaf
has no reference to branch
and
doesn’t know they’re related. We want leaf
to know that branch
is its
parent. We’ll do that next.
我们克隆leaf
中的Rc<Node>
并将其存储在branch
中,这意味着leaf
中的Node
现在有两个所有者: leaf
和branch
。我们可以通过branch.children
从branch
到leaf
,但是没有办法从leaf
到branch
。原因是leaf
没有引用branch
并且不知道它们是相关的。我们希望leaf
知道branch
是它的父代。我们接下来就这样做。
Adding a Reference from a Child to Its Parent
添加从子级到父级的引用
To make the child node aware of its parent, we need to add a parent
field to
our Node
struct definition. The trouble is in deciding what the type of
parent
should be. We know it can’t contain an Rc<T>
, because that would
create a reference cycle with leaf.parent
pointing to branch
and
branch.children
pointing to leaf
, which would cause their strong_count
values to never be 0.
为了让子节点知道它的父节点,我们需要在Node
结构定义中添加一个parent
字段。问题在于决定parent
应该是什么类型。我们知道它不能包含Rc<T>
,因为这会创建一个引用循环,其中leaf.parent
指向branch
, branch.children
指向leaf
,这将导致它们的strong_count
值永远不会为 0。
Thinking about the relationships another way, a parent node should own its
children: if a parent node is dropped, its child nodes should be dropped as
well. However, a child should not own its parent: if we drop a child node, the
parent should still exist. This is a case for weak references!
从另一种角度考虑关系,父节点应该拥有它的子节点:如果父节点被删除,它的子节点也应该被删除。但是,子节点不应该拥有其父节点:如果我们删除子节点,父节点应该仍然存在。这是弱引用的情况!
So instead of Rc<T>
, we’ll make the type of parent
use Weak<T>
,
specifically a RefCell<Weak<Node>>
. Now our Node
struct definition looks
like this:
因此, parent
将使用Weak<T>
Rc<T>
3CT> ,特别是RefCell<Weak<Node>>
。现在我们的Node
结构定义如下所示:
Filename: src/main.rs 文件名:src/main.rs
A node will be able to refer to its parent node but doesn’t own its parent.
In Listing 15-28, we update main
to use this new definition so the leaf
node will have a way to refer to its parent, branch
:
节点将能够引用其父节点,但不拥有其父节点。在清单 15-28 中,我们更新了main
以使用这个新定义,这样leaf
节点将有一种方法来引用它的父branch
:
Filename: src/main.rs 文件名:src/main.rs
Creating the leaf
node looks similar to Listing 15-27 with the exception of
the parent
field: leaf
starts out without a parent, so we create a new,
empty Weak<Node>
reference instance.
创建leaf
节点看起来与清单 15-27 类似,但parent
字段除外: leaf
一开始没有父节点,因此我们创建一个新的空Weak<Node>
引用实例。
At this point, when we try to get a reference to the parent of leaf
by using
the upgrade
method, we get a None
value. We see this in the output from the
first println!
statement:
此时,当我们尝试使用upgrade
方法获取对leaf
的父级的引用时,我们得到None
值。我们在第一个println!
陈述:
leaf parent = None
When we create the branch
node, it will also have a new Weak<Node>
reference in the parent
field, because branch
doesn’t have a parent node.
We still have leaf
as one of the children of branch
. Once we have the
Node
instance in branch
, we can modify leaf
to give it a Weak<Node>
reference to its parent. We use the borrow_mut
method on the
RefCell<Weak<Node>>
in the parent
field of leaf
, and then we use the
Rc::downgrade
function to create a Weak<Node>
reference to branch
from
the Rc<Node>
in branch.
当我们创建branch
节点时,它的parent
字段中也会有一个新的Weak<Node>
引用,因为branch
没有父节点。我们仍然有leaf
作为branch
的子级之一。一旦我们在branch
中拥有了Node
实例,我们就可以修改leaf
以给它一个对其父级的Weak<Node>
引用。我们对leaf
的parent
字段中的RefCell<Weak<Node>>
使用borrow_mut
方法,然后使用Rc::downgrade
函数从Rc<Node>
创建对branch
的Weak<Node>
引用Rc<Node>
branch.
When we print the parent of leaf
again, this time we’ll get a Some
variant
holding branch
: now leaf
can access its parent! When we print leaf
, we
also avoid the cycle that eventually ended in a stack overflow like we had in
Listing 15-26; the Weak<Node>
references are printed as (Weak)
:
当我们再次打印leaf
的父级时,这一次我们将得到一个Some
变体,其中包含branch
:现在leaf
可以访问其父级!当我们打印leaf
时,我们还避免了最终以堆栈溢出结束的循环,如清单 15-26 所示; Weak<Node>
引用打印为(Weak)
:
leaf parent = Some(Node { value: 5, parent: RefCell { value: (Weak) },
children: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) },
children: RefCell { value: [] } }] } })
The lack of infinite output indicates that this code didn’t create a reference
cycle. We can also tell this by looking at the values we get from calling
Rc::strong_count
and Rc::weak_count
.
缺少无限输出表明该代码没有创建引用循环。我们还可以通过查看调用Rc::strong_count
和Rc::weak_count
获得的值来判断这一点。
Visualizing Changes to strong_count
and weak_count
可视化strong_count
和weak_count
的变化
Let’s look at how the strong_count
and weak_count
values of the Rc<Node>
instances change by creating a new inner scope and moving the creation of
branch
into that scope. By doing so, we can see what happens when branch
is
created and then dropped when it goes out of scope. The modifications are shown
in Listing 15-29:
让我们看看通过创建新的内部作用域并将branch
的创建移动到该作用域中, Rc<Node>
实例的strong_count
和weak_count
值如何变化。通过这样做,我们可以看到创建branch
并在超出范围时删除分支时会发生什么。修改如清单 15-29 所示:
Filename: src/main.rs 文件名:src/main.rs
After leaf
is created, its Rc<Node>
has a strong count of 1 and a weak
count of 0. In the inner scope, we create branch
and associate it with
leaf
, at which point when we print the counts, the Rc<Node>
in branch
will have a strong count of 1 and a weak count of 1 (for leaf.parent
pointing
to branch
with a Weak<Node>
). When we print the counts in leaf
, we’ll see
it will have a strong count of 2, because branch
now has a clone of the
Rc<Node>
of leaf
stored in branch.children
, but will still have a weak
count of 0.
创建leaf
后,其Rc<Node>
的强计数为 1,弱计数为 0。在内部作用域中,我们创建branch
并将其与leaf
关联,此时当我们打印计数时, Rc<Node>
branch
中的Rc<Node>
的强计数为 1,弱计数为 1(对于leaf.parent
指向带有Weak<Node>
branch
)。当我们打印leaf
中的计数时,我们会看到它的强计数为 2,因为branch
现在有存储在branch.children
中的leaf
的Rc<Node>
的克隆,但仍然会有弱计数 2 0。
When the inner scope ends, branch
goes out of scope and the strong count of
the Rc<Node>
decreases to 0, so its Node
is dropped. The weak count of 1
from leaf.parent
has no bearing on whether or not Node
is dropped, so we
don’t get any memory leaks!
当内部作用域结束时, branch
超出作用域,并且Rc<Node>
的强计数减少到 0,因此它的Node
被删除。 leaf.parent
的弱计数 1 与Node
是否被删除无关,因此我们不会出现任何内存泄漏!
If we try to access the parent of leaf
after the end of the scope, we’ll get
None
again. At the end of the program, the Rc<Node>
in leaf
has a strong
count of 1 and a weak count of 0, because the variable leaf
is now the only
reference to the Rc<Node>
again.
如果我们尝试在作用域结束后访问leaf
的父级,我们将再次得到None
。在程序结束时, leaf
中的Rc<Node>
的强计数为 1,弱计数为 0,因为变量leaf
现在再次成为对Rc<Node>
的唯一引用。
All of the logic that manages the counts and value dropping is built into
Rc<T>
and Weak<T>
and their implementations of the Drop
trait. By
specifying that the relationship from a child to its parent should be a
Weak<T>
reference in the definition of Node
, you’re able to have parent
nodes point to child nodes and vice versa without creating a reference cycle
and memory leaks.
管理计数和值删除的所有逻辑都内置于Rc<T>
和Weak<T>
及其Drop
特征的实现中。通过在Node
的定义中指定子节点与其父节点的关系应该是Weak<T>
引用,您可以让父节点指向子节点,反之亦然,而不会创建引用循环和内存泄漏。
Summary 概括
This chapter covered how to use smart pointers to make different guarantees and
trade-offs from those Rust makes by default with regular references. The
Box<T>
type has a known size and points to data allocated on the heap. The
Rc<T>
type keeps track of the number of references to data on the heap so
that data can have multiple owners. The RefCell<T>
type with its interior
mutability gives us a type that we can use when we need an immutable type but
need to change an inner value of that type; it also enforces the borrowing
rules at runtime instead of at compile time.
本章介绍了如何使用智能指针来做出与 Rust 默认情况下使用常规引用所做的不同的保证和权衡。 Box<T>
类型具有已知大小并指向堆上分配的数据。 Rc<T>
类型跟踪堆上数据的引用次数,以便数据可以拥有多个所有者。 RefCell<T>
类型及其内部可变性为我们提供了一种类型,当我们需要不可变类型但需要更改该类型的内部值时可以使用该类型;它还在运行时而不是在编译时强制执行借用规则。
Also discussed were the Deref
and Drop
traits, which enable a lot of the
functionality of smart pointers. We explored reference cycles that can cause
memory leaks and how to prevent them using Weak<T>
.
还讨论了Deref
和Drop
特征,它们启用了智能指针的许多功能。我们探讨了可能导致内存泄漏的引用循环以及如何使用Weak<T>
来防止它们。
If this chapter has piqued your interest and you want to implement your own
smart pointers, check out “The Rustonomicon” for more useful
information.
如果本章激起了您的兴趣并且您想实现自己的智能指针,请查看“The Rustonomicon”以获取更多有用的信息。
Next, we’ll talk about concurrency in Rust. You’ll even learn about a few new
smart pointers.
接下来,我们将讨论 Rust 中的并发。您甚至会了解一些新的智能指针。
Fearless Concurrency 无畏并发
Handling concurrent programming safely and efficiently is another of Rust’s
major goals. Concurrent programming, where different parts of a program
execute independently, and parallel programming, where different parts of a
program execute at the same time, are becoming increasingly important as more
computers take advantage of their multiple processors. Historically,
programming in these contexts has been difficult and error prone: Rust hopes to
change that.
安全高效地处理并发编程是 Rust 的另一个主要目标。随着越来越多的计算机利用其多个处理器,并发编程(程序的不同部分独立执行)和并行编程(程序的不同部分同时执行)变得越来越重要。从历史上看,在这些环境中编程一直是困难且容易出错的:Rust 希望改变这一点。
Initially, the Rust team thought that ensuring memory safety and preventing
concurrency problems were two separate challenges to be solved with different
methods. Over time, the team discovered that the ownership and type systems are
a powerful set of tools to help manage memory safety and concurrency
problems! By leveraging ownership and type checking, many concurrency errors
are compile-time errors in Rust rather than runtime errors. Therefore, rather
than making you spend lots of time trying to reproduce the exact circumstances
under which a runtime concurrency bug occurs, incorrect code will refuse to
compile and present an error explaining the problem. As a result, you can fix
your code while you’re working on it rather than potentially after it has been
shipped to production. We’ve nicknamed this aspect of Rust fearless
concurrency. Fearless concurrency allows you to write code that is free of
subtle bugs and is easy to refactor without introducing new bugs.
最初,Rust 团队认为确保内存安全和防止并发问题是两个独立的挑战,需要用不同的方法来解决。随着时间的推移,团队发现所有权和类型系统是一组强大的工具,可以帮助管理内存安全和并发问题!通过利用所有权和类型检查,许多并发错误是 Rust 中的编译时错误,而不是运行时错误。因此,不正确的代码将拒绝编译并显示解释问题的错误,而不是让您花费大量时间尝试重现发生运行时并发错误的确切情况。因此,您可以在处理代码时修复代码,而不是在将代码交付生产后修复。我们将 Rust无畏并发的这一方面称为“无所畏惧的并发” 。无畏并发允许您编写没有细微错误的代码,并且易于重构而不会引入新的错误。
Note: For simplicity’s sake, we’ll refer to many of the problems as
concurrent rather than being more precise by saying concurrent and/or
parallel. If this book were about concurrency and/or parallelism, we’d be
more specific. For this chapter, please mentally substitute concurrent
and/or parallel whenever we use concurrent.
注意:为了简单起见,我们将许多问题称为并发问题,而不是通过说并发和/或并行来更精确。如果这本书是关于并发和/或并行性的,我们会更具体。在本章中,每当我们使用并发时,请在心里用并发和/或并行代替。
Many languages are dogmatic about the solutions they offer for handling
concurrent problems. For example, Erlang has elegant functionality for
message-passing concurrency but has only obscure ways to share state between
threads. Supporting only a subset of possible solutions is a reasonable
strategy for higher-level languages, because a higher-level language promises
benefits from giving up some control to gain abstractions. However, lower-level
languages are expected to provide the solution with the best performance in any
given situation and have fewer abstractions over the hardware. Therefore, Rust
offers a variety of tools for modeling problems in whatever way is appropriate
for your situation and requirements.
许多语言对于它们为处理并发问题提供的解决方案都是教条的。例如,Erlang 具有优雅的消息传递并发功能,但在线程之间共享状态的方式却很晦涩。对于高级语言来说,仅支持可能解决方案的子集是一个合理的策略,因为高级语言承诺通过放弃某些控制来获得抽象而带来好处。然而,较低级语言有望在任何给定情况下提供最佳性能的解决方案,并且对硬件的抽象较少。因此,Rust 提供了各种工具来以适合您的情况和要求的方式对问题进行建模。
Here are the topics we’ll cover in this chapter:
以下是我们将在本章中讨论的主题:
- How to create threads to run multiple pieces of code at the same time
如何创建线程同时运行多段代码 - Message-passing concurrency, where channels send messages between threads
消息传递并发,通道在线程之间发送消息 - Shared-state concurrency, where multiple threads have access to some piece
of data
共享状态并发,多个线程可以访问某些数据 - The
Sync
andSend
traits, which extend Rust’s concurrency guarantees to user-defined types as well as types provided by the standard librarySync
和Send
特征,将 Rust 的并发保证扩展到用户定义的类型以及标准库提供的类型
Using Threads to Run Code Simultaneously
使用线程同时运行代码
In most current operating systems, an executed program’s code is run in a
process, and the operating system will manage multiple processes at once.
Within a program, you can also have independent parts that run simultaneously.
The features that run these independent parts are called threads. For
example, a web server could have multiple threads so that it could respond to
more than one request at the same time.
在大多数当前的操作系统中,执行程序的代码在进程中运行,并且操作系统将同时管理多个进程。在程序中,您还可以拥有同时运行的独立部分。运行这些独立部分的功能称为线程。例如,一台 Web 服务器可以有多个线程,以便它可以同时响应多个请求。
Splitting the computation in your program into multiple threads to run multiple
tasks at the same time can improve performance, but it also adds complexity.
Because threads can run simultaneously, there’s no inherent guarantee about the
order in which parts of your code on different threads will run. This can lead
to problems, such as:
将程序中的计算拆分为多个线程以同时运行多个任务可以提高性能,但也会增加复杂性。由于线程可以同时运行,因此对于不同线程上的代码部分的运行顺序没有固有的保证。这可能会导致问题,例如:
- Race conditions, where threads are accessing data or resources in an
inconsistent order
竞争条件,线程以不一致的顺序访问数据或资源 - Deadlocks, where two threads are waiting for each other, preventing both
threads from continuing
死锁,两个线程互相等待,阻止两个线程继续运行 - Bugs that happen only in certain situations and are hard to reproduce and fix
reliably
仅在某些情况下发生且难以可靠地重现和修复的错误
Rust attempts to mitigate the negative effects of using threads, but
programming in a multithreaded context still takes careful thought and requires
a code structure that is different from that in programs running in a single
thread.
Rust 试图减轻使用线程的负面影响,但在多线程上下文中编程仍然需要仔细考虑,并且需要与在单线程中运行的程序不同的代码结构。
Programming languages implement threads in a few different ways, and many
operating systems provide an API the language can call for creating new
threads. The Rust standard library uses a 1:1 model of thread implementation,
whereby a program uses one operating system thread per one language thread.
There are crates that implement other models of threading that make different
tradeoffs to the 1:1 model.
编程语言以几种不同的方式实现线程,许多操作系统提供了一个 API,该语言可以调用该 API 来创建新线程。 Rust 标准库使用1:1的线程实现模型,即程序针对一种语言线程使用一个操作系统线程。有些包实现了其他线程模型,对 1:1 模型进行了不同的权衡。
Creating a New Thread with spawn
使用spawn
创建一个新线程
To create a new thread, we call the thread::spawn
function and pass it a
closure (we talked about closures in Chapter 13) containing the code we want to
run in the new thread. The example in Listing 16-1 prints some text from a main
thread and other text from a new thread:
为了创建一个新线程,我们调用thread::spawn
函数并向它传递一个闭包(我们在第 13 章中讨论过闭包),其中包含我们想要在新线程中运行的代码。清单 16-1 中的示例从主线程打印一些文本,从新线程打印其他文本:
Filename: src/main.rs 文件名:src/main.rs
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));
}
}
Note that when the main thread of a Rust program completes, all spawned threads
are shut down, whether or not they have finished running. The output from this
program might be a little different every time, but it will look similar to the
following:
请注意,当 Rust 程序的主线程完成时,所有生成的线程都会关闭,无论它们是否已完成运行。该程序的输出每次可能略有不同,但看起来类似于以下内容:
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!
The calls to thread::sleep
force a thread to stop its execution for a short
duration, allowing a different thread to run. The threads will probably take
turns, but that isn’t guaranteed: it depends on how your operating system
schedules the threads. In this run, the main thread printed first, even though
the print statement from the spawned thread appears first in the code. And even
though we told the spawned thread to print until i
is 9, it only got to 5
before the main thread shut down.
对thread::sleep
调用会强制线程在短时间内停止执行,从而允许另一个线程运行。线程可能会轮流运行,但这并不能保证:这取决于操作系统如何调度线程。在此运行中,主线程首先打印,即使来自生成线程的打印语句首先出现在代码中。即使我们告诉生成的线程打印直到i
为 9,但在主线程关闭之前它只达到了 5。
If you run this code and only see output from the main thread, or don’t see any
overlap, try increasing the numbers in the ranges to create more opportunities
for the operating system to switch between the threads.
如果运行此代码并且只看到主线程的输出,或者没有看到任何重叠,请尝试增加范围中的数字,以便为操作系统在线程之间切换创造更多机会。
Waiting for All Threads to Finish Using join
Handles
使用join
句柄等待所有线程完成
The code in Listing 16-1 not only stops the spawned thread prematurely most of
the time due to the main thread ending, but because there is no guarantee on
the order in which threads run, we also can’t guarantee that the spawned thread
will get to run at all!
清单16-1中的代码不仅在大多数情况下会因主线程结束而提前停止生成的线程,而且由于无法保证线程运行的顺序,我们也无法保证生成的线程会快跑吧!
We can fix the problem of the spawned thread not running or ending prematurely
by saving the return value of thread::spawn
in a variable. The return type of
thread::spawn
is JoinHandle
. A JoinHandle
is an owned value that, when we
call the join
method on it, will wait for its thread to finish. Listing 16-2
shows how to use the JoinHandle
of the thread we created in Listing 16-1 and
call join
to make sure the spawned thread finishes before main
exits:
我们可以通过将thread::spawn
的返回值保存在变量中来解决生成的线程未运行或提前结束的问题。 thread::spawn
的返回类型是JoinHandle
。 JoinHandle
是一个拥有的值,当我们对其调用join
方法时,它将等待其线程完成。清单 16-2 显示了如何使用我们在清单 16-1 中创建的线程的JoinHandle
并调用join
以确保生成的线程在main
退出之前完成:
Filename: src/main.rs 文件名:src/main.rs
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();
}
Calling join
on the handle blocks the thread currently running until the
thread represented by the handle terminates. Blocking a thread means that
thread is prevented from performing work or exiting. Because we’ve put the call
to join
after the main thread’s for
loop, running Listing 16-2 should
produce output similar to this:
对句柄调用join
会阻塞当前正在运行的线程,直到句柄所代表的线程终止。阻塞线程意味着阻止线程执行工作或退出。因为我们将对join
的调用放在主线程的for
循环之后,所以运行清单 16-2 应该会产生与此类似的输出:
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!
The two threads continue alternating, but the main thread waits because of the
call to handle.join()
and does not end until the spawned thread is finished.
两个线程继续交替,但主线程因调用handle.join()
而等待,直到生成的线程完成为止。
But let’s see what happens when we instead move handle.join()
before the
for
loop in main
, like this:
但是让我们看看当我们将handle.join()
移到main
中的for
循环之前会发生什么,如下所示:
Filename: src/main.rs 文件名:src/main.rs
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));
}
}
The main thread will wait for the spawned thread to finish and then run its
for
loop, so the output won’t be interleaved anymore, as shown here:
主线程将等待生成的线程完成,然后运行其for
循环,因此输出将不再交错,如下所示:
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!
Small details, such as where join
is called, can affect whether or not your
threads run at the same time.
小细节(例如调用join
位置)可能会影响线程是否同时运行。
Using move
Closures with Threads
move
闭包与线程结合使用
We’ll often use the move
keyword with closures passed to thread::spawn
because the closure will then take ownership of the values it uses from the
environment, thus transferring ownership of those values from one thread to
another. In the “Capturing References or Moving Ownership” section of Chapter 13, we discussed move
in the context of closures. Now,
we’ll concentrate more on the interaction between move
and thread::spawn
.
我们经常将move
关键字与传递给thread::spawn
闭包一起使用,因为闭包随后将从环境中获取它使用的值的所有权,从而将这些值的所有权从一个线程转移到另一个线程。在第 13 章的“捕获引用或移动所有权”忽略部分中,我们讨论了闭包背景下的move
。现在,我们将更多地关注move
和thread::spawn
之间的交互。
Notice in Listing 16-1 that the closure we pass to thread::spawn
takes no
arguments: we’re not using any data from the main thread in the spawned
thread’s code. To use data from the main thread in the spawned thread, the
spawned thread’s closure must capture the values it needs. Listing 16-3 shows
an attempt to create a vector in the main thread and use it in the spawned
thread. However, this won’t yet work, as you’ll see in a moment.
请注意,在清单 16-1 中,我们传递给thread::spawn
闭包不带任何参数:我们没有在生成线程的代码中使用来自主线程的任何数据。要在生成的线程中使用来自主线程的数据,生成的线程的闭包必须捕获它所需的值。清单 16-3 显示了在主线程中创建向量并在派生线程中使用它的尝试。然而,这还行不通,稍后您就会看到。
Filename: src/main.rs 文件名:src/main.rs
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("Here's a vector: {v:?}");
});
handle.join().unwrap();
}
The closure uses v
, so it will capture v
and make it part of the closure’s
environment. Because thread::spawn
runs this closure in a new thread, we
should be able to access v
inside that new thread. But when we compile this
example, we get the following error:
闭包使用v
,因此它将捕获v
并使其成为闭包环境的一部分。因为thread::spawn
在新线程中运行此闭包,所以我们应该能够在该新线程中访问v
。但是当我们编译这个例子时,我们得到以下错误:
$ 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
--> 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`
--> 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
Rust infers how to capture v
, and because println!
only needs a reference
to v
, the closure tries to borrow v
. However, there’s a problem: Rust can’t
tell how long the spawned thread will run, so it doesn’t know if the reference
to v
will always be valid.
Rust推断如何捕获v
,因为println!
只需要对v
引用,闭包会尝试借用v
。然而,有一个问题:Rust 无法判断生成的线程将运行多长时间,因此它不知道对v
引用是否始终有效。
Listing 16-4 provides a scenario that’s more likely to have a reference to v
that won’t be valid:
清单 16-4 提供了一个更有可能引用无效v
的场景:
Filename: src/main.rs 文件名:src/main.rs
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();
}
If Rust allowed us to run this code, there’s a possibility the spawned thread
would be immediately put in the background without running at all. The spawned
thread has a reference to v
inside, but the main thread immediately drops
v
, using the drop
function we discussed in Chapter 15. Then, when the
spawned thread starts to execute, v
is no longer valid, so a reference to it
is also invalid. Oh no!
如果 Rust 允许我们运行这段代码,那么生成的线程有可能会立即放入后台而不运行。生成的线程内部有对v
的引用,但主线程立即使用我们在第 15 章中讨论的drop
函数删除v
。然后,当生成的线程开始执行时, v
不再有效,因此对它的引用是也无效。哦不!
To fix the compiler error in Listing 16-3, we can use the error message’s
advice:
要修复清单 16-3 中的编译器错误,我们可以使用错误消息的建议:
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 || {
| ++++
By adding the move
keyword before the closure, we force the closure to take
ownership of the values it’s using rather than allowing Rust to infer that it
should borrow the values. The modification to Listing 16-3 shown in Listing
16-5 will compile and run as we intend:
通过在闭包之前添加move
关键字,我们强制闭包取得它正在使用的值的所有权,而不是让 Rust 推断它应该借用这些值。清单 16-5 中所示的对清单 16-3 的修改将按照我们的预期进行编译和运行:
Filename: src/main.rs 文件名:src/main.rs
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();
}
We might be tempted to try the same thing to fix the code in Listing 16-4 where
the main thread called drop
by using a move
closure. However, this fix will
not work because what Listing 16-4 is trying to do is disallowed for a
different reason. If we added move
to the closure, we would move v
into the
closure’s environment, and we could no longer call drop
on it in the main
thread. We would get this compiler error instead:
我们可能会尝试同样的方法来修复清单 16-4 中的代码,其中主线程通过使用move
闭包调用drop
。然而,这个修复不会起作用,因为清单 16-4 试图做的事情由于不同的原因而被禁止。如果我们将move
添加到闭包中,我们会将v
移动到闭包的环境中,并且我们无法再在主线程中对其调用drop
。我们会得到这个编译器错误:
$ cargo run
Compiling threads v0.1.0 (file:///projects/threads)
error[E0382]: use of moved value: `v`
--> src/main.rs:10:10
|
4 | let v = vec![1, 2, 3];
| - move occurs because `v` has type `Vec<i32>`, 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
Rust’s ownership rules have saved us again! We got an error from the code in
Listing 16-3 because Rust was being conservative and only borrowing v
for the
thread, which meant the main thread could theoretically invalidate the spawned
thread’s reference. By telling Rust to move ownership of v
to the spawned
thread, we’re guaranteeing Rust that the main thread won’t use v
anymore. If
we change Listing 16-4 in the same way, we’re then violating the ownership
rules when we try to use v
in the main thread. The move
keyword overrides
Rust’s conservative default of borrowing; it doesn’t let us violate the
ownership rules.
Rust 的所有权规则再次拯救了我们!我们从清单 16-3 中的代码中得到了一个错误,因为 Rust 很保守,只为线程借用v
,这意味着主线程理论上可以使生成的线程的引用无效。通过告诉 Rust 将v
的所有权移至生成的线程,我们向 Rust 保证主线程不会再使用v
。如果我们以同样的方式更改清单 16-4,那么当我们尝试在主线程中使用v
时,就会违反所有权规则。 move
关键字会覆盖 Rust 保守的默认借用方式;它不会让我们违反所有权规则。
With a basic understanding of threads and the thread API, let’s look at what we
can do with threads.
对线程和线程 API 有了基本的了解后,我们来看看可以用线程做什么。
Using Message Passing to Transfer Data Between Threads
使用消息传递在线程之间传输数据
One increasingly popular approach to ensuring safe concurrency is message
passing, where threads or actors communicate by sending each other messages
containing data. Here’s the idea in a slogan from the Go language
documentation:
“Do not communicate by sharing memory; instead, share memory by communicating.”
确保安全并发的一种日益流行的方法是消息传递,其中线程或参与者通过向彼此发送包含数据的消息来进行通信。这是Go 语言文档中的一句口号的想法:“不要通过共享内存进行通信;相反,通过交流来共享记忆。”
To accomplish message-sending concurrency, Rust’s standard library provides an
implementation of channels. A channel is a general programming concept by
which data is sent from one thread to another.
为了实现消息发送并发,Rust 的标准库提供了channels的实现。通道是一种通用编程概念,数据通过通道从一个线程发送到另一个线程。
You can imagine a channel in programming as being like a directional channel of
water, such as a stream or a river. If you put something like a rubber duck
into a river, it will travel downstream to the end of the waterway.
您可以将编程中的通道想象为定向水道,例如小溪或河流。如果你把橡皮鸭之类的东西放入河中,它会顺流而下,到达水道的尽头。
A channel has two halves: a transmitter and a receiver. The transmitter half is
the upstream location where you put rubber ducks into the river, and the
receiver half is where the rubber duck ends up downstream. One part of your
code calls methods on the transmitter with the data you want to send, and
another part checks the receiving end for arriving messages. A channel is said
to be closed if either the transmitter or receiver half is dropped.
通道有两部分:发送器和接收器。发射器的一半是您将橡皮鸭放入河中的上游位置,接收器的一半是橡皮鸭最终到达下游的位置。代码的一部分使用要发送的数据调用发送器上的方法,另一部分检查接收端是否有到达的消息。如果发送器或接收器一半掉线,则称通道已关闭。
Here, we’ll work up to a program that has one thread to generate values and
send them down a channel, and another thread that will receive the values and
print them out. We’ll be sending simple values between threads using a channel
to illustrate the feature. Once you’re familiar with the technique, you could
use channels for any threads that need to communicate between each other, such
as a chat system or a system where many threads perform parts of a calculation
and send the parts to one thread that aggregates the results.
在这里,我们将编写一个程序,该程序具有一个线程来生成值并将它们发送到通道,另一个线程将接收值并将它们打印出来。我们将使用通道在线程之间发送简单的值来说明该功能。一旦熟悉了这项技术,您就可以将通道用于任何需要相互通信的线程,例如聊天系统或许多线程执行部分计算并将这些部分发送到聚合计算的一个线程的系统。结果。
First, in Listing 16-6, we’ll create a channel but not do anything with it.
Note that this won’t compile yet because Rust can’t tell what type of values we
want to send over the channel.
首先,在清单 16-6 中,我们将创建一个通道,但不对其执行任何操作。请注意,这还无法编译,因为 Rust 无法判断我们要通过通道发送什么类型的值。
Filename: src/main.rs 文件名:src/main.rs
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
}
We create a new channel using the mpsc::channel
function; mpsc
stands for
multiple producer, single consumer. In short, the way Rust’s standard library
implements channels means a channel can have multiple sending ends that
produce values but only one receiving end that consumes those values. Imagine
multiple streams flowing together into one big river: everything sent down any
of the streams will end up in one river at the end. We’ll start with a single
producer for now, but we’ll add multiple producers when we get this example
working.
我们使用mpsc::channel
函数创建一个新通道; mpsc
代表多个生产者、单个消费者。简而言之,Rust 的标准库实现通道的方式意味着一个通道可以有多个生成值的发送端,但只有一个接收这些值的接收端。想象一下,多条溪流汇聚成一条大河:任何一条溪流流下的所有东西最终都会流入一条河流。我们现在将从单个生产者开始,但是当我们让这个示例运行时,我们将添加多个生产者。
The mpsc::channel
function returns a tuple, the first element of which is the
sending end—the transmitter—and the second element is the receiving end—the
receiver. The abbreviations tx
and rx
are traditionally used in many fields
for transmitter and receiver respectively, so we name our variables as such
to indicate each end. We’re using a let
statement with a pattern that
destructures the tuples; we’ll discuss the use of patterns in let
statements
and destructuring in Chapter 18. For now, know that using a let
statement
this way is a convenient approach to extract the pieces of the tuple returned
by mpsc::channel
.mpsc::channel
函数返回一个元组,其中第一个元素是发送端(发送器),第二个元素是接收端(接收器)。缩写tx
和rx
传统上在许多领域中分别用于发送器和接收器,因此我们这样命名变量以指示每一端。我们使用let
语句和解构元组的模式;我们将在第 18 章讨论let
语句和解构中模式的使用。现在,我们知道以这种方式使用let
语句是提取mpsc::channel
返回的元组片段的便捷方法。
Let’s move the transmitting end into a spawned thread and have it send one
string so the spawned thread is communicating with the main thread, as shown in
Listing 16-7. This is like putting a rubber duck in the river upstream or
sending a chat message from one thread to another.
让我们将发送端移至衍生线程中,并让它发送一个字符串,以便衍生线程与主线程进行通信,如清单 16-7 所示。这就像在上游河中放一只橡皮鸭或从一个线程向另一个线程发送聊天消息。
Filename: src/main.rs 文件名:src/main.rs
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();
});
}
Again, we’re using thread::spawn
to create a new thread and then using move
to move tx
into the closure so the spawned thread owns tx
. The spawned
thread needs to own the transmitter to be able to send messages through the
channel. The transmitter has a send
method that takes the value we want to
send. The send
method returns a Result<T, E>
type, so if the receiver has
already been dropped and there’s nowhere to send a value, the send operation
will return an error. In this example, we’re calling unwrap
to panic in case
of an error. But in a real application, we would handle it properly: return to
Chapter 9 to review strategies for proper error handling.
同样,我们使用thread::spawn
创建一个新线程,然后使用move
将tx
移动到闭包中,以便生成的线程拥有tx
。生成的线程需要拥有发送器才能通过通道发送消息。发送器有一个send
方法,它接受我们想要发送的值。 send
方法返回Result<T, E>
类型,因此如果接收方已被删除并且无处可发送值,则发送操作将返回错误。在此示例中,我们在发生错误时调用unwrap
来恐慌。但在实际的应用程序中,我们会正确处理它:返回第 9 章回顾正确的错误处理策略。
In Listing 16-8, we’ll get the value from the receiver in the main thread. This
is like retrieving the rubber duck from the water at the end of the river or
receiving a chat message.
在清单 16-8 中,我们将从主线程中的接收器获取值。这就像从河尾的水中取出橡皮鸭或收到聊天消息一样。
Filename: src/main.rs 文件名:src/main.rs
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}");
}
The receiver has two useful methods: recv
and try_recv
. We’re using recv
,
short for receive, which will block the main thread’s execution and wait
until a value is sent down the channel. Once a value is sent, recv
will
return it in a Result<T, E>
. When the transmitter closes, recv
will return
an error to signal that no more values will be coming.
接收器有两个有用的方法: recv
和try_recv
。我们使用recv
receive的缩写),它将阻塞主线程的执行并等待,直到一个值沿着通道发送。发送值后, recv
将在Result<T, E>
中返回该值。当发送器关闭时, recv
将返回一个错误,表示不会有更多值到来。
The try_recv
method doesn’t block, but will instead return a Result<T, E>
immediately: an Ok
value holding a message if one is available and an Err
value if there aren’t any messages this time. Using try_recv
is useful if
this thread has other work to do while waiting for messages: we could write a
loop that calls try_recv
every so often, handles a message if one is
available, and otherwise does other work for a little while until checking
again.try_recv
方法不会阻塞,而是立即返回Result<T, E>
:如果有消息可用,则返回一个包含消息的Ok
值;如果这次没有任何消息,则返回一个Err
值。如果该线程在等待消息时有其他工作要做,则使用try_recv
很有用:我们可以编写一个循环,经常调用try_recv
,如果消息可用则处理消息,否则执行其他工作一段时间,直到再次检查。
We’ve used recv
in this example for simplicity; we don’t have any other work
for the main thread to do other than wait for messages, so blocking the main
thread is appropriate.
为了简单起见,我们在这个例子中使用了recv
;除了等待消息之外,主线程没有任何其他工作要做,因此阻塞主线程是合适的。
When we run the code in Listing 16-8, we’ll see the value printed from the main
thread:
当我们运行清单 16-8 中的代码时,我们将看到从主线程打印的值:
Got: hi
Perfect! 完美的!
Channels and Ownership Transference
渠道及所有权转让
The ownership rules play a vital role in message sending because they help you
write safe, concurrent code. Preventing errors in concurrent programming is the
advantage of thinking about ownership throughout your Rust programs. Let’s do
an experiment to show how channels and ownership work together to prevent
problems: we’ll try to use a val
value in the spawned thread after we’ve
sent it down the channel. Try compiling the code in Listing 16-9 to see why
this code isn’t allowed:
所有权规则在消息发送中起着至关重要的作用,因为它们可以帮助您编写安全的并发代码。防止并发编程中的错误是考虑整个 Rust 程序的所有权的优点。让我们做一个实验来展示通道和所有权如何协同工作以防止出现问题:在将其发送到通道后,我们将尝试在生成的线程中使用val
值。尝试编译清单 16-9 中的代码,看看为什么不允许使用此代码:
Filename: src/main.rs 文件名:src/main.rs
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}");
}
Here, we try to print val
after we’ve sent it down the channel via tx.send
.
Allowing this would be a bad idea: once the value has been sent to another
thread, that thread could modify or drop it before we try to use the value
again. Potentially, the other thread’s modifications could cause errors or
unexpected results due to inconsistent or nonexistent data. However, Rust gives
us an error if we try to compile the code in Listing 16-9:
在这里,我们在通过tx.send
将 val 发送到通道后尝试打印val
。允许这样做将是一个坏主意:一旦该值被发送到另一个线程,该线程就可以在我们尝试再次使用该值之前修改或删除它。由于数据不一致或不存在,其他线程的修改可能会导致错误或意外结果。然而,如果我们尝试编译清单 16-9 中的代码,Rust 会给我们一个错误:
$ cargo run
Compiling message-passing v0.1.0 (file:///projects/message-passing)
error[E0382]: borrow of moved value: `val`
--> 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)
help: consider cloning the value if the performance cost is acceptable
|
9 | tx.send(val.clone()).unwrap();
| ++++++++
For more information about this error, try `rustc --explain E0382`.
error: could not compile `message-passing` (bin "message-passing") due to 1 previous error
Our concurrency mistake has caused a compile time error. The send
function
takes ownership of its parameter, and when the value is moved, the receiver
takes ownership of it. This stops us from accidentally using the value again
after sending it; the ownership system checks that everything is okay.
我们的并发错误导致了编译时错误。 send
函数取得其参数的所有权,当值移动时,接收者取得它的所有权。这可以防止我们在发送后意外地再次使用该值;所有权系统检查一切是否正常。
Sending Multiple Values and Seeing the Receiver Waiting
发送多个值并看到接收器正在等待
The code in Listing 16-8 compiled and ran, but it didn’t clearly show us that
two separate threads were talking to each other over the channel. In Listing
16-10 we’ve made some modifications that will prove the code in Listing 16-8 is
running concurrently: the spawned thread will now send multiple messages and
pause for a second between each message.
清单 16-8 中的代码已编译并运行,但它没有清楚地向我们显示两个单独的线程正在通过通道相互通信。在清单 16-10 中,我们做了一些修改,以证明清单 16-8 中的代码是并发运行的:生成的线程现在将发送多条消息,并在每条消息之间暂停一秒钟。
Filename: src/main.rs 文件名:src/main.rs
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}");
}
}
This time, the spawned thread has a vector of strings that we want to send to
the main thread. We iterate over them, sending each individually, and pause
between each by calling the thread::sleep
function with a Duration
value of
1 second.
这次,生成的线程有一个我们想要发送到主线程的字符串向量。我们迭代它们,单独发送每个,并通过调用thread::sleep
函数( Duration
值为 1 秒)在每个之间暂停。
In the main thread, we’re not calling the recv
function explicitly anymore:
instead, we’re treating rx
as an iterator. For each value received, we’re
printing it. When the channel is closed, iteration will end.
在主线程中,我们不再显式调用recv
函数:相反,我们将rx
视为迭代器。对于收到的每个值,我们都会打印它。当通道关闭时,迭代将结束。
When running the code in Listing 16-10, you should see the following output
with a 1-second pause in between each line:
运行清单 16-10 中的代码时,您应该看到以下输出,每行之间有 1 秒的暂停:
Got: hi
Got: from
Got: the
Got: thread
Because we don’t have any code that pauses or delays in the for
loop in the
main thread, we can tell that the main thread is waiting to receive values from
the spawned thread.
因为我们在主线程的for
循环中没有任何暂停或延迟的代码,所以我们可以知道主线程正在等待从生成的线程接收值。
Creating Multiple Producers by Cloning the Transmitter
通过克隆发送器创建多个生产者
Earlier we mentioned that mpsc
was an acronym for multiple producer,
single consumer. Let’s put mpsc
to use and expand the code in Listing 16-10
to create multiple threads that all send values to the same receiver. We can do
so by cloning the transmitter, as shown in Listing 16-11:
前面我们提到mpsc
是multiple Producer, Single Consumer的缩写。让我们使用mpsc
并扩展清单 16-10 中的代码来创建多个线程,这些线程都将值发送到同一个接收器。我们可以通过克隆发射器来实现这一点,如清单 16-11 所示:
Filename: src/main.rs 文件名:src/main.rs
This time, before we create the first spawned thread, we call clone
on the
transmitter. This will give us a new transmitter we can pass to the first
spawned thread. We pass the original transmitter to a second spawned thread.
This gives us two threads, each sending different messages to the one receiver.
这次,在创建第一个衍生线程之前,我们在发送器上调用clone
。这将为我们提供一个新的发送器,我们可以将其传递给第一个生成的线程。我们将原始发送器传递给第二个生成的线程。这给了我们两个线程,每个线程向一个接收者发送不同的消息。
When you run the code, your output should look something like this:
当您运行代码时,您的输出应如下所示:
Got: hi
Got: more
Got: from
Got: messages
Got: for
Got: the
Got: thread
Got: you
You might see the values in another order, depending on your system. This is
what makes concurrency interesting as well as difficult. If you experiment with
thread::sleep
, giving it various values in the different threads, each run
will be more nondeterministic and create different output each time.
您可能会看到其他顺序的值,具体取决于您的系统。这就是并发既有趣又困难的原因。如果您尝试使用thread::sleep
,并在不同的线程中给它不同的值,则每次运行将更加不确定,并且每次都会创建不同的输出。
Now that we’ve looked at how channels work, let’s look at a different method of
concurrency.
现在我们已经了解了通道的工作原理,让我们看看另一种不同的并发方法。
Shared-State Concurrency 共享状态并发
Message passing is a fine way of handling concurrency, but it’s not the only
one. Another method would be for multiple threads to access the same shared
data. Consider this part of the slogan from the Go language documentation
again: “do not communicate by sharing memory.”
消息传递是处理并发的一种很好的方法,但它不是唯一的方法。另一种方法是让多个线程访问相同的共享数据。再考虑一下 Go 语言文档中的这句口号:“不要通过共享内存进行通信。”
What would communicating by sharing memory look like? In addition, why would
message-passing enthusiasts caution not to use memory sharing?
通过共享内存进行通信会是什么样子?此外,为什么消息传递爱好者会警告不要使用内存共享?
In a way, channels in any programming language are similar to single ownership,
because once you transfer a value down a channel, you should no longer use that
value. Shared memory concurrency is like multiple ownership: multiple threads
can access the same memory location at the same time. As you saw in Chapter 15,
where smart pointers made multiple ownership possible, multiple ownership can
add complexity because these different owners need managing. Rust’s type system
and ownership rules greatly assist in getting this management correct. For an
example, let’s look at mutexes, one of the more common concurrency primitives
for shared memory.
在某种程度上,任何编程语言中的通道都类似于单一所有权,因为一旦您将值转移到通道中,您就不应该再使用该值。共享内存并发就像多重所有权:多个线程可以同时访问同一内存位置。正如您在第 15 章中看到的,智能指针使多重所有权成为可能,多重所有权会增加复杂性,因为这些不同的所有者需要管理。 Rust 的类型系统和所有权规则极大地有助于正确进行这种管理。举个例子,让我们看一下互斥体,它是共享内存的更常见的并发原语之一。
Using Mutexes to Allow Access to Data from One Thread at a Time
使用互斥体允许一次从一个线程访问数据
Mutex is an abbreviation for mutual exclusion, as in, a mutex allows only
one thread to access some data at any given time. To access the data in a
mutex, a thread must first signal that it wants access by asking to acquire the
mutex’s lock. The lock is a data structure that is part of the mutex that
keeps track of who currently has exclusive access to the data. Therefore, the
mutex is described as guarding the data it holds via the locking system.
互斥体是互斥体的缩写,互斥体在任何给定时间只允许一个线程访问某些数据。要访问互斥体中的数据,线程必须首先通过请求获取互斥体的锁来表明它想要访问。锁是一种数据结构,是互斥体的一部分,用于跟踪当前谁对数据具有独占访问权。因此,互斥体被描述为通过锁定系统保护其保存的数据。
Mutexes have a reputation for being difficult to use because you have to
remember two rules:
互斥体因难以使用而闻名,因为您必须记住两条规则:
- You must attempt to acquire the lock before using the data.
在使用数据之前,您必须尝试获取锁。 - When you’re done with the data that the mutex guards, you must unlock the
data so other threads can acquire the lock.
当您完成互斥锁保护的数据后,必须解锁数据,以便其他线程可以获得锁。
For a real-world metaphor for a mutex, imagine a panel discussion at a
conference with only one microphone. Before a panelist can speak, they have to
ask or signal that they want to use the microphone. When they get the
microphone, they can talk for as long as they want to and then hand the
microphone to the next panelist who requests to speak. If a panelist forgets to
hand the microphone off when they’re finished with it, no one else is able to
speak. If management of the shared microphone goes wrong, the panel won’t work
as planned!
对于互斥锁的现实世界比喻,想象一下在只有一个麦克风的会议上进行小组讨论。在小组成员发言之前,他们必须询问或示意他们想要使用麦克风。当他们拿到麦克风时,他们可以随意发言,然后将麦克风交给下一位要求发言的小组成员。如果小组成员在结束后忘记交出麦克风,那么其他人就无法发言。如果共享麦克风的管理出现问题,面板将无法按计划工作!
Management of mutexes can be incredibly tricky to get right, which is why so
many people are enthusiastic about channels. However, thanks to Rust’s type
system and ownership rules, you can’t get locking and unlocking wrong.
正确管理互斥体可能非常棘手,这就是为什么这么多人对通道充满热情的原因。然而,由于 Rust 的类型系统和所有权规则,您不会出现错误的锁定和解锁。
The API of Mutex<T>
Mutex<T>
的API
As an example of how to use a mutex, let’s start by using a mutex in a
single-threaded context, as shown in Listing 16-12:
作为如何使用互斥锁的示例,我们首先在单线程上下文中使用互斥锁,如清单 16-12 所示:
Filename: src/main.rs 文件名:src/main.rs
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
println!("m = {m:?}");
}
As with many types, we create a Mutex<T>
using the associated function new
.
To access the data inside the mutex, we use the lock
method to acquire the
lock. This call will block the current thread so it can’t do any work until
it’s our turn to have the lock.
与许多类型一样,我们使用关联函数new
创建一个Mutex<T>
。为了访问互斥锁内的数据,我们使用lock
方法来获取锁。此调用将阻塞当前线程,因此在轮到我们获得锁之前它无法执行任何工作。
The call to lock
would fail if another thread holding the lock panicked. In
that case, no one would ever be able to get the lock, so we’ve chosen to
unwrap
and have this thread panic if we’re in that situation.
如果持有锁的另一个线程发生恐慌,则对lock
的调用将会失败。在这种情况下,没有人能够获得锁,因此如果我们处于这种情况,我们选择unwrap
并使该线程发生恐慌。
After we’ve acquired the lock, we can treat the return value, named num
in
this case, as a mutable reference to the data inside. The type system ensures
that we acquire a lock before using the value in m
. The type of m
is
Mutex<i32>
, not i32
, so we must call lock
to be able to use the i32
value. We can’t forget; the type system won’t let us access the inner i32
otherwise.
获取锁后,我们可以将返回值(在本例中名为num
视为对内部数据的可变引用。类型系统确保我们在使用m
中的值之前获取锁。 m
的类型是Mutex<i32>
,而不是i32
,因此我们必须调用lock
才能使用i32
值。我们不能忘记;否则类型系统不会让我们访问内部i32
。
As you might suspect, Mutex<T>
is a smart pointer. More accurately, the call
to lock
returns a smart pointer called MutexGuard
, wrapped in a
LockResult
that we handled with the call to unwrap
. The MutexGuard
smart
pointer implements Deref
to point at our inner data; the smart pointer also
has a Drop
implementation that releases the lock automatically when a
MutexGuard
goes out of scope, which happens at the end of the inner scope. As
a result, we don’t risk forgetting to release the lock and blocking the mutex
from being used by other threads, because the lock release happens
automatically.
正如您可能怀疑的那样, Mutex<T>
是一个智能指针。更准确地说,对lock
的调用返回一个名为MutexGuard
的智能指针,该指针包装在我们通过调用unwrap
处理的LockResult
中。 MutexGuard
智能指针实现Deref
来指向我们的内部数据;智能指针还有一个Drop
实现,当MutexGuard
超出范围(发生在内部范围的末尾)时,该实现会自动释放锁。因此,我们不会冒忘记释放锁并阻止其他线程使用互斥体的风险,因为锁释放会自动发生。
After dropping the lock, we can print the mutex value and see that we were able
to change the inner i32
to 6.
释放锁后,我们可以打印互斥锁值,并看到我们能够将内部i32
更改为 6。
Sharing a Mutex<T>
Between Multiple Threads
在多个线程之间共享Mutex<T>
Now, let’s try to share a value between multiple threads using Mutex<T>
.
We’ll spin up 10 threads and have them each increment a counter value by 1, so
the counter goes from 0 to 10. The next example in Listing 16-13 will have
a compiler error, and we’ll use that error to learn more about using
Mutex<T>
and how Rust helps us use it correctly.
现在,让我们尝试使用Mutex<T>
在多个线程之间共享值。我们将启动 10 个线程,并让它们各自将计数器值加 1,因此计数器从 0 变为 10。清单 16-13 中的下一个示例将出现编译器错误,我们将使用该错误来学习更多关于使用Mutex<T>
以及 Rust 如何帮助我们正确使用它的信息。
Filename: src/main.rs 文件名:src/main.rs
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());
}
We create a counter
variable to hold an i32
inside a Mutex<T>
, as we did
in Listing 16-12. Next, we create 10 threads by iterating over a range of
numbers. We use thread::spawn
and give all the threads the same closure: one
that moves the counter into the thread, acquires a lock on the Mutex<T>
by
calling the lock
method, and then adds 1 to the value in the mutex. When a
thread finishes running its closure, num
will go out of scope and release the
lock so another thread can acquire it.
我们创建一个counter
变量来将i32
保存在Mutex<T>
中,如清单 16-12 中所做的那样。接下来,我们通过迭代一系列数字来创建 10 个线程。我们使用thread::spawn
并为所有线程提供相同的闭包:将计数器移入线程,通过调用lock
方法获取Mutex<T>
上的锁,然后将互斥体中的值加 1 。当一个线程完成运行其闭包时, num
将超出范围并释放锁,以便另一个线程可以获取它。
In the main thread, we collect all the join handles. Then, as we did in Listing
16-2, we call join
on each handle to make sure all the threads finish. At
that point, the main thread will acquire the lock and print the result of this
program.
在主线程中,我们收集所有连接句柄。然后,正如我们在清单 16-2 中所做的那样,我们对每个句柄调用join
以确保所有线程都完成。此时,主线程将获取锁并打印该程序的结果。
We hinted that this example wouldn’t compile. Now let’s find out why!
我们暗示这个例子无法编译。现在让我们找出原因!
$ cargo run
Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0382]: borrow of moved value: `counter`
--> src/main.rs:21:29
|
5 | let counter = Mutex::new(0);
| ------- move occurs because `counter` has type `Mutex<i32>`, which does not implement the `Copy` trait
...
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
For more information about this error, try `rustc --explain E0382`.
error: could not compile `shared-state` (bin "shared-state") due to 1 previous error
The error message states that the counter
value was moved in the previous
iteration of the loop. Rust is telling us that we can’t move the ownership
of counter
into multiple threads. Let’s fix the compiler error with a
multiple-ownership method we discussed in Chapter 15.
错误消息指出counter
值在循环的上一次迭代中已移动。 Rust 告诉我们,我们不能将counter
的所有权转移到多个线程中。让我们用第 15 章讨论的多重所有权方法来修复编译器错误。
Multiple Ownership with Multiple Threads
多线程的多重所有权
In Chapter 15, we gave a value multiple owners by using the smart pointer
Rc<T>
to create a reference counted value. Let’s do the same here and see
what happens. We’ll wrap the Mutex<T>
in Rc<T>
in Listing 16-14 and clone
the Rc<T>
before moving ownership to the thread.
在第 15 章中,我们通过使用智能指针Rc<T>
创建引用计数值来赋予一个值多个所有者。让我们在这里做同样的事情,看看会发生什么。我们将在清单 16-14 中将Mutex<T>
包装在Rc<T>
中,并在将所有权移至线程之前克隆Rc<T>
。
Filename: src/main.rs 文件名:src/main.rs
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(&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());
}
Once again, we compile and get… different errors! The compiler is teaching us
a lot.
我们再次编译并得到……不同的错误!编译器教会了我们很多东西。
$ cargo run
Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0277]: `Rc<Mutex<i32>>` cannot be sent between threads safely
--> 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<Mutex<i32>>` cannot be sent between threads safely
|
= help: within `{closure@src/main.rs:11:36: 11:43}`, the trait `Send` is not implemented for `Rc<Mutex<i32>>`, which is required by `{closure@src/main.rs:11:36: 11:43}: Send`
note: required because it's used within this closure
--> src/main.rs:11:36
|
11 | let handle = thread::spawn(move || {
| ^^^^^^^
note: required by a bound in `spawn`
--> /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/std/src/thread/mod.rs:677: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
Wow, that error message is very wordy! Here’s the important part to focus on:
`Rc<Mutex<i32>>` cannot be sent between threads safely
. The compiler is
also telling us the reason why: the trait `Send` is not implemented for `Rc<Mutex<i32>>`
. We’ll talk about Send
in the next section: it’s one of
the traits that ensures the types we use with threads are meant for use in
concurrent situations.
哇,这个错误信息太啰嗦了!这是需要关注的重要部分: `Rc<Mutex<i32>>` cannot be sent between threads safely
。编译器还告诉我们原因: the trait `Send` is not implemented for `Rc<Mutex<i32>>`
。我们将在下一节中讨论Send
:它是确保我们与线程一起使用的类型适用于并发情况的特征之一。
Unfortunately, Rc<T>
is not safe to share across threads. When Rc<T>
manages the reference count, it adds to the count for each call to clone
and
subtracts from the count when each clone is dropped. But it doesn’t use any
concurrency primitives to make sure that changes to the count can’t be
interrupted by another thread. This could lead to wrong counts—subtle bugs that
could in turn lead to memory leaks or a value being dropped before we’re done
with it. What we need is a type exactly like Rc<T>
but one that makes changes
to the reference count in a thread-safe way.
不幸的是, Rc<T>
不能安全地跨线程共享。当Rc<T>
管理引用计数时,它会添加每次调用clone
的计数,并在删除每个克隆时从计数中减去。但它不使用任何并发原语来确保计数的更改不会被另一个线程中断。这可能会导致错误的计数 - 微妙的错误可能会导致内存泄漏或在我们完成之前删除某个值。我们需要的是一种与Rc<T>
完全相同的类型,但它以线程安全的方式更改引用计数。
Atomic Reference Counting with Arc<T>
使用Arc<T>
进行原子引用计数
Fortunately, Arc<T>
is a type like Rc<T>
that is safe to use in
concurrent situations. The a stands for atomic, meaning it’s an atomically
reference counted type. Atomics are an additional kind of concurrency
primitive that we won’t cover in detail here: see the standard library
documentation for std::sync::atomic
for more
details. At this point, you just need to know that atomics work like primitive
types but are safe to share across threads.
幸运的是, Arc<T>
是一种类似于Rc<T>
类型,可以在并发情况下安全使用。 a代表atomic ,这意味着它是一个原子引用计数类型。原子是另一种并发原语,我们不会在这里详细介绍:有关更多详细信息,请参阅std::sync::atomic
的标准库文档。此时,您只需要知道原子像原始类型一样工作,但可以安全地跨线程共享。
You might then wonder why all primitive types aren’t atomic and why standard
library types aren’t implemented to use Arc<T>
by default. The reason is that
thread safety comes with a performance penalty that you only want to pay when
you really need to. If you’re just performing operations on values within a
single thread, your code can run faster if it doesn’t have to enforce the
guarantees atomics provide.
然后您可能想知道为什么所有基元类型都不是原子的,以及为什么标准库类型没有实现为默认使用Arc<T>
。原因是线程安全会带来性能损失,您只有在真正需要时才愿意付出代价。如果您只是在单个线程中对值执行操作,并且不必强制执行原子提供的保证,那么您的代码可以运行得更快。
Let’s return to our example: Arc<T>
and Rc<T>
have the same API, so we fix
our program by changing the use
line, the call to new
, and the call to
clone
. The code in Listing 16-15 will finally compile and run:
让我们回到我们的示例: Arc<T>
和Rc<T>
具有相同的 API,因此我们通过更改use
行、对new
调用以及对clone
调用来修复我们的程序。清单16-15中的代码最终将编译并运行:
Filename: src/main.rs 文件名:src/main.rs
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(&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());
}
This code will print the following:
该代码将打印以下内容:
Result: 10
We did it! We counted from 0 to 10, which may not seem very impressive, but it
did teach us a lot about Mutex<T>
and thread safety. You could also use this
program’s structure to do more complicated operations than just incrementing a
counter. Using this strategy, you can divide a calculation into independent
parts, split those parts across threads, and then use a Mutex<T>
to have each
thread update the final result with its part.
我们做到了!我们从0数到10,这看起来可能不太令人印象深刻,但它确实教会了我们很多关于Mutex<T>
和线程安全的知识。您还可以使用该程序的结构来执行更复杂的操作,而不仅仅是递增计数器。使用此策略,您可以将计算划分为独立的部分,跨线程拆分这些部分,然后使用Mutex<T>
让每个线程用其部分更新最终结果。
Note that if you are doing simple numerical operations, there are types simpler
than Mutex<T>
types provided by the std::sync::atomic
module of the
standard library. These types provide safe, concurrent,
atomic access to primitive types. We chose to use Mutex<T>
with a primitive
type for this example so we could concentrate on how Mutex<T>
works.
请注意,如果您正在进行简单的数值运算,则标准库的std::sync::atomic
模块提供的类型比Mutex<T>
类型更简单。这些类型提供对原始类型的安全、并发、原子访问。在本示例中,我们选择使用具有原始类型的Mutex<T>
以便我们可以专注于Mutex<T>
的工作原理。
Similarities Between RefCell<T>
/Rc<T>
and Mutex<T>
/Arc<T>
RefCell<T>
/ Rc<T>
和Mutex<T>
/ Arc<T>
之间的相似之处
You might have noticed that counter
is immutable but we could get a mutable
reference to the value inside it; this means Mutex<T>
provides interior
mutability, as the Cell
family does. In the same way we used RefCell<T>
in
Chapter 15 to allow us to mutate contents inside an Rc<T>
, we use Mutex<T>
to mutate contents inside an Arc<T>
.
您可能已经注意到counter
是不可变的,但我们可以获得对其内部值的可变引用;这意味着Mutex<T>
提供内部可变性,就像Cell
系列一样。就像我们在第 15 章中使用RefCell<T>
来允许我们改变Rc<T>
内的内容一样,我们使用Mutex<T>
来改变Arc<T>
内的内容。
Another detail to note is that Rust can’t protect you from all kinds of logic
errors when you use Mutex<T>
. Recall in Chapter 15 that using Rc<T>
came
with the risk of creating reference cycles, where two Rc<T>
values refer to
each other, causing memory leaks. Similarly, Mutex<T>
comes with the risk of
creating deadlocks. These occur when an operation needs to lock two resources
and two threads have each acquired one of the locks, causing them to wait for
each other forever. If you’re interested in deadlocks, try creating a Rust
program that has a deadlock; then research deadlock mitigation strategies for
mutexes in any language and have a go at implementing them in Rust. The
standard library API documentation for Mutex<T>
and MutexGuard
offers
useful information.
另一个需要注意的细节是,当您使用Mutex<T>
时,Rust 无法保护您免受各种逻辑错误的影响。回想一下第 15 章,使用Rc<T>
会带来创建引用循环的风险,其中两个Rc<T>
值相互引用,从而导致内存泄漏。同样, Mutex<T>
也存在产生死锁的风险。当一个操作需要锁定两个资源并且两个线程各自获取其中一个锁,导致它们永远等待对方时,就会发生这种情况。如果您对死锁感兴趣,请尝试创建一个具有死锁的 Rust 程序;然后研究任何语言中互斥体的死锁缓解策略,并尝试在 Rust 中实现它们。 Mutex<T>
和MutexGuard
的标准库 API 文档提供了有用的信息。
We’ll round out this chapter by talking about the Send
and Sync
traits and
how we can use them with custom types.
我们将通过讨论Send
和Sync
特征以及如何将它们与自定义类型一起使用来结束本章。
Extensible Concurrency with the Sync
and Send
Traits
具有Sync
和Send
特征的可扩展并发
Interestingly, the Rust language has very few concurrency features. Almost
every concurrency feature we’ve talked about so far in this chapter has been
part of the standard library, not the language. Your options for handling
concurrency are not limited to the language or the standard library; you can
write your own concurrency features or use those written by others.
有趣的是,Rust 语言的并发特性非常少。到目前为止,我们在本章中讨论的几乎所有并发特性都是标准库的一部分,而不是语言的一部分。您处理并发的选项不仅限于语言或标准库;您可以编写自己的并发功能或使用其他人编写的并发功能。
However, two concurrency concepts are embedded in the language: the
std::marker
traits Sync
and Send
.
但是,该语言中嵌入了两个并发概念: std::marker
特性Sync
和Send
。
Allowing Transference of Ownership Between Threads with Send
允许Send
在线程之间转移所有权
The Send
marker trait indicates that ownership of values of the type
implementing Send
can be transferred between threads. Almost every Rust type
is Send
, but there are some exceptions, including Rc<T>
: this cannot be
Send
because if you cloned an Rc<T>
value and tried to transfer ownership
of the clone to another thread, both threads might update the reference count
at the same time. For this reason, Rc<T>
is implemented for use in
single-threaded situations where you don’t want to pay the thread-safe
performance penalty.Send
标记特征指示实现Send
的类型的值的所有权可以在线程之间转移。几乎所有 Rust 类型都是Send
,但有一些例外,包括Rc<T>
:这不能是Send
因为如果您克隆了Rc<T>
值并尝试将克隆的所有权转移到另一个线程,则两个线程都可能同时更新引用计数。因此,实现Rc<T>
是为了在您不想付出线程安全性能损失的单线程情况下使用。
Therefore, Rust’s type system and trait bounds ensure that you can never
accidentally send an Rc<T>
value across threads unsafely. When we tried to do
this in Listing 16-14, we got the error the trait Send is not implemented for Rc<Mutex<i32>>
. When we switched to Arc<T>
, which is Send
, the code
compiled.
因此,Rust 的类型系统和特征边界确保您永远不会意外地不安全地跨线程发送Rc<T>
值。当我们尝试在清单 16-14 中执行此操作时,我们收到错误the trait Send is not implemented for Rc<Mutex<i32>>
。当我们切换到Arc<T>
(即Send
时,代码被编译。
Any type composed entirely of Send
types is automatically marked as Send
as
well. Almost all primitive types are Send
, aside from raw pointers, which
we’ll discuss in Chapter 19.
任何完全由Send
类型组成的类型也会自动标记为Send
。除了我们将在第 19 章讨论的原始指针之外,几乎所有原始类型都是Send
。
Allowing Access from Multiple Threads with Sync
允许从多个线程Sync
访问
The Sync
marker trait indicates that it is safe for the type implementing
Sync
to be referenced from multiple threads. In other words, any type T
is
Sync
if &T
(an immutable reference to T
) is Send
, meaning the reference
can be sent safely to another thread. Similar to Send
, primitive types are
Sync
, and types composed entirely of types that are Sync
are also Sync
.Sync
标记特征表明从多个线程引用实现Sync
类型是安全的。换句话说,如果&T
(对T
的不可变引用)是Send
,则任何类型T
都是Sync
,这意味着该引用可以安全地发送到另一个线程。与Send
类似,原始类型是Sync
,并且完全由Sync
类型组成的类型也是Sync
。
The smart pointer Rc<T>
is also not Sync
for the same reasons that it’s not
Send
. The RefCell<T>
type (which we talked about in Chapter 15) and the
family of related Cell<T>
types are not Sync
. The implementation of borrow
checking that RefCell<T>
does at runtime is not thread-safe. The smart
pointer Mutex<T>
is Sync
and can be used to share access with multiple
threads as you saw in the “Sharing a Mutex<T>
Between Multiple
Threads” section.
智能指针Rc<T>
也不是Sync
,原因与它不是Send
原因相同。 RefCell<T>
类型(我们在第 15 章中讨论过)和相关的Cell<T>
类型系列不是Sync
。 RefCell<T>
在运行时执行的借用检查的实现不是线程安全的。智能指针Mutex<T>
是Sync
,可用于与多个线程共享访问,正如您在“在多个线程之间共享Mutex<T>
”忽略部分中看到的那样。
Implementing Send
and Sync
Manually Is Unsafe
手动实现Send
和Sync
是不安全的
Because types that are made up of Send
and Sync
traits are automatically
also Send
and Sync
, we don’t have to implement those traits manually. As
marker traits, they don’t even have any methods to implement. They’re just
useful for enforcing invariants related to concurrency.
由于由Send
和Sync
特征组成的类型也自动具有Send
和Sync
特征,因此我们不必手动实现这些特征。作为标记特征,它们甚至没有任何方法可以实现。它们只是用于强制执行与并发相关的不变量。
Manually implementing these traits involves implementing unsafe Rust code.
We’ll talk about using unsafe Rust code in Chapter 19; for now, the important
information is that building new concurrent types not made up of Send
and
Sync
parts requires careful thought to uphold the safety guarantees. “The
Rustonomicon” has more information about these guarantees and how to
uphold them.
手动实现这些特征涉及实现不安全的 Rust 代码。我们将在第 19 章讨论使用不安全的 Rust 代码;目前,重要的信息是构建不由Send
和Sync
部分组成的新并发类型需要仔细考虑以维护安全保证。 《The Rustonomicon》提供了有关这些保证以及如何维护这些保证的更多信息。
Summary 概括
This isn’t the last you’ll see of concurrency in this book: the project in
Chapter 20 will use the concepts in this chapter in a more realistic situation
than the smaller examples discussed here.
这并不是你在本书中最后一次看到并发:第 20 章中的项目将在比这里讨论的较小示例更现实的情况下使用本章中的概念。
As mentioned earlier, because very little of how Rust handles concurrency is
part of the language, many concurrency solutions are implemented as crates.
These evolve more quickly than the standard library, so be sure to search
online for the current, state-of-the-art crates to use in multithreaded
situations.
如前所述,由于 Rust 处理并发的方式很少是语言的一部分,因此许多并发解决方案都是以 crate 的形式实现的。它们的发展速度比标准库更快,因此请务必在线搜索当前最先进的 crate,以便在多线程情况下使用。
The Rust standard library provides channels for message passing and smart
pointer types, such as Mutex<T>
and Arc<T>
, that are safe to use in
concurrent contexts. The type system and the borrow checker ensure that the
code using these solutions won’t end up with data races or invalid references.
Once you get your code to compile, you can rest assured that it will happily
run on multiple threads without the kinds of hard-to-track-down bugs common in
other languages. Concurrent programming is no longer a concept to be afraid of:
go forth and make your programs concurrent, fearlessly!
Rust 标准库提供了消息传递和智能指针类型的通道,例如Mutex<T>
和Arc<T>
,它们可以在并发上下文中安全使用。类型系统和借用检查器确保使用这些解决方案的代码不会出现数据争用或无效引用。一旦你编译了你的代码,你就可以放心,它会很高兴地在多个线程上运行,而不会出现其他语言中常见的难以追踪的错误。并发编程不再是一个令人害怕的概念:勇敢地让你的程序并发!
Next, we’ll talk about idiomatic ways to model problems and structure solutions
as your Rust programs get bigger. In addition, we’ll discuss how Rust’s idioms
relate to those you might be familiar with from object-oriented programming.
接下来,我们将讨论随着 Rust 程序变得越来越大,建模问题和构建解决方案的惯用方法。此外,我们还将讨论 Rust 的习惯用法与您可能熟悉的面向对象编程的习惯用法之间的关系。
Object-Oriented Programming Features of Rust
Rust 的面向对象编程特性
Object-oriented programming (OOP) is a way of modeling programs. Objects as a
programmatic concept were introduced in the programming language Simula in the
1960s. Those objects influenced Alan Kay’s programming architecture in which
objects pass messages to each other. To describe this architecture, he coined
the term object-oriented programming in 1967. Many competing definitions
describe what OOP is, and by some of these definitions Rust is object-oriented,
but by others it is not. In this chapter, we’ll explore certain characteristics
that are commonly considered object-oriented and how those characteristics
translate to idiomatic Rust. We’ll then show you how to implement an
object-oriented design pattern in Rust and discuss the trade-offs of doing so
versus implementing a solution using some of Rust’s strengths instead.
面向对象编程(OOP)是一种程序建模方法。对象作为编程概念于 20 世纪 60 年代在编程语言 Simula 中引入。这些对象影响了 Alan Kay 的编程架构,其中对象相互传递消息。为了描述这种架构,他在 1967 年创造了面向对象编程这个术语。许多相互竞争的定义描述了 OOP 是什么,根据其中一些定义,Rust 是面向对象的,但根据其他定义,它不是。在本章中,我们将探讨通常被认为是面向对象的某些特征,以及这些特征如何转化为惯用的 Rust。然后,我们将向您展示如何在 Rust 中实现面向对象的设计模式,并讨论这样做与使用 Rust 的一些优势实现解决方案之间的权衡。
Characteristics of Object-Oriented Languages
面向对象语言的特点
There is no consensus in the programming community about what features a
language must have to be considered object-oriented. Rust is influenced by many
programming paradigms, including OOP; for example, we explored the features
that came from functional programming in Chapter 13. Arguably, OOP languages
share certain common characteristics, namely objects, encapsulation, and
inheritance. Let’s look at what each of those characteristics means and whether
Rust supports it.
对于一种语言必须具备哪些特性才能被视为面向对象,编程社区尚未达成共识。 Rust 受到许多编程范式的影响,包括 OOP;例如,我们在第 13 章中探讨了来自函数式编程的特性。可以说,OOP 语言具有某些共同的特性,即对象、封装和继承。让我们看看每个特性的含义以及 Rust 是否支持它们。
Objects Contain Data and Behavior
对象包含数据和行为
The book Design Patterns: Elements of Reusable Object-Oriented Software by
Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley
Professional, 1994), colloquially referred to as The Gang of Four book, is a
catalog of object-oriented design patterns. It defines OOP this way:
Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides 所著的《设计模式:可重用面向对象软件的元素》一书(Addison-Wesley Professional,1994 年)通俗地称为“四人帮”一书,是一本面向对象的目录面向设计模式。它这样定义 OOP:
Object-oriented programs are made up of objects. An object packages both data and the procedures that operate on that data. The procedures are typically called methods or operations.
面向对象的程序是由对象组成的。对象封装了数据和操作该数据的过程。这些过程通常称为方法或操作。
Using this definition, Rust is object-oriented: structs and enums have data,
and impl
blocks provide methods on structs and enums. Even though structs and
enums with methods aren’t called objects, they provide the same
functionality, according to the Gang of Four’s definition of objects.
使用这个定义,Rust 是面向对象的:结构和枚举具有数据,并且impl
块提供结构和枚举上的方法。尽管具有方法的结构和枚举不称为对象,但根据四人帮对对象的定义,它们提供相同的功能。
Encapsulation that Hides Implementation Details
隐藏实现细节的封装
Another aspect commonly associated with OOP is the idea of encapsulation,
which means that the implementation details of an object aren’t accessible to
code using that object. Therefore, the only way to interact with an object is
through its public API; code using the object shouldn’t be able to reach into
the object’s internals and change data or behavior directly. This enables the
programmer to change and refactor an object’s internals without needing to
change the code that uses the object.
通常与 OOP 相关的另一个方面是封装的思想,这意味着使用该对象的代码无法访问该对象的实现细节。因此,与对象交互的唯一方法是通过其公共 API;使用该对象的代码不应该能够进入对象的内部并直接更改数据或行为。这使得程序员能够更改和重构对象的内部结构,而无需更改使用该对象的代码。
We discussed how to control encapsulation in Chapter 7: we can use the pub
keyword to decide which modules, types, functions, and methods in our code
should be public, and by default everything else is private. For example, we
can define a struct AveragedCollection
that has a field containing a vector
of i32
values. The struct can also have a field that contains the average of
the values in the vector, meaning the average doesn’t have to be computed
on demand whenever anyone needs it. In other words, AveragedCollection
will
cache the calculated average for us. Listing 17-1 has the definition of the
AveragedCollection
struct:
我们在第 7 章中讨论了如何控制封装:我们可以使用pub
关键字来决定代码中的哪些模块、类型、函数和方法应该是公共的,默认情况下其他所有内容都是私有的。例如,我们可以定义一个 struct AveragedCollection
,它有一个包含i32
值向量的字段。该结构还可以有一个包含向量中值的平均值的字段,这意味着每当有人需要时都不必按需计算平均值。换句话说, AveragedCollection
会为我们缓存计算出的平均值。清单 17-1 包含AveragedCollection
结构的定义:
Filename: src/lib.rs 文件名:src/lib.rs
pub struct AveragedCollection {
list: Vec<i32>,
average: f64,
}
The struct is marked pub
so that other code can use it, but the fields within
the struct remain private. This is important in this case because we want to
ensure that whenever a value is added or removed from the list, the average is
also updated. We do this by implementing add
, remove
, and average
methods
on the struct, as shown in Listing 17-2:
该结构被标记为pub
,以便其他代码可以使用它,但该结构中的字段仍然是私有的。这在本例中很重要,因为我们希望确保每当在列表中添加或删除值时,平均值也会更新。我们通过在结构体上实现add
、 remove
和average
方法来实现这一点,如清单 17-2 所示:
Filename: src/lib.rs 文件名:src/lib.rs
The public methods add
, remove
, and average
are the only ways to access
or modify data in an instance of AveragedCollection
. When an item is added
to list
using the add
method or removed using the remove
method, the
implementations of each call the private update_average
method that handles
updating the average
field as well.
公共方法add
、 remove
和average
是访问或修改AveragedCollection
实例中的数据的唯一方法。当使用add
方法将项目添加到list
或使用remove
方法删除项目时,每个项目的实现都会调用私有update_average
方法,该方法也处理更新average
字段。
We leave the list
and average
fields private so there is no way for
external code to add or remove items to or from the list
field directly;
otherwise, the average
field might become out of sync when the list
changes. The average
method returns the value in the average
field,
allowing external code to read the average
but not modify it.
我们将list
和average
字段保留为私有,因此外部代码无法直接向list
字段添加或删除项目;否则,当list
更改时, average
字段可能会变得不同步。 average
方法返回average
字段中的值,允许外部代码读取average
但不能修改它。
Because we’ve encapsulated the implementation details of the struct
AveragedCollection
, we can easily change aspects, such as the data structure,
in the future. For instance, we could use a HashSet<i32>
instead of a
Vec<i32>
for the list
field. As long as the signatures of the add
,
remove
, and average
public methods stay the same, code using
AveragedCollection
wouldn’t need to change in order to compile. If we made
list
public instead, this wouldn’t necessarily be the case: HashSet<i32>
and
Vec<i32>
have different methods for adding and removing items, so the external
code would likely have to change if it were modifying list
directly.
因为我们已经封装了 struct AveragedCollection
的实现细节,所以将来我们可以轻松地更改数据结构等方面。例如,我们可以使用HashSet<i32>
而不是Vec<i32>
作为list
字段。只要add
、 remove
和average
公共方法的签名保持不变,使用AveragedCollection
的代码就不需要更改即可编译。如果我们将list
设为公开,则情况不一定如此: HashSet<i32>
和Vec<i32>
有不同的添加和删除项目的方法,因此如果外部代码修改list
,则可能需要更改直接地。
If encapsulation is a required aspect for a language to be considered
object-oriented, then Rust meets that requirement. The option to use pub
or
not for different parts of code enables encapsulation of implementation details.
如果封装是一种语言被认为是面向对象的必需方面,那么 Rust 就满足了这个要求。对代码的不同部分使用或不使用pub
选项可以实现实现细节的封装。
Inheritance as a Type System and as Code Sharing
作为类型系统和代码共享的继承
Inheritance is a mechanism whereby an object can inherit elements from
another object’s definition, thus gaining the parent object’s data and behavior
without you having to define them again.
继承是一种机制,一个对象可以从另一个对象的定义继承元素,从而获得父对象的数据和行为,而无需再次定义它们。
If a language must have inheritance to be an object-oriented language, then
Rust is not one. There is no way to define a struct that inherits the parent
struct’s fields and method implementations without using a macro.
如果一种语言必须具有继承才能成为面向对象的语言,那么 Rust 就不是。如果不使用宏,则无法定义继承父结构体的字段和方法实现的结构体。
However, if you’re used to having inheritance in your programming toolbox, you
can use other solutions in Rust, depending on your reason for reaching for
inheritance in the first place.
但是,如果您习惯于在编程工具箱中使用继承,则可以在 Rust 中使用其他解决方案,具体取决于您首先实现继承的原因。
You would choose inheritance for two main reasons. One is for reuse of code:
you can implement particular behavior for one type, and inheritance enables you
to reuse that implementation for a different type. You can do this in a limited
way in Rust code using default trait method implementations, which you saw in
Listing 10-14 when we added a default implementation of the summarize
method
on the Summary
trait. Any type implementing the Summary
trait would have
the summarize
method available on it without any further code. This is
similar to a parent class having an implementation of a method and an
inheriting child class also having the implementation of the method. We can
also override the default implementation of the summarize
method when we
implement the Summary
trait, which is similar to a child class overriding the
implementation of a method inherited from a parent class.
您选择继承有两个主要原因。一是为了代码的重用:您可以为一种类型实现特定的行为,而继承使您能够为不同的类型重用该实现。您可以使用默认特征方法实现在 Rust 代码中以有限的方式完成此操作,当我们在Summary
特征上添加summarize
方法的默认实现时,您可以在清单 10-14 中看到。任何实现Summary
特征的类型都可以使用summarize
方法,而无需任何进一步的代码。这类似于具有方法的实现的父类和也具有该方法的实现的继承子类。当我们实现Summary
特征时,我们还可以覆盖summarize
方法的默认实现,这类似于子类覆盖从父类继承的方法的实现。
The other reason to use inheritance relates to the type system: to enable a
child type to be used in the same places as the parent type. This is also
called polymorphism, which means that you can substitute multiple objects for
each other at runtime if they share certain characteristics.
使用继承的另一个原因与类型系统有关:使子类型能够在与父类型相同的位置使用。这也称为多态性,这意味着如果多个对象共享某些特征,则可以在运行时相互替换多个对象。
Polymorphism 多态性
To many people, polymorphism is synonymous with inheritance. But it’s
actually a more general concept that refers to code that can work with data
of multiple types. For inheritance, those types are generally subclasses.
对于许多人来说,多态性与继承同义。但它实际上是一个更普遍的概念,指的是可以处理多种类型数据的代码。对于继承来说,这些类型通常是子类。
Rust instead uses generics to abstract over different possible types and
trait bounds to impose constraints on what those types must provide. This is
sometimes called bounded parametric polymorphism.
相反,Rust 使用泛型来抽象不同的可能类型和特征边界,以对这些类型必须提供的内容施加约束。这有时称为有界参数多态性。
Inheritance has recently fallen out of favor as a programming design solution
in many programming languages because it’s often at risk of sharing more code
than necessary. Subclasses shouldn’t always share all characteristics of their
parent class but will do so with inheritance. This can make a program’s design
less flexible. It also introduces the possibility of calling methods on
subclasses that don’t make sense or that cause errors because the methods don’t
apply to the subclass. In addition, some languages will only allow single
inheritance (meaning a subclass can only inherit from one class), further
restricting the flexibility of a program’s design.
最近,在许多编程语言中,继承作为一种编程设计解决方案已经不再受欢迎,因为它经常面临共享过多代码的风险。子类不应该总是共享其父类的所有特征,但可以通过继承来实现。这会降低程序设计的灵活性。它还引入了在子类上调用没有意义或导致错误的方法的可能性,因为这些方法不适用于子类。此外,有些语言只允许单继承(即子类只能从一个类继承),这进一步限制了程序设计的灵活性。
For these reasons, Rust takes the different approach of using trait objects
instead of inheritance. Let’s look at how trait objects enable polymorphism in
Rust.
由于这些原因,Rust 采用了不同的方法,即使用特征对象而不是继承。让我们看看 Trait 对象如何在 Rust 中实现多态性。
Using Trait Objects That Allow for Values of Different Types
使用允许不同类型值的特征对象
In Chapter 8, we mentioned that one limitation of vectors is that they can
store elements of only one type. We created a workaround in Listing 8-9 where
we defined a SpreadsheetCell
enum that had variants to hold integers, floats,
and text. This meant we could store different types of data in each cell and
still have a vector that represented a row of cells. This is a perfectly good
solution when our interchangeable items are a fixed set of types that we know
when our code is compiled.
在第 8 章中,我们提到向量的一个限制是它们只能存储一种类型的元素。我们在清单 8-9 中创建了一个解决方法,其中定义了一个SpreadsheetCell
枚举,它具有保存整数、浮点数和文本的变体。这意味着我们可以在每个单元格中存储不同类型的数据,并且仍然有一个代表一行单元格的向量。当我们的可互换项是我们在编译代码时知道的一组固定类型时,这是一个非常好的解决方案。
However, sometimes we want our library user to be able to extend the set of
types that are valid in a particular situation. To show how we might achieve
this, we’ll create an example graphical user interface (GUI) tool that iterates
through a list of items, calling a draw
method on each one to draw it to the
screen—a common technique for GUI tools. We’ll create a library crate called
gui
that contains the structure of a GUI library. This crate might include
some types for people to use, such as Button
or TextField
. In addition,
gui
users will want to create their own types that can be drawn: for
instance, one programmer might add an Image
and another might add a
SelectBox
.
然而,有时我们希望我们的库用户能够扩展在特定情况下有效的类型集。为了展示我们如何实现这一目标,我们将创建一个示例图形用户界面 (GUI) 工具,该工具循环访问项目列表,调用每个项目的draw
方法将其绘制到屏幕上 - 这是 GUI 工具的常用技术。我们将创建一个名为gui
的库包,其中包含 GUI 库的结构。这个箱子可能包含一些供人们使用的类型,例如Button
或TextField
。此外, gui
用户将希望创建自己的可绘制类型:例如,一个程序员可能会添加一个Image
,另一个程序员可能会添加一个SelectBox
。
We won’t implement a fully fledged GUI library for this example but will show
how the pieces would fit together. At the time of writing the library, we can’t
know and define all the types other programmers might want to create. But we do
know that gui
needs to keep track of many values of different types, and it
needs to call a draw
method on each of these differently typed values. It
doesn’t need to know exactly what will happen when we call the draw
method,
just that the value will have that method available for us to call.
我们不会为此示例实现一个成熟的 GUI 库,但会展示这些部分如何组合在一起。在编写库时,我们无法知道和定义其他程序员可能想要创建的所有类型。但我们确实知道gui
需要跟踪许多不同类型的值,并且它需要对每个不同类型的值调用一个draw
方法。它不需要确切地知道当我们调用draw
方法时会发生什么,只需知道该值将具有可供我们调用的方法即可。
To do this in a language with inheritance, we might define a class named
Component
that has a method named draw
on it. The other classes, such as
Button
, Image
, and SelectBox
, would inherit from Component
and thus
inherit the draw
method. They could each override the draw
method to define
their custom behavior, but the framework could treat all of the types as if
they were Component
instances and call draw
on them. But because Rust
doesn’t have inheritance, we need another way to structure the gui
library to
allow users to extend it with new types.
要在具有继承的语言中执行此操作,我们可以定义一个名为Component
的类,该类具有名为draw
方法。其他类(例如Button
、 Image
和SelectBox
)将从Component
继承,从而继承draw
方法。它们每个都可以重写draw
方法来定义它们的自定义行为,但是框架可以将所有类型视为Component
实例并在它们上调用draw
。但由于 Rust 没有继承,我们需要另一种方式来构建gui
库,以允许用户使用新类型对其进行扩展。
Defining a Trait for Common Behavior
定义常见行为的特征
To implement the behavior we want gui
to have, we’ll define a trait named
Draw
that will have one method named draw
. Then we can define a vector that
takes a trait object. A trait object points to both an instance of a type
implementing our specified trait and a table used to look up trait methods on
that type at runtime. We create a trait object by specifying some sort of
pointer, such as a &
reference or a Box<T>
smart pointer, then the dyn
keyword, and then specifying the relevant trait. (We’ll talk about the reason
trait objects must use a pointer in Chapter 19 in the section “Dynamically
Sized Types and the Sized
Trait.”) We can
use trait objects in place of a generic or concrete type. Wherever we use a
trait object, Rust’s type system will ensure at compile time that any value
used in that context will implement the trait object’s trait. Consequently, we
don’t need to know all the possible types at compile time.
为了实现我们希望gui
具有的行为,我们将定义一个名为Draw
特征,它将有一个名为draw
方法。然后我们可以定义一个带有特征对象的向量。特征对象既指向实现我们指定特征的类型的实例,又指向用于在运行时查找该类型的特征方法的表。我们通过指定某种指针(例如&
引用或Box<T>
智能指针)、 dyn
关键字,然后指定相关特征来创建特征对象。 (我们将在第 19 章的“动态大小类型和Sized
特征”一节中讨论特征对象必须使用指针的原因。ignore )我们可以使用特征对象来代替泛型或具体类型。无论我们在哪里使用特征对象,Rust 的类型系统都会在编译时确保在该上下文中使用的任何值都将实现特征对象的特征。因此,我们不需要在编译时知道所有可能的类型。
We’ve mentioned that, in Rust, we refrain from calling structs and enums
“objects” to distinguish them from other languages’ objects. In a struct or
enum, the data in the struct fields and the behavior in impl
blocks are
separated, whereas in other languages, the data and behavior combined into one
concept is often labeled an object. However, trait objects are more like
objects in other languages in the sense that they combine data and behavior.
But trait objects differ from traditional objects in that we can’t add data to
a trait object. Trait objects aren’t as generally useful as objects in other
languages: their specific purpose is to allow abstraction across common
behavior.
我们已经提到,在 Rust 中,我们避免将结构和枚举称为“对象”,以将它们与其他语言的对象区分开来。在结构体或枚举中,结构体字段中的数据和impl
块中的行为是分开的,而在其他语言中,组合成一个概念的数据和行为通常被标记为一个对象。然而,特征对象更像其他语言中的对象,因为它们结合了数据和行为。但特征对象与传统对象的不同之处在于我们不能向特征对象添加数据。 Trait 对象并不像其他语言中的对象那样有用:它们的特定目的是允许对常见行为进行抽象。
Listing 17-3 shows how to define a trait named Draw
with one method named
draw
:
清单 17-3 展示了如何使用名为Draw
draw
:
Filename: src/lib.rs 文件名:src/lib.rs
pub trait Draw {
fn draw(&self);
}
This syntax should look familiar from our discussions on how to define traits
in Chapter 10. Next comes some new syntax: Listing 17-4 defines a struct named
Screen
that holds a vector named components
. This vector is of type
Box<dyn Draw>
, which is a trait object; it’s a stand-in for any type inside
a Box
that implements the Draw
trait.
从我们在第 10 章中关于如何定义 Trait 的讨论中,这个语法应该看起来很熟悉。接下来是一些新语法:清单 17-4 定义了一个名为Screen
结构体,它包含一个名为components
向量。该向量的类型为Box<dyn Draw>
,它是一个特征对象;它是Box
内任何实现Draw
特征的类型的替代。
Filename: src/lib.rs 文件名:src/lib.rs
On the Screen
struct, we’ll define a method named run
that will call the
draw
method on each of its components
, as shown in Listing 17-5:
在Screen
结构体上,我们将定义一个名为run
方法,它将在其每个components
上调用draw
方法,如清单 17-5 所示:
Filename: src/lib.rs 文件名:src/lib.rs
This works differently from defining a struct that uses a generic type
parameter with trait bounds. A generic type parameter can only be substituted
with one concrete type at a time, whereas trait objects allow for multiple
concrete types to fill in for the trait object at runtime. For example, we
could have defined the Screen
struct using a generic type and a trait bound
as in Listing 17-6:
这与定义使用带有特征边界的泛型类型参数的结构不同。泛型类型参数一次只能替换为一种具体类型,而特征对象允许在运行时填充多个具体类型。例如,我们可以使用泛型类型和特征绑定来定义Screen
结构,如清单 17-6 所示:
Filename: src/lib.rs 文件名:src/lib.rs
This restricts us to a Screen
instance that has a list of components all of
type Button
or all of type TextField
. If you’ll only ever have homogeneous
collections, using generics and trait bounds is preferable because the
definitions will be monomorphized at compile time to use the concrete types.
这将我们限制为一个Screen
实例,该实例具有所有类型为Button
或所有类型为TextField
的组件列表。如果您只拥有同质集合,那么最好使用泛型和特征边界,因为定义将在编译时进行单态化以使用具体类型。
On the other hand, with the method using trait objects, one Screen
instance
can hold a Vec<T>
that contains a Box<Button>
as well as a
Box<TextField>
. Let’s look at how this works, and then we’ll talk about the
runtime performance implications.
另一方面,通过使用特征对象的方法,一个Screen
实例可以保存一个包含Box<Button>
以及Box<TextField>
Vec<T>
。让我们看看它是如何工作的,然后我们将讨论运行时性能的影响。
Implementing the Trait 实施特质
Now we’ll add some types that implement the Draw
trait. We’ll provide the
Button
type. Again, actually implementing a GUI library is beyond the scope
of this book, so the draw
method won’t have any useful implementation in its
body. To imagine what the implementation might look like, a Button
struct
might have fields for width
, height
, and label
, as shown in Listing 17-7:
现在我们将添加一些实现Draw
特征的类型。我们将提供Button
类型。同样,实际实现 GUI 库超出了本书的范围,因此draw
方法在其主体中不会有任何有用的实现。想象一下实现的样子,一个Button
结构体可能有width
、 height
和label
字段,如清单 17-7 所示:
Filename: src/lib.rs 文件名:src/lib.rs
The width
, height
, and label
fields on Button
will differ from the
fields on other components; for example, a TextField
type might have those
same fields plus a placeholder
field. Each of the types we want to draw on
the screen will implement the Draw
trait but will use different code in the
draw
method to define how to draw that particular type, as Button
has here
(without the actual GUI code, as mentioned). The Button
type, for instance,
might have an additional impl
block containing methods related to what
happens when a user clicks the button. These kinds of methods won’t apply to
types like TextField
.Button
上的width
、 height
和label
字段将与其他组件上的字段不同;例如, TextField
类型可能具有相同的字段以及placeholder
字段。我们想要在屏幕上绘制的每种类型都将实现Draw
特征,但将在draw
方法中使用不同的代码来定义如何绘制该特定类型,就像Button
在这里所做的那样(如上所述,没有实际的 GUI 代码)。例如, Button
类型可能有一个附加的impl
块,其中包含与用户单击按钮时发生的情况相关的方法。这些方法不适用于TextField
等类型。
If someone using our library decides to implement a SelectBox
struct that has
width
, height
, and options
fields, they implement the Draw
trait on the
SelectBox
type as well, as shown in Listing 17-8:
如果使用我们库的人决定实现一个具有width
、 height
和options
字段的SelectBox
结构,他们也会在SelectBox
类型上实现Draw
特征,如清单 17-8 所示:
Filename: src/main.rs 文件名:src/main.rs
Our library’s user can now write their main
function to create a Screen
instance. To the Screen
instance, they can add a SelectBox
and a Button
by putting each in a Box<T>
to become a trait object. They can then call the
run
method on the Screen
instance, which will call draw
on each of the
components. Listing 17-9 shows this implementation:
我们库的用户现在可以编写他们的main
函数来创建Screen
实例。对于Screen
实例,他们可以添加一个SelectBox
和一个Button
,方法是将它们放入Box<T>
中以成为特征对象。然后,他们可以调用Screen
实例上的run
方法,该方法将调用每个组件上的draw
。清单 17-9 显示了这个实现:
Filename: src/main.rs 文件名:src/main.rs
When we wrote the library, we didn’t know that someone might add the
SelectBox
type, but our Screen
implementation was able to operate on the
new type and draw it because SelectBox
implements the Draw
trait, which
means it implements the draw
method.
当我们编写库时,我们不知道有人可能会添加SelectBox
类型,但我们的Screen
实现能够对新类型进行操作并绘制它,因为SelectBox
实现了Draw
特征,这意味着它实现了draw
方法。
This concept—of being concerned only with the messages a value responds to
rather than the value’s concrete type—is similar to the concept of duck
typing in dynamically typed languages: if it walks like a duck and quacks
like a duck, then it must be a duck! In the implementation of run
on Screen
in Listing 17-5, run
doesn’t need to know what the concrete type of each
component is. It doesn’t check whether a component is an instance of a Button
or a SelectBox
, it just calls the draw
method on the component. By
specifying Box<dyn Draw>
as the type of the values in the components
vector, we’ve defined Screen
to need values that we can call the draw
method on.
这个概念(只关心值响应的消息而不是值的具体类型)类似于动态类型语言中的鸭子类型概念:如果它像鸭子一样行走并且像鸭子一样嘎嘎叫,那么它一定是一只鸭子!在清单17-5中run
on Screen
的实现中, run
不需要知道每个组件的具体类型是什么。它不会检查组件是否是Button
或SelectBox
的实例,它只是调用组件上的draw
方法。通过指定Box<dyn Draw>
作为components
向量中的值的类型,我们定义了Screen
来需要我们可以调用draw
方法的值。
The advantage of using trait objects and Rust’s type system to write code
similar to code using duck typing is that we never have to check whether a
value implements a particular method at runtime or worry about getting errors
if a value doesn’t implement a method but we call it anyway. Rust won’t compile
our code if the values don’t implement the traits that the trait objects need.
使用 Trait 对象和 Rust 的类型系统编写与使用鸭子类型类似的代码的优点是,我们不必在运行时检查一个值是否实现了特定方法,也不必担心如果一个值没有实现某个方法但会出现错误。无论如何我们都这么称呼它。如果值没有实现特征对象所需的特征,Rust 将不会编译我们的代码。
For example, Listing 17-10 shows what happens if we try to create a Screen
with a String
as a component:
例如,清单 17-10 显示了如果我们尝试创建一个包含String
作为组件的Screen
会发生什么:
Filename: src/main.rs 文件名:src/main.rs
use gui::Screen;
fn main() {
let screen = Screen {
components: vec![Box::new(String::from("Hi"))],
};
screen.run();
}
We’ll get this error because String
doesn’t implement the Draw
trait:
我们会收到此错误,因为String
没有实现Draw
特征:
$ cargo run
Compiling gui v0.1.0 (file:///projects/gui)
error[E0277]: the trait bound `String: Draw` is not satisfied
--> 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<String>` to `Box<dyn Draw>`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `gui` (bin "gui") due to 1 previous error
This error lets us know that either we’re passing something to Screen
we
didn’t mean to pass and so should pass a different type or we should implement
Draw
on String
so that Screen
is able to call draw
on it.
这个错误让我们知道,要么我们向Screen
传递了一些我们本来不想传递的东西,所以应该传递不同的类型,要么我们应该在String
上实现Draw
,以便Screen
能够在其上调用draw
。
Trait Objects Perform Dynamic Dispatch
Trait 对象执行动态调度
Recall in the “Performance of Code Using
Generics” section in
Chapter 10 our discussion on the monomorphization process performed by the
compiler when we use trait bounds on generics: the compiler generates
nongeneric implementations of functions and methods for each concrete type that
we use in place of a generic type parameter. The code that results from
monomorphization is doing static dispatch, which is when the compiler knows
what method you’re calling at compile time. This is opposed to dynamic
dispatch, which is when the compiler can’t tell at compile time which method
you’re calling. In dynamic dispatch cases, the compiler emits code that at
runtime will figure out which method to call.
回想一下第 10 章的“使用泛型的代码性能”忽略部分,我们讨论了当我们在泛型上使用特征边界时编译器执行的单态化过程:编译器为我们使用的每个具体类型生成函数和方法的非泛型实现。泛型类型参数的位置。单态化产生的代码正在执行静态调度,此时编译器知道您在编译时调用什么方法。这与动态调度相反,动态调度是编译器在编译时无法判断您正在调用哪个方法的情况。在动态调度情况下,编译器会发出代码,在运行时将确定要调用哪个方法。
When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t
know all the types that might be used with the code that’s using trait objects,
so it doesn’t know which method implemented on which type to call. Instead, at
runtime, Rust uses the pointers inside the trait object to know which method to
call. This lookup incurs a runtime cost that doesn’t occur with static
dispatch. Dynamic dispatch also prevents the compiler from choosing to inline a
method’s code, which in turn prevents some optimizations. However, we did get
extra flexibility in the code that we wrote in Listing 17-5 and were able to
support in Listing 17-9, so it’s a trade-off to consider.
当我们使用特征对象时,Rust 必须使用动态调度。编译器不知道可能与使用特征对象的代码一起使用的所有类型,因此它不知道要调用哪个类型上实现的哪个方法。相反,在运行时,Rust 使用特征对象内的指针来知道要调用哪个方法。此查找会产生静态调度不会发生的运行时成本。动态分派还可以防止编译器选择内联方法的代码,从而阻止某些优化。然而,我们在清单 17-5 中编写的代码确实获得了额外的灵活性,并且能够在清单 17-9 中提供支持,因此这是一个需要考虑的权衡。
Implementing an Object-Oriented Design Pattern
实现面向对象的设计模式
The state pattern is an object-oriented design pattern. The crux of the
pattern is that we define a set of states a value can have internally. The
states are represented by a set of state objects, and the value’s behavior
changes based on its state. We’re going to work through an example of a blog
post struct that has a field to hold its state, which will be a state object
from the set “draft”, “review”, or “published”.
状态模式是一种面向对象的设计模式。该模式的关键在于我们定义一个值在内部可以具有的一组状态。状态由一组状态对象表示,并且值的行为根据其状态而变化。我们将研究一个博客文章结构的示例,该结构有一个字段来保存其状态,该字段将是“草稿”、“审阅”或“已发布”集合中的状态对象。
The state objects share functionality: in Rust, of course, we use structs and
traits rather than objects and inheritance. Each state object is responsible
for its own behavior and for governing when it should change into another
state. The value that holds a state object knows nothing about the different
behavior of the states or when to transition between states.
状态对象共享功能:当然,在 Rust 中,我们使用结构和特征,而不是对象和继承。每个状态对象对其自身的行为负责,并负责管理何时应更改为另一种状态。保存状态对象的值对状态的不同行为或何时在状态之间转换一无所知。
The advantage of using the state pattern is that, when the business
requirements of the program change, we won’t need to change the code of the
value holding the state or the code that uses the value. We’ll only need to
update the code inside one of the state objects to change its rules or perhaps
add more state objects.
使用状态模式的优点是,当程序的业务需求发生变化时,我们不需要更改保存状态的值的代码或使用该值的代码。我们只需要更新状态对象之一内的代码即可更改其规则,或者添加更多状态对象。
First, we’re going to implement the state pattern in a more traditional
object-oriented way, then we’ll use an approach that’s a bit more natural in
Rust. Let’s dig in to incrementally implementing a blog post workflow using the
state pattern.
首先,我们将以更传统的面向对象的方式实现状态模式,然后我们将使用一种在 Rust 中更自然的方法。让我们深入研究如何使用状态模式逐步实现博客文章工作流程。
The final functionality will look like this:
最终的功能将如下所示:
- A blog post starts as an empty draft.
博客文章一开始是一个空草稿。 - When the draft is done, a review of the post is requested.
草稿完成后,要求对该帖子进行审查。 - When the post is approved, it gets published.
当帖子获得批准后,就会发布。 - Only published blog posts return content to print, so unapproved posts can’t
accidentally be published.
只有已发布的博客帖子才会返回要打印的内容,因此不会意外发布未经批准的帖子。
Any other changes attempted on a post should have no effect. For example, if we
try to approve a draft blog post before we’ve requested a review, the post
should remain an unpublished draft.
对帖子尝试的任何其他更改都不会产生任何影响。例如,如果我们在请求审核之前尝试批准博客文章草稿,则该文章应保留为未发布的草稿。
Listing 17-11 shows this workflow in code form: this is an example usage of the
API we’ll implement in a library crate named blog
. This won’t compile yet
because we haven’t implemented the blog
crate.
清单 17-11 以代码形式显示了此工作流程:这是我们将在名为blog
库箱中实现的 API 的示例用法。这还无法编译,因为我们还没有实现blog
箱。
Filename: src/main.rs 文件名:src/main.rs
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());
}
We want to allow the user to create a new draft blog post with Post::new
. We
want to allow text to be added to the blog post. If we try to get the post’s
content immediately, before approval, we shouldn’t get any text because the
post is still a draft. We’ve added assert_eq!
in the code for demonstration
purposes. An excellent unit test for this would be to assert that a draft blog
post returns an empty string from the content
method, but we’re not going to
write tests for this example.
我们希望允许用户使用Post::new
创建新的博客文章草稿。我们希望允许将文本添加到博客文章中。如果我们尝试在批准之前立即获取帖子的内容,我们不应该收到任何文本,因为该帖子仍然是草稿。我们添加了assert_eq!
在代码中用于演示目的。一个优秀的单元测试是断言草稿博客文章从content
方法返回一个空字符串,但我们不打算为此示例编写测试。
Next, we want to enable a request for a review of the post, and we want
content
to return an empty string while waiting for the review. When the post
receives approval, it should get published, meaning the text of the post will
be returned when content
is called.
接下来,我们要启用对帖子进行审核的请求,并且我们希望content
在等待审核时返回空字符串。当帖子获得批准后,它应该被发布,这意味着调用content
时将返回帖子的文本。
Notice that the only type we’re interacting with from the crate is the Post
type. This type will use the state pattern and will hold a value that will be
one of three state objects representing the various states a post can be
in—draft, waiting for review, or published. Changing from one state to another
will be managed internally within the Post
type. The states change in
response to the methods called by our library’s users on the Post
instance,
but they don’t have to manage the state changes directly. Also, users can’t
make a mistake with the states, like publishing a post before it’s reviewed.
请注意,我们与板条箱交互的唯一类型是Post
类型。此类型将使用状态模式,并保存一个值,该值将是三个状态对象之一,表示帖子可能处于的各种状态 - 草稿、等待审核或已发布。从一种状态到另一种状态的更改将在Post
类型内部进行管理。状态会根据我们库的用户在Post
实例上调用的方法而发生变化,但他们不必直接管理状态更改。此外,用户不能对州犯错误,例如在帖子经过审核之前发布帖子。
Defining Post
and Creating a New Instance in the Draft State
在草稿状态下定义Post
并创建新实例
Let’s get started on the implementation of the library! We know we need a
public Post
struct that holds some content, so we’ll start with the
definition of the struct and an associated public new
function to create an
instance of Post
, as shown in Listing 17-12. We’ll also make a private
State
trait that will define the behavior that all state objects for a Post
must have.
让我们开始实现该库吧!我们知道我们需要一个公共Post
结构来保存一些内容,因此我们将从结构的定义和关联的公共new
函数开始来创建Post
的实例,如清单 17-12 所示。我们还将创建一个私有State
特征,它将定义Post
的所有状态对象必须具有的行为。
Then Post
will hold a trait object of Box<dyn State>
inside an Option<T>
in a private field named state
to hold the state object. You’ll see why the
Option<T>
is necessary in a bit.
然后Post
将在名为state
私有字段中的Option<T>
内保存Box<dyn State>
的特征对象,以保存状态对象。稍后您就会明白为什么Option<T>
是必要的。
Filename: src/lib.rs 文件名:src/lib.rs
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
}
trait State {}
struct Draft {}
impl State for Draft {}
The State
trait defines the behavior shared by different post states. The
state objects are Draft
, PendingReview
, and Published
, and they will all
implement the State
trait. For now, the trait doesn’t have any methods, and
we’ll start by defining just the Draft
state because that is the state we
want a post to start in.State
特征定义了不同帖子状态共享的行为。状态对象是Draft
、 PendingReview
和Published
,它们都将实现State
特征。目前,该特征没有任何方法,我们将首先定义Draft
状态,因为这是我们希望帖子开始的状态。
When we create a new Post
, we set its state
field to a Some
value that
holds a Box
. This Box
points to a new instance of the Draft
struct.
This ensures whenever we create a new instance of Post
, it will start out as
a draft. Because the state
field of Post
is private, there is no way to
create a Post
in any other state! In the Post::new
function, we set the
content
field to a new, empty String
.
当我们创建一个新的Post
时,我们将其state
字段设置为包含Box
Some
值。此Box
指向Draft
结构的新实例。这确保了每当我们创建Post
的新实例时,它都会以草稿形式开始。因为Post
的state
字段是私有的,所以没有办法在任何其他状态下创建Post
!在Post::new
函数中,我们将content
字段设置为新的空String
。
Storing the Text of the Post Content
存储帖子内容的文本
We saw in Listing 17-11 that we want to be able to call a method named
add_text
and pass it a &str
that is then added as the text content of the
blog post. We implement this as a method, rather than exposing the content
field as pub
, so that later we can implement a method that will control how
the content
field’s data is read. The add_text
method is pretty
straightforward, so let’s add the implementation in Listing 17-13 to the impl Post
block:
我们在清单 17-11 中看到,我们希望能够调用名为add_text
的方法并向其传递一个&str
,然后将其添加为博客文章的文本内容。我们将其实现为一种方法,而不是将content
字段公开为pub
,以便稍后我们可以实现一个方法来控制如何读取content
字段的数据。 add_text
方法非常简单,所以让我们将清单 17-13 中的实现添加到impl Post
块中:
Filename: src/lib.rs 文件名:src/lib.rs
The add_text
method takes a mutable reference to self
, because we’re
changing the Post
instance that we’re calling add_text
on. We then call
push_str
on the String
in content
and pass the text
argument to add to
the saved content
. This behavior doesn’t depend on the state the post is in,
so it’s not part of the state pattern. The add_text
method doesn’t interact
with the state
field at all, but it is part of the behavior we want to
support.add_text
方法采用对self
的可变引用,因为我们正在更改调用add_text
的Post
实例。然后,我们对content
中的String
调用push_str
并传递text
参数以添加到保存的content
中。此行为不取决于帖子所处的状态,因此它不是状态模式的一部分。 add_text
方法根本不与state
字段交互,但它是我们想要支持的行为的一部分。
Ensuring the Content of a Draft Post Is Empty
确保草稿帖子的内容为空
Even after we’ve called add_text
and added some content to our post, we still
want the content
method to return an empty string slice because the post is
still in the draft state, as shown on line 7 of Listing 17-11. For now, let’s
implement the content
method with the simplest thing that will fulfill this
requirement: always returning an empty string slice. We’ll change this later
once we implement the ability to change a post’s state so it can be published.
So far, posts can only be in the draft state, so the post content should always
be empty. Listing 17-14 shows this placeholder implementation:
即使我们调用了add_text
并向帖子添加了一些内容,我们仍然希望content
方法返回一个空字符串切片,因为帖子仍处于草稿状态,如清单 17-11 的第 7 行所示。现在,让我们用最简单的方法来实现content
方法来满足此要求:始终返回一个空字符串切片。一旦我们实现了更改帖子状态以便发布的功能,我们将在稍后更改此设置。到目前为止,帖子只能处于草稿状态,因此帖子内容应始终为空。清单 17-14 显示了这个占位符的实现:
Filename: src/lib.rs 文件名:src/lib.rs
With this added content
method, everything in Listing 17-11 up to line 7
works as intended.
通过这种添加content
方法,清单 17-11 中直到第 7 行的所有内容都按预期工作。
Requesting a Review of the Post Changes Its State
请求审核帖子会更改其状态
Next, we need to add functionality to request a review of a post, which should
change its state from Draft
to PendingReview
. Listing 17-15 shows this code:
接下来,我们需要添加功能来请求对帖子进行审核,这应该将其状态从Draft
更改为PendingReview
。清单 17-15 显示了以下代码:
Filename: src/lib.rs 文件名:src/lib.rs
We give Post
a public method named request_review
that will take a mutable
reference to self
. Then we call an internal request_review
method on the
current state of Post
, and this second request_review
method consumes the
current state and returns a new state.
我们为Post
提供了一个名为request_review
的公共方法,它将采用对self
的可变引用。然后我们对Post
的当前状态调用内部request_review
方法,第二个request_review
方法消耗当前状态并返回一个新状态。
We add the request_review
method to the State
trait; all types that
implement the trait will now need to implement the request_review
method.
Note that rather than having self
, &self
, or &mut self
as the first
parameter of the method, we have self: Box<Self>
. This syntax means the
method is only valid when called on a Box
holding the type. This syntax takes
ownership of Box<Self>
, invalidating the old state so the state value of the
Post
can transform into a new state.
我们将request_review
方法添加到State
特征中;所有实现该特征的类型现在都需要实现request_review
方法。请注意,我们没有使用self
、 &self
或&mut self
作为方法的第一个参数,而是使用self: Box<Self>
。此语法意味着该方法仅在保存该类型的Box
上调用时才有效。此语法获取Box<Self>
的所有权,使旧状态无效,以便Post
的状态值可以转换为新状态。
To consume the old state, the request_review
method needs to take ownership
of the state value. This is where the Option
in the state
field of Post
comes in: we call the take
method to take the Some
value out of the state
field and leave a None
in its place, because Rust doesn’t let us have
unpopulated fields in structs. This lets us move the state
value out of
Post
rather than borrowing it. Then we’ll set the post’s state
value to the
result of this operation.
要使用旧状态, request_review
方法需要获取状态值的所有权。这就是Post
的state
字段中的Option
发挥作用的地方:我们调用take
方法从state
字段中取出Some
值,并在其位置保留None
,因为 Rust 不允许我们在结构中拥有未填充的字段。这让我们可以将state
值移出Post
,而不是借用它。然后我们将帖子的state
值设置为该操作的结果。
We need to set state
to None
temporarily rather than setting it directly
with code like self.state = self.state.request_review();
to get ownership of
the state
value. This ensures Post
can’t use the old state
value after
we’ve transformed it into a new state.
我们需要暂时将state
设置为None
,而不是直接使用self.state = self.state.request_review();
之类的代码设置它。获得state
价值的所有权。这确保了在我们将旧状态值转换为新状态后, Post
无法使用旧state
值。
The request_review
method on Draft
returns a new, boxed instance of a new
PendingReview
struct, which represents the state when a post is waiting for a
review. The PendingReview
struct also implements the request_review
method
but doesn’t do any transformations. Rather, it returns itself, because when we
request a review on a post already in the PendingReview
state, it should stay
in the PendingReview
state.Draft
上的request_review
方法返回一个新的PendingReview
结构的装箱实例,它表示帖子等待审核时的状态。 PendingReview
结构还实现了request_review
方法,但不执行任何转换。相反,它会返回自身,因为当我们请求对已处于PendingReview
状态的帖子进行审阅时,它应该保持在PendingReview
状态。
Now we can start seeing the advantages of the state pattern: the
request_review
method on Post
is the same no matter its state
value. Each
state is responsible for its own rules.
现在我们可以开始看到状态模式的优点: Post
上的request_review
方法无论其state
值如何都是相同的。每个州都有自己的规则。
We’ll leave the content
method on Post
as is, returning an empty string
slice. We can now have a Post
in the PendingReview
state as well as in the
Draft
state, but we want the same behavior in the PendingReview
state.
Listing 17-11 now works up to line 10!
我们将原样保留Post
上的content
方法,返回一个空字符串切片。我们现在可以在PendingReview
状态和Draft
状态下都有一个Post
,但我们希望在PendingReview
状态下有相同的行为。清单 17-11 现在可以运行到第 10 行!
Adding approve
to Change the Behavior of content
添加approve
以更改content
的行为
The approve
method will be similar to the request_review
method: it will
set state
to the value that the current state says it should have when that
state is approved, as shown in Listing 17-16:approve
方法与request_review
方法类似:它将state
设置为当前状态规定的当状态被批准时应具有的值,如清单 17-16 所示:
Filename: src/lib.rs 文件名:src/lib.rs
We add the approve
method to the State
trait and add a new struct that
implements State
, the Published
state.
我们将approve
方法添加到State
特征中,并添加一个实现State
Published
状态)的新结构。
Similar to the way request_review
on PendingReview
works, if we call the
approve
method on a Draft
, it will have no effect because approve
will
return self
. When we call approve
on PendingReview
, it returns a new,
boxed instance of the Published
struct. The Published
struct implements the
State
trait, and for both the request_review
method and the approve
method, it returns itself, because the post should stay in the Published
state in those cases.
与PendingReview
上request_review
的工作方式类似,如果我们在Draft
上调用approve
方法,它将不会产生任何效果,因为approve
将返回self
。当我们对PendingReview
调用approve
时,它会返回Published
结构的一个新的装箱实例。 Published
结构实现了State
特征,对于request_review
方法和approve
方法,它返回自身,因为在这些情况下帖子应该保持在Published
状态。
Now we need to update the content
method on Post
. We want the value
returned from content
to depend on the current state of the Post
, so we’re
going to have the Post
delegate to a content
method defined on its state
,
as shown in Listing 17-17:
现在我们需要更新Post
上的content
方法。我们希望从content
返回的值取决于Post
的当前状态,因此我们将Post
委托给在其state
上定义的content
方法,如清单 17-17 所示:
Filename: src/lib.rs 文件名:src/lib.rs
Because the goal is to keep all these rules inside the structs that implement
State
, we call a content
method on the value in state
and pass the post
instance (that is, self
) as an argument. Then we return the value that’s
returned from using the content
method on the state
value.
因为目标是将所有这些规则保留在实现State
的结构中,所以我们对state
中的值调用content
方法,并将 post 实例(即self
)作为参数传递。然后我们返回对state
值使用content
方法返回的值。
We call the as_ref
method on the Option
because we want a reference to the
value inside the Option
rather than ownership of the value. Because state
is an Option<Box<dyn State>>
, when we call as_ref
, an Option<&Box<dyn State>>
is returned. If we didn’t call as_ref
, we would get an error because
we can’t move state
out of the borrowed &self
of the function parameter.
我们在Option
上调用as_ref
方法,因为我们想要引用Option
内的值而不是该值的所有权。因为state
是Option<Box<dyn State>>
,所以当我们调用as_ref
时,会返回Option<&Box<dyn State>>
。如果我们不调用as_ref
,我们会收到错误,因为我们无法将state
移出函数参数借用的&self
。
We then call the unwrap
method, which we know will never panic, because we
know the methods on Post
ensure that state
will always contain a Some
value when those methods are done. This is one of the cases we talked about in
the “Cases In Which You Have More Information Than the
Compiler” section of Chapter 9 when we
know that a None
value is never possible, even though the compiler isn’t able
to understand that.
然后我们调用unwrap
方法,我们知道它永远不会恐慌,因为我们知道Post
上的方法确保当这些方法完成时state
将始终包含Some
值。这是我们在第 9 章“你拥有比编译器更多信息的情况”忽略部分中讨论的情况之一,当我们知道None
值永远不可能时,即使编译器无法理解这一点。
At this point, when we call content
on the &Box<dyn State>
, deref coercion
will take effect on the &
and the Box
so the content
method will
ultimately be called on the type that implements the State
trait. That means
we need to add content
to the State
trait definition, and that is where
we’ll put the logic for what content to return depending on which state we
have, as shown in Listing 17-18:
此时,当我们在&Box<dyn State>
上调用content
时,deref 强制转换将对&
和Box
生效,因此最终将在实现State
特征的类型上调用content
方法。这意味着我们需要将content
添加到State
特征定义中,这就是我们将根据我们拥有的状态来放置返回内容的逻辑的地方,如清单 17-18 所示:
Filename: src/lib.rs 文件名:src/lib.rs
We add a default implementation for the content
method that returns an empty
string slice. That means we don’t need to implement content
on the Draft
and PendingReview
structs. The Published
struct will override the content
method and return the value in post.content
.
我们为返回空字符串切片的content
方法添加了默认实现。这意味着我们不需要在Draft
和PendingReview
结构上实现content
。 Published
结构将重写content
方法并返回post.content
中的值。
Note that we need lifetime annotations on this method, as we discussed in
Chapter 10. We’re taking a reference to a post
as an argument and returning a
reference to part of that post
, so the lifetime of the returned reference is
related to the lifetime of the post
argument.
请注意,我们需要对此方法进行生命周期注释,正如我们在第 10 章中讨论的那样。我们将对post
的引用作为参数并返回对该post
的一部分的引用,因此返回引用的生命周期与post
参数的生命周期。
And we’re done—all of Listing 17-11 now works! We’ve implemented the state
pattern with the rules of the blog post workflow. The logic related to the
rules lives in the state objects rather than being scattered throughout Post
.
我们就完成了——清单 17-11 的所有内容现在都可以工作了!我们已经使用博客文章工作流程的规则实现了状态模式。与规则相关的逻辑存在于状态对象中,而不是分散在Post
中。
Why Not An Enum? 为什么不是枚举?
You may have been wondering why we didn’t use an enum
with the different
possible post states as variants. That’s certainly a possible solution, try
it and compare the end results to see which you prefer! One disadvantage of
using an enum is every place that checks the value of the enum will need a
match
expression or similar to handle every possible variant. This could
get more repetitive than this trait object solution.
您可能想知道为什么我们不使用具有不同可能的帖子状态作为变体的enum
。这当然是一个可能的解决方案,尝试一下并比较最终结果,看看您更喜欢哪一个!使用枚举的一个缺点是每个检查枚举值的地方都需要一个match
表达式或类似的表达式来处理每种可能的变体。这可能比这个特征对象解决方案更加重复。
Trade-offs of the State Pattern
状态模式的权衡
We’ve shown that Rust is capable of implementing the object-oriented state
pattern to encapsulate the different kinds of behavior a post should have in
each state. The methods on Post
know nothing about the various behaviors. The
way we organized the code, we have to look in only one place to know the
different ways a published post can behave: the implementation of the State
trait on the Published
struct.
我们已经证明 Rust 能够实现面向对象的状态模式来封装帖子在每种状态下应具有的不同类型的行为。 Post
上的方法对各种行为一无所知。根据我们组织代码的方式,我们只需查看一个地方即可了解已发布帖子的不同行为方式: Published
结构上State
特征的实现。
If we were to create an alternative implementation that didn’t use the state
pattern, we might instead use match
expressions in the methods on Post
or
even in the main
code that checks the state of the post and changes behavior
in those places. That would mean we would have to look in several places to
understand all the implications of a post being in the published state! This
would only increase the more states we added: each of those match
expressions
would need another arm.
如果我们要创建一个不使用状态模式的替代实现,我们可能会在Post
的方法中甚至在检查帖子状态并更改这些位置的行为的main
代码中使用match
表达式。这意味着我们必须在几个地方查看才能理解帖子处于已发布状态的所有含义!这只会增加我们添加的更多状态:每个match
表达式都需要另一个臂。
With the state pattern, the Post
methods and the places we use Post
don’t
need match
expressions, and to add a new state, we would only need to add a
new struct and implement the trait methods on that one struct.
使用状态模式, Post
方法和我们使用Post
地方不需要match
表达式,并且要添加新状态,我们只需要添加一个新结构并在该结构上实现特征方法。
The implementation using the state pattern is easy to extend to add more
functionality. To see the simplicity of maintaining code that uses the state
pattern, try a few of these suggestions:
使用状态模式的实现很容易扩展以添加更多功能。要了解维护使用状态模式的代码的简单性,请尝试以下一些建议:
- Add a
reject
method that changes the post’s state fromPendingReview
back toDraft
.
添加reject
方法,将帖子的状态从PendingReview
更改回Draft
。 - Require two calls to
approve
before the state can be changed toPublished
.
需要两次调用才能approve
,然后才能将状态更改为Published
。 - Allow users to add text content only when a post is in the
Draft
state. Hint: have the state object responsible for what might change about the content but not responsible for modifying thePost
.
仅当帖子处于Draft
状态时才允许用户添加文本内容。提示:让状态对象负责内容可能发生的变化,但不负责修改Post
。
One downside of the state pattern is that, because the states implement the
transitions between states, some of the states are coupled to each other. If we
add another state between PendingReview
and Published
, such as Scheduled
,
we would have to change the code in PendingReview
to transition to
Scheduled
instead. It would be less work if PendingReview
didn’t need to
change with the addition of a new state, but that would mean switching to
another design pattern.
状态模式的一个缺点是,由于状态实现状态之间的转换,因此某些状态相互耦合。如果我们在PendingReview
和Published
之间添加另一个状态(例如Scheduled
,则必须更改PendingReview
中的代码以转换为Scheduled
。如果PendingReview
不需要因添加新状态而进行更改,那么工作量将会减少,但这意味着要切换到另一种设计模式。
Another downside is that we’ve duplicated some logic. To eliminate some of the
duplication, we might try to make default implementations for the
request_review
and approve
methods on the State
trait that return self
;
however, this would violate object safety, because the trait doesn’t know what
the concrete self
will be exactly. We want to be able to use State
as a
trait object, so we need its methods to be object safe.
另一个缺点是我们重复了一些逻辑。为了消除一些重复,我们可能会尝试对返回self
的State
特征的request_review
和approve
方法进行默认实现;然而,这会违反对象安全,因为该特征不知道具体的self
到底是什么。我们希望能够使用State
作为特征对象,因此我们需要它的方法是对象安全的。
Other duplication includes the similar implementations of the request_review
and approve
methods on Post
. Both methods delegate to the implementation of
the same method on the value in the state
field of Option
and set the new
value of the state
field to the result. If we had a lot of methods on Post
that followed this pattern, we might consider defining a macro to eliminate the
repetition (see the “Macros” section in Chapter 19).
其他重复包括Post
上request_review
和approve
方法的类似实现。这两个方法都委托对Option
的state
字段中的值执行相同的方法,并将state
字段的新值设置为结果。如果我们在Post
上有很多遵循这种模式的方法,我们可能会考虑定义一个宏来消除重复(参见第 19 章中的“宏”忽略部分)。
By implementing the state pattern exactly as it’s defined for object-oriented
languages, we’re not taking as full advantage of Rust’s strengths as we could.
Let’s look at some changes we can make to the blog
crate that can make
invalid states and transitions into compile time errors.
通过完全按照面向对象语言的定义来实现状态模式,我们并没有充分利用 Rust 的优势。让我们看一下可以对blog
箱进行的一些更改,这些更改可能会导致无效状态并转换为编译时错误。
Encoding States and Behavior as Types
将状态和行为编码为类型
We’ll show you how to rethink the state pattern to get a different set of
trade-offs. Rather than encapsulating the states and transitions completely so
outside code has no knowledge of them, we’ll encode the states into different
types. Consequently, Rust’s type checking system will prevent attempts to use
draft posts where only published posts are allowed by issuing a compiler error.
我们将向您展示如何重新思考状态模式以获得一组不同的权衡。我们不会完全封装状态和转换以使外部代码不知道它们,而是将状态编码为不同的类型。因此,Rust 的类型检查系统将通过发出编译器错误来阻止尝试使用仅允许发布的帖子的草稿帖子。
Let’s consider the first part of main
in Listing 17-11:
让我们考虑清单 17-11 中main
的第一部分:
Filename: src/main.rs 文件名:src/main.rs
We still enable the creation of new posts in the draft state using Post::new
and the ability to add text to the post’s content. But instead of having a
content
method on a draft post that returns an empty string, we’ll make it so
draft posts don’t have the content
method at all. That way, if we try to get
a draft post’s content, we’ll get a compiler error telling us the method
doesn’t exist. As a result, it will be impossible for us to accidentally
display draft post content in production, because that code won’t even compile.
Listing 17-19 shows the definition of a Post
struct and a DraftPost
struct,
as well as methods on each:
我们仍然可以使用Post::new
在草稿状态下创建新帖子,并能够向帖子内容添加文本。但是,我们不会在草稿帖子上使用返回空字符串的content
方法,而是让草稿帖子根本没有content
方法。这样,如果我们尝试获取草稿帖子的内容,我们将收到编译器错误,告诉我们该方法不存在。因此,我们不可能在生产中意外地显示草稿帖子内容,因为该代码甚至无法编译。清单 17-19 显示了Post
结构和DraftPost
结构的定义,以及每个结构的方法:
Filename: src/lib.rs 文件名:src/lib.rs
pub struct Post {
content: String,
}
pub struct DraftPost {
content: String,
}
impl Post {
pub fn new() -> DraftPost {
DraftPost {
content: String::new(),
}
}
pub fn content(&self) -> &str {
&self.content
}
}
impl DraftPost {
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
}
Both the Post
and DraftPost
structs have a private content
field that
stores the blog post text. The structs no longer have the state
field because
we’re moving the encoding of the state to the types of the structs. The Post
struct will represent a published post, and it has a content
method that
returns the content
.Post
和DraftPost
结构都有一个存储博客文章文本的私有content
字段。结构不再具有state
字段,因为我们将状态的编码转移到结构的类型。 Post
结构将表示已发布的帖子,并且它有一个返回content
content
方法。
We still have a Post::new
function, but instead of returning an instance of
Post
, it returns an instance of DraftPost
. Because content
is private
and there aren’t any functions that return Post
, it’s not possible to create
an instance of Post
right now.
我们仍然有一个Post::new
函数,但它不是返回Post
的实例,而是返回DraftPost
的实例。由于content
是私有的,并且没有任何函数返回Post
,因此现在无法创建Post
实例。
The DraftPost
struct has an add_text
method, so we can add text to
content
as before, but note that DraftPost
does not have a content
method
defined! So now the program ensures all posts start as draft posts, and draft
posts don’t have their content available for display. Any attempt to get around
these constraints will result in a compiler error.DraftPost
结构有一个add_text
方法,因此我们可以像以前一样向content
添加文本,但请注意, DraftPost
没有定义content
方法!因此,现在该程序确保所有帖子都以草稿帖子开始,并且草稿帖子的内容无法显示。任何绕过这些限制的尝试都会导致编译器错误。
Implementing Transitions as Transformations into Different Types
将转换实现为不同类型的转换
So how do we get a published post? We want to enforce the rule that a draft
post has to be reviewed and approved before it can be published. A post in the
pending review state should still not display any content. Let’s implement
these constraints by adding another struct, PendingReviewPost
, defining the
request_review
method on DraftPost
to return a PendingReviewPost
, and
defining an approve
method on PendingReviewPost
to return a Post
, as
shown in Listing 17-20:
那么我们如何获得已发布的帖子呢?我们希望强制执行这样的规则:草稿帖子必须经过审查和批准才能发布。处于待审状态的帖子不应显示任何内容。让我们通过添加另一个结构体PendingReviewPost
来实现这些约束,在DraftPost
上定义request_review
方法以返回PendingReviewPost
,并在PendingReviewPost
上定义approve
方法以返回Post
,如清单 17-20 所示:
Filename: src/lib.rs 文件名:src/lib.rs
The request_review
and approve
methods take ownership of self
, thus
consuming the DraftPost
and PendingReviewPost
instances and transforming
them into a PendingReviewPost
and a published Post
, respectively. This way,
we won’t have any lingering DraftPost
instances after we’ve called
request_review
on them, and so forth. The PendingReviewPost
struct doesn’t
have a content
method defined on it, so attempting to read its content
results in a compiler error, as with DraftPost
. Because the only way to get a
published Post
instance that does have a content
method defined is to call
the approve
method on a PendingReviewPost
, and the only way to get a
PendingReviewPost
is to call the request_review
method on a DraftPost
,
we’ve now encoded the blog post workflow into the type system.request_review
和approve
方法获取self
的所有权,从而使用DraftPost
和PendingReviewPost
实例并将它们分别转换为PendingReviewPost
和已发布的Post
。这样,在调用request_review
等之后,我们就不会再有任何残留的DraftPost
实例。 PendingReviewPost
结构没有定义content
方法,因此尝试读取其内容会导致编译器错误,与DraftPost
一样。因为获取已定义content
方法的已发布Post
实例的唯一方法是调用PendingReviewPost
上的approve
方法,而获取PendingReviewPost
唯一方法是调用DraftPost
上的request_review
方法,所以我们现在已经编码将博客文章工作流程放入类型系统中。
But we also have to make some small changes to main
. The request_review
and
approve
methods return new instances rather than modifying the struct they’re
called on, so we need to add more let post =
shadowing assignments to save
the returned instances. We also can’t have the assertions about the draft and
pending review posts’ contents be empty strings, nor do we need them: we can’t
compile code that tries to use the content of posts in those states any longer.
The updated code in main
is shown in Listing 17-21:
但我们还必须对main
进行一些小的更改。 request_review
和approve
方法返回新实例,而不是修改它们所调用的结构,因此我们需要添加更多let post =
shadowing 赋值来保存返回的实例。我们也不能让有关草稿和待审核帖子内容的断言为空字符串,我们也不需要它们:我们无法再编译尝试使用这些状态中的帖子内容的代码。 main
中更新后的代码如清单 17-21 所示:
Filename: src/main.rs 文件名:src/main.rs
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());
}
The changes we needed to make to main
to reassign post
mean that this
implementation doesn’t quite follow the object-oriented state pattern anymore:
the transformations between the states are no longer encapsulated entirely
within the Post
implementation. However, our gain is that invalid states are
now impossible because of the type system and the type checking that happens at
compile time! This ensures that certain bugs, such as display of the content of
an unpublished post, will be discovered before they make it to production.
我们需要对main
进行更改以重新分配post
意味着此实现不再完全遵循面向对象的状态模式:状态之间的转换不再完全封装在Post
实现中。然而,我们的收获是,由于类型系统和编译时发生的类型检查,无效状态现在是不可能的!这可以确保某些错误(例如未发布帖子内容的显示)在投入生产之前被发现。
Try the tasks suggested at the start of this section on the blog
crate as it
is after Listing 17-21 to see what you think about the design of this version
of the code. Note that some of the tasks might be completed already in this
design.
尝试在blog
箱上执行本节开头建议的任务(如清单 17-21 之后),看看您对此版本代码的设计有何看法。请注意,某些任务可能已在此设计中完成。
We’ve seen that even though Rust is capable of implementing object-oriented
design patterns, other patterns, such as encoding state into the type system,
are also available in Rust. These patterns have different trade-offs. Although
you might be very familiar with object-oriented patterns, rethinking the
problem to take advantage of Rust’s features can provide benefits, such as
preventing some bugs at compile time. Object-oriented patterns won’t always be
the best solution in Rust due to certain features, like ownership, that
object-oriented languages don’t have.
我们已经看到,尽管 Rust 能够实现面向对象的设计模式,但 Rust 中也可以使用其他模式,例如将状态编码到类型系统中。这些模式有不同的权衡。尽管您可能非常熟悉面向对象的模式,但重新思考问题以利用 Rust 的功能可以带来好处,例如在编译时防止一些错误。由于面向对象语言不具备的某些功能(例如所有权),面向对象模式并不总是 Rust 中的最佳解决方案。
Summary 概括
No matter whether or not you think Rust is an object-oriented language after
reading this chapter, you now know that you can use trait objects to get some
object-oriented features in Rust. Dynamic dispatch can give your code some
flexibility in exchange for a bit of runtime performance. You can use this
flexibility to implement object-oriented patterns that can help your code’s
maintainability. Rust also has other features, like ownership, that
object-oriented languages don’t have. An object-oriented pattern won’t always
be the best way to take advantage of Rust’s strengths, but is an available
option.
无论你在读完本章后是否认为 Rust 是一种面向对象的语言,你现在都知道你可以使用 Trait 对象来获得 Rust 中的一些面向对象的特性。动态调度可以为您的代码提供一些灵活性,以换取一些运行时性能。您可以利用这种灵活性来实现面向对象的模式,从而提高代码的可维护性。 Rust 还具有面向对象语言所没有的其他功能,例如所有权。面向对象的模式并不总是利用 Rust 优势的最佳方式,但它是一个可用的选择。
Next, we’ll look at patterns, which are another of Rust’s features that enable
lots of flexibility. We’ve looked at them briefly throughout the book but
haven’t seen their full capability yet. Let’s go!
接下来,我们将看看模式,这是 Rust 的另一个功能,可以提供很大的灵活性。我们在整本书中简要地了解了它们,但还没有看到它们的全部功能。我们走吧!
Patterns and Matching 模式与搭配
Patterns are a special syntax in Rust for matching against the structure of
types, both complex and simple. Using patterns in conjunction with match
expressions and other constructs gives you more control over a program’s
control flow. A pattern consists of some combination of the following:
模式是 Rust 中的一种特殊语法,用于匹配复杂和简单的类型结构。将模式与match
表达式和其他构造结合使用可以让您更好地控制程序的控制流。模式由以下内容的某种组合组成:
- Literals 文字
- Destructured arrays, enums, structs, or tuples
解构数组、枚举、结构或元组 - Variables 变量
- Wildcards 通配符
- Placeholders 占位符
Some example patterns include x
, (a, 3)
, and Some(Color::Red)
. In the
contexts in which patterns are valid, these components describe the shape of
data. Our program then matches values against the patterns to determine whether
it has the correct shape of data to continue running a particular piece of code.
一些示例模式包括x
、 (a, 3)
和Some(Color::Red)
。在模式有效的上下文中,这些组件描述了数据的形状。然后,我们的程序将值与模式进行匹配,以确定它是否具有正确的数据形状来继续运行特定的代码段。
To use a pattern, we compare it to some value. If the pattern matches the
value, we use the value parts in our code. Recall the match
expressions in
Chapter 6 that used patterns, such as the coin-sorting machine example. If the
value fits the shape of the pattern, we can use the named pieces. If it
doesn’t, the code associated with the pattern won’t run.
为了使用模式,我们将其与某个值进行比较。如果模式与值匹配,我们将在代码中使用值部分。回想一下第 6 章中使用模式的match
表达式,例如硬币分类机的示例。如果该值适合图案的形状,我们可以使用指定的片段。如果没有,与该模式关联的代码将不会运行。
This chapter is a reference on all things related to patterns. We’ll cover the
valid places to use patterns, the difference between refutable and irrefutable
patterns, and the different kinds of pattern syntax that you might see. By the
end of the chapter, you’ll know how to use patterns to express many concepts in
a clear way.
本章是所有与模式相关的内容的参考。我们将介绍使用模式的有效位置、可反驳的模式和不可反驳的模式之间的区别,以及您可能会看到的不同类型的模式语法。在本章结束时,您将了解如何使用模式以清晰的方式表达许多概念。
All the Places Patterns Can Be Used
所有地方都可以使用图案
Patterns pop up in a number of places in Rust, and you’ve been using them a lot
without realizing it! This section discusses all the places where patterns are
valid.
模式出现在 Rust 的很多地方,你已经在没有意识到的情况下经常使用它们!本节讨论模式有效的所有地方。
match
Arms
match
武器
As discussed in Chapter 6, we use patterns in the arms of match
expressions.
Formally, match
expressions are defined as the keyword match
, a value to
match on, and one or more match arms that consist of a pattern and an
expression to run if the value matches that arm’s pattern, like this:
正如第 6 章中所讨论的,我们在match
表达式的分支中使用模式。正式地, match
表达式被定义为关键字match
、要匹配的值以及一个或多个匹配臂,该匹配臂由一个模式和一个在该值与该臂的模式匹配时运行的表达式组成,如下所示:
match VALUE {
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
}
For example, here’s the match
expression from Listing 6-5 that matches on an
Option<i32>
value in the variable x
:
例如,下面是清单 6-5 中的match
表达式,它匹配变量x
中的Option<i32>
值:
match x {
None => None,
Some(i) => Some(i + 1),
}
The patterns in this match
expression are the None
and Some(i)
on the
left of each arrow.
此match
表达式中的模式是每个箭头左侧的None
和Some(i)
。
One requirement for match
expressions is that they need to be exhaustive in
the sense that all possibilities for the value in the match
expression must
be accounted for. One way to ensure you’ve covered every possibility is to have
a catchall pattern for the last arm: for example, a variable name matching any
value can never fail and thus covers every remaining case.match
表达式的一项要求是它们需要详尽无遗,因为必须考虑match
表达式中值的所有可能性。确保涵盖所有可能性的一种方法是为最后一个分支提供一个包罗万象的模式:例如,匹配任何值的变量名称永远不会失败,从而涵盖所有剩余的情况。
The particular pattern _
will match anything, but it never binds to a
variable, so it’s often used in the last match arm. The _
pattern can be
useful when you want to ignore any value not specified, for example. We’ll
cover the _
pattern in more detail in the “Ignoring Values in a
Pattern” section later in this
chapter.
特定模式_
将匹配任何内容,但它从不绑定到变量,因此它经常在最后一个匹配臂中使用。例如,当您想要忽略任何未指定的值时, _
模式可能很有用。我们将在本章后面的“忽略模式中的值”忽略部分中更详细地介绍_
模式。
Conditional if let
Expressions
条件if let
表达式
In Chapter 6 we discussed how to use if let
expressions mainly as a shorter
way to write the equivalent of a match
that only matches one case.
Optionally, if let
can have a corresponding else
containing code to run if
the pattern in the if let
doesn’t match.
在第 6 章中,我们主要讨论了如何使用if let
表达式作为一种更短的方式来编写仅匹配一种情况的匹配match
等效项。或者,如果if let
中的模式不匹配,则if let
可以有一个相应的包含代码的else
来运行。
Listing 18-1 shows that it’s also possible to mix and match if let
, else if
, and else if let
expressions. Doing so gives us more flexibility than a
match
expression in which we can express only one value to compare with the
patterns. Also, Rust doesn’t require that the conditions in a series of if let
, else if
, else if let
arms relate to each other.
清单 18-1 表明,也可以混合和匹配if let
、 else if
和else if let
表达式。这样做为我们提供了比match
表达式更大的灵活性,在匹配表达式中我们只能表达一个值来与模式进行比较。此外,Rust 不要求一系列if let
、 else if
、 else if let
分支中的条件相互关联。
The code in Listing 18-1 determines what color to make your background based on
a series of checks for several conditions. For this example, we’ve created
variables with hardcoded values that a real program might receive from user
input.
清单 18-1 中的代码根据对多个条件的一系列检查来确定背景颜色。对于此示例,我们创建了具有硬编码值的变量,真实程序可能会从用户输入接收这些值。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let favorite_color: Option<&str> = None;
let is_tuesday = false;
let age: Result<u8, _> = "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 > 30 {
println!("Using purple as the background color");
} else {
println!("Using orange as the background color");
}
} else {
println!("Using blue as the background color");
}
}
If the user specifies a favorite color, that color is used as the background.
If no favorite color is specified and today is Tuesday, the background color is
green. Otherwise, if the user specifies their age as a string and we can parse
it as a number successfully, the color is either purple or orange depending on
the value of the number. If none of these conditions apply, the background
color is blue.
如果用户指定最喜欢的颜色,则该颜色将用作背景。如果没有指定最喜欢的颜色并且今天是星期二,则背景颜色为绿色。否则,如果用户将他们的年龄指定为字符串,并且我们可以成功将其解析为数字,则颜色为紫色或橙色,具体取决于数字的值。如果这些条件都不适用,则背景颜色为蓝色。
This conditional structure lets us support complex requirements. With the
hardcoded values we have here, this example will print Using purple as the background color
.
这种条件结构使我们能够支持复杂的需求。使用此处的硬编码值,此示例将打印Using purple as the background color
。
You can see that if let
can also introduce shadowed variables in the same way
that match
arms can: the line if let Ok(age) = age
introduces a new
shadowed age
variable that contains the value inside the Ok
variant. This
means we need to place the if age > 30
condition within that block: we can’t
combine these two conditions into if let Ok(age) = age && age > 30
. The
shadowed age
we want to compare to 30 isn’t valid until the new scope starts
with the curly bracket.
您可以看到, if let
也可以采用与match
相同的方式引入阴影变量: if let Ok(age) = age
行引入了一个新的阴影age
变量,其中包含Ok
变量内的值。这意味着我们需要将if age > 30
条件放置在该块中:我们无法将这两个条件组合到if let Ok(age) = age && age > 30
中。我们想要与 30 进行比较的阴影age
在新范围以大括号开头之前才有效。
The downside of using if let
expressions is that the compiler doesn’t check
for exhaustiveness, whereas with match
expressions it does. If we omitted the
last else
block and therefore missed handling some cases, the compiler would
not alert us to the possible logic bug.
使用if let
表达式的缺点是编译器不会检查是否详尽,而使用match
表达式会检查。如果我们省略了最后一个else
块并因此错过了对某些情况的处理,编译器将不会提醒我们可能的逻辑错误。
while let
Conditional Loops
while let
条件循环
Similar in construction to if let
, the while let
conditional loop allows a
while
loop to run for as long as a pattern continues to match. In Listing
18-2 we code a while let
loop that uses a vector as a stack and prints the
values in the vector in the opposite order in which they were pushed.
与if let
结构类似, while let
条件循环允许while
循环在模式继续匹配时运行。在清单 18-2 中,我们编写了一个while let
循环,该循环使用向量作为堆栈,并按照与压入向量相反的顺序打印向量中的值。
This example prints 3, 2, and then 1. The pop
method takes the last element
out of the vector and returns Some(value)
. If the vector is empty, pop
returns None
. The while
loop continues running the code in its block as
long as pop
returns Some
. When pop
returns None
, the loop stops. We can
use while let
to pop every element off our stack.
此示例打印 3、2,然后打印 1。 pop
方法从向量中取出最后一个元素并返回Some(value)
。如果向量为空, pop
返回None
。只要pop
返回Some
, while
循环就会继续运行其块中的代码。当pop
返回None
时,循环停止。我们可以使用while let
将每个元素从堆栈中弹出。
for
Loops
for
循环
In a for
loop, the value that directly follows the keyword for
is a
pattern. For example, in for x in y
the x
is the pattern. Listing 18-3
demonstrates how to use a pattern in a for
loop to destructure, or break
apart, a tuple as part of the for
loop.
在for
循环中,直接跟在关键字for
后面的值是一个模式。例如,在for x in y
中x
是模式。清单 18-3 演示了如何在for
循环中使用模式来解构或分解元组作为for
循环的一部分。
The code in Listing 18-3 will print the following:
清单 18-3 中的代码将打印以下内容:
$ 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
We adapt an iterator using the enumerate
method so it produces a value and
the index for that value, placed into a tuple. The first value produced is the
tuple (0, 'a')
. When this value is matched to the pattern (index, value)
,
index
will be 0
and value
will be 'a'
, printing the first line of the
output.
我们使用enumerate
方法调整迭代器,以便它生成一个值以及该值的索引,并将其放入元组中。生成的第一个值是元组(0, 'a')
。当该值与模式(index, value)
匹配时, index
将为0
, value
将为'a'
,打印输出的第一行。
let
Statements
let
语句
Prior to this chapter, we had only explicitly discussed using patterns with
match
and if let
, but in fact, we’ve used patterns in other places as well,
including in let
statements. For example, consider this straightforward
variable assignment with let
:
在本章之前,我们只明确讨论了在match
和if let
中使用模式,但事实上,我们也在其他地方使用了模式,包括在let
语句中。例如,考虑使用let
进行的简单变量赋值:
Every time you’ve used a let
statement like this you’ve been using patterns,
although you might not have realized it! More formally, a let
statement looks
like this:
每次使用像这样的let
语句时,您都在使用模式,尽管您可能没有意识到!更正式地说, let
语句如下所示:
let PATTERN = EXPRESSION;
In statements like let x = 5;
with a variable name in the PATTERN
slot, the
variable name is just a particularly simple form of a pattern. Rust compares
the expression against the pattern and assigns any names it finds. So in the
let x = 5;
example, x
is a pattern that means “bind what matches here to
the variable x
.” Because the name x
is the whole pattern, this pattern
effectively means “bind everything to the variable x
, whatever the value is.”
在像let x = 5;
这样的语句中当PATTERN
槽中有变量名时,变量名只是模式的一种特别简单的形式。 Rust 将表达式与模式进行比较,并分配它找到的任何名称。所以let x = 5;
例如, x
是一个模式,表示“将此处匹配的内容绑定到变量x
”。因为名称x
是整个模式,所以该模式实际上意味着“将所有内容绑定到变量x
,无论值是什么。”
To see the pattern matching aspect of let
more clearly, consider Listing
18-4, which uses a pattern with let
to destructure a tuple.
为了更清楚地了解let
的模式匹配方面,请考虑清单 18-4,它使用let
的模式来解构元组。
Here, we match a tuple against a pattern. Rust compares the value (1, 2, 3)
to the pattern (x, y, z)
and sees that the value matches the pattern, so Rust
binds 1
to x
, 2
to y
, and 3
to z
. You can think of this tuple
pattern as nesting three individual variable patterns inside it.
在这里,我们将元组与模式进行匹配。 Rust 将值(1, 2, 3)
与模式(x, y, z)
进行比较,发现该值与模式匹配,因此 Rust 将1
绑定到x
, 2
绑定到y
, 3
绑定到z
。您可以将此元组模式视为其中嵌套了三个单独的变量模式。
If the number of elements in the pattern doesn’t match the number of elements
in the tuple, the overall type won’t match and we’ll get a compiler error. For
example, Listing 18-5 shows an attempt to destructure a tuple with three
elements into two variables, which won’t work.
如果模式中的元素数量与元组中的元素数量不匹配,则整体类型将不匹配,我们将收到编译器错误。例如,清单 18-5 展示了将一个包含三个元素的元组解构为两个变量的尝试,但这是行不通的。
Attempting to compile this code results in this type error:
尝试编译此代码会导致此类型错误:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0308]: mismatched types
--> 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
To fix the error, we could ignore one or more of the values in the tuple using
_
or ..
, as you’ll see in the “Ignoring Values in a
Pattern” section. If the problem
is that we have too many variables in the pattern, the solution is to make the
types match by removing variables so the number of variables equals the number
of elements in the tuple.
要修复该错误,我们可以使用_
或..
忽略元组中的一个或多个值,正如您将在“忽略模式中的值”忽略部分中看到的那样。如果问题是模式中的变量太多,解决方案是通过删除变量来使类型匹配,以便变量的数量等于元组中元素的数量。
Function Parameters 功能参数
Function parameters can also be patterns. The code in Listing 18-6, which
declares a function named foo
that takes one parameter named x
of type
i32
, should by now look familiar.
函数参数也可以是模式。清单 18-6 中的代码声明了一个名为foo
的函数,该函数接受一个名为x
、类型为i32
的参数,现在看起来应该很熟悉。
The x
part is a pattern! As we did with let
, we could match a tuple in a
function’s arguments to the pattern. Listing 18-7 splits the values in a tuple
as we pass it to a function.x
部分是一个模式!正如我们对let
所做的那样,我们可以将函数参数中的元组与模式进行匹配。清单 18-7 当我们将元组传递给函数时,将其拆分为元组中的值。
Filename: src/main.rs 文件名:src/main.rs
fn print_coordinates(&(x, y): &(i32, i32)) {
println!("Current location: ({x}, {y})");
}
fn main() {
let point = (3, 5);
print_coordinates(&point);
}
This code prints Current location: (3, 5)
. The values &(3, 5)
match the
pattern &(x, y)
, so x
is the value 3
and y
is the value 5
.
此代码打印Current location: (3, 5)
。值&(3, 5)
与模式&(x, y)
匹配,因此x
是值3
, y
是值5
。
We can also use patterns in closure parameter lists in the same way as in
function parameter lists, because closures are similar to functions, as
discussed in Chapter 13.
我们还可以像在函数参数列表中一样在闭包参数列表中使用模式,因为闭包与函数类似,如第 13 章所述。
At this point, you’ve seen several ways of using patterns, but patterns don’t
work the same in every place we can use them. In some places, the patterns must
be irrefutable; in other circumstances, they can be refutable. We’ll discuss
these two concepts next.
至此,您已经了解了使用模式的多种方法,但是模式并不是在我们可以使用它们的每个地方都以相同的方式工作。在某些地方,模式必须是无可辩驳的;在某些地方,模式必须是无可辩驳的。在其他情况下,它们是可以反驳的。接下来我们将讨论这两个概念。
Refutability: Whether a Pattern Might Fail to Match
可反驳性:模式是否可能无法匹配
Patterns come in two forms: refutable and irrefutable. Patterns that will match
for any possible value passed are irrefutable. An example would be x
in the
statement let x = 5;
because x
matches anything and therefore cannot fail
to match. Patterns that can fail to match for some possible value are
refutable. An example would be Some(x)
in the expression if let Some(x) = a_value
because if the value in the a_value
variable is None
rather than
Some
, the Some(x)
pattern will not match.
模式有两种形式:可反驳的和不可反驳的。与任何可能传递的值相匹配的模式是无可辩驳的。例如,语句let x = 5;
中的x
因为x
匹配任何内容,因此不可能匹配失败。无法匹配某些可能值的模式是可以反驳的。例如if let Some(x) = a_value
中的Some(x)
因为如果a_value
变量中的值为None
而不是Some
,则Some(x)
模式将不匹配。
Function parameters, let
statements, and for
loops can only accept
irrefutable patterns, because the program cannot do anything meaningful when
values don’t match. The if let
and while let
expressions accept
refutable and irrefutable patterns, but the compiler warns against
irrefutable patterns because by definition they’re intended to handle possible
failure: the functionality of a conditional is in its ability to perform
differently depending on success or failure.
函数参数、 let
语句和for
循环只能接受无可辩驳的模式,因为当值不匹配时程序无法执行任何有意义的操作。 if let
和while let
表达式接受可反驳和不可反驳的模式,但编译器会警告不可反驳的模式,因为根据定义,它们旨在处理可能的失败:条件的功能在于其能够根据成功或失败执行不同的操作。
In general, you shouldn’t have to worry about the distinction between refutable
and irrefutable patterns; however, you do need to be familiar with the concept
of refutability so you can respond when you see it in an error message. In
those cases, you’ll need to change either the pattern or the construct you’re
using the pattern with, depending on the intended behavior of the code.
一般来说,您不必担心可反驳模式和不可反驳模式之间的区别;但是,您确实需要熟悉可反驳性的概念,以便在错误消息中看到它时可以做出响应。在这些情况下,您需要更改模式或使用该模式的构造,具体取决于代码的预期行为。
Let’s look at an example of what happens when we try to use a refutable pattern
where Rust requires an irrefutable pattern and vice versa. Listing 18-8 shows a
let
statement, but for the pattern we’ve specified Some(x)
, a refutable
pattern. As you might expect, this code will not compile.
让我们看一个例子,看看当我们尝试使用可反驳的模式时会发生什么,而 Rust 需要不可反驳的模式,反之亦然。清单 18-8 显示了一个let
语句,但对于我们指定的模式Some(x)
,这是一个可反驳的模式。正如您所料,这段代码将无法编译。
If some_option_value
was a None
value, it would fail to match the pattern
Some(x)
, meaning the pattern is refutable. However, the let
statement can
only accept an irrefutable pattern because there is nothing valid the code can
do with a None
value. At compile time, Rust will complain that we’ve tried to
use a refutable pattern where an irrefutable pattern is required:
如果some_option_value
是None
值,它将无法匹配模式Some(x)
,这意味着该模式是可反驳的。但是, let
语句只能接受无可辩驳的模式,因为代码无法对None
值执行任何有效操作。在编译时,Rust 会抱怨我们试图在需要不可反驳模式的地方使用可反驳模式:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0005]: refutable pattern in local binding
--> 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/ch18-02-refutability.html
= note: the matched value is of type `Option<i32>`
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
Because we didn’t cover (and couldn’t cover!) every valid value with the
pattern Some(x)
, Rust rightfully produces a compiler error.
因为我们没有用Some(x)
模式覆盖(也无法覆盖!)每个有效值,Rust 理所当然地会产生编译器错误。
If we have a refutable pattern where an irrefutable pattern is needed, we can
fix it by changing the code that uses the pattern: instead of using let
, we
can use if let
. Then if the pattern doesn’t match, the code will just skip
the code in the curly brackets, giving it a way to continue validly. Listing
18-9 shows how to fix the code in Listing 18-8.
如果我们有一个需要不可反驳模式的可反驳模式,我们可以通过更改使用该模式的代码来修复它:我们可以使用 if let
而不是使用if let
。然后,如果模式不匹配,代码将跳过大括号中的代码,从而提供有效继续的方法。清单 18-9 显示了如何修复清单 18-8 中的代码。
We’ve given the code an out! This code is perfectly valid now. However,
if we give if let
an irrefutable pattern (a pattern that will always
match), such as x
, as shown in Listing 18-10, the compiler will give a
warning.
我们已经给出了代码!该代码现在完全有效。但是,如果我们给出if let
一个无可辩驳的模式(始终匹配的模式),例如x
,如清单 18-10 所示,编译器将给出警告。
Rust complains that it doesn’t make sense to use if let
with an irrefutable
pattern:
Rust 抱怨说, if let
与无可辩驳的模式一起使用是没有意义的:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
warning: irrefutable `if let` pattern
--> 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
For this reason, match arms must use refutable patterns, except for the last
arm, which should match any remaining values with an irrefutable pattern. Rust
allows us to use an irrefutable pattern in a match
with only one arm, but
this syntax isn’t particularly useful and could be replaced with a simpler
let
statement.
因此,匹配臂必须使用可反驳的模式,最后一个臂除外,它应该将任何剩余的值与不可反驳的模式相匹配。 Rust 允许我们在只有一只手臂的match
中使用无可辩驳的模式,但这种语法并不是特别有用,可以用更简单的let
语句替换。
Now that you know where to use patterns and the difference between refutable
and irrefutable patterns, let’s cover all the syntax we can use to create
patterns.
现在您已经知道在哪里使用模式以及可反驳模式和不可反驳模式之间的区别,让我们介绍可用于创建模式的所有语法。
Pattern Syntax 模式语法
In this section, we gather all the syntax valid in patterns and discuss why and
when you might want to use each one.
在本节中,我们收集模式中有效的所有语法,并讨论您可能想要使用每一种语法的原因和时间。
Matching Literals 匹配文字
As you saw in Chapter 6, you can match patterns against literals directly. The
following code gives some examples:
正如您在第 6 章中看到的,您可以直接将模式与文字进行匹配。下面的代码给出了一些示例:
This code prints one
because the value in x
is 1. This syntax is useful
when you want your code to take an action if it gets a particular concrete
value.
此代码打印one
因为x
中的值为 1。当您希望代码在获取特定具体值时执行操作时,此语法非常有用。
Matching Named Variables 匹配命名变量
Named variables are irrefutable patterns that match any value, and we’ve used
them many times in the book. However, there is a complication when you use
named variables in match
expressions. Because match
starts a new scope,
variables declared as part of a pattern inside the match
expression will
shadow those with the same name outside the match
construct, as is the case
with all variables. In Listing 18-11, we declare a variable named x
with the
value Some(5)
and a variable y
with the value 10
. We then create a
match
expression on the value x
. Look at the patterns in the match arms and
println!
at the end, and try to figure out what the code will print before
running this code or reading further.
命名变量是匹配任何值的无可辩驳的模式,我们在书中多次使用它们。但是,当您在match
表达式中使用命名变量时,会出现一些复杂情况。因为match
启动一个新的作用域,所以声明为match
表达式内模式一部分的变量将遮蔽match
构造外部的同名变量,就像所有变量的情况一样。在清单 18-11 中,我们声明了一个名为x
、值为Some(5)
的变量和一个值为10
变量y
。然后我们对值x
创建一个match
表达式。看看火柴臂和println!
最后,在运行此代码或进一步阅读之前尝试弄清楚代码将打印什么。
Filename: src/main.rs 文件名:src/main.rs
Let’s walk through what happens when the match
expression runs. The pattern
in the first match arm doesn’t match the defined value of x
, so the code
continues.
让我们看一下match
表达式运行时会发生什么。第一个匹配臂中的模式与x
的定义值不匹配,因此代码继续。
The pattern in the second match arm introduces a new variable named y
that
will match any value inside a Some
value. Because we’re in a new scope inside
the match
expression, this is a new y
variable, not the y
we declared at
the beginning with the value 10. This new y
binding will match any value
inside a Some
, which is what we have in x
. Therefore, this new y
binds to
the inner value of the Some
in x
. That value is 5
, so the expression for
that arm executes and prints Matched, y = 5
.
第二个匹配臂中的模式引入了一个名为y
的新变量,它将匹配Some
值内的任何值。因为我们处于match
表达式内的新作用域,所以这是一个新的y
变量,而不是我们在开头声明的值为 10 的y
。这个新y
绑定将匹配Some
内的任何值,这就是我们所拥有的在x
中。因此,这个新的y
绑定到x
中Some
的内部值。该值为5
,因此该臂的表达式将执行并打印Matched, y = 5
。
If x
had been a None
value instead of Some(5)
, the patterns in the first
two arms wouldn’t have matched, so the value would have matched to the
underscore. We didn’t introduce the x
variable in the pattern of the
underscore arm, so the x
in the expression is still the outer x
that hasn’t
been shadowed. In this hypothetical case, the match
would print Default case, x = None
.
如果x
是None
值而不是Some(5)
,则前两个臂中的模式将不匹配,因此该值将与下划线匹配。我们没有在下划线臂的模式中引入x
变量,因此表达式中的x
仍然是没有被遮蔽的外部x
。在这个假设的情况下, match
将打印Default case, x = None
。
When the match
expression is done, its scope ends, and so does the scope of
the inner y
. The last println!
produces at the end: x = Some(5), y = 10
.
当match
表达式完成时,它的范围结束,内部y
的范围也结束。最后的println!
at the end: x = Some(5), y = 10
。
To create a match
expression that compares the values of the outer x
and
y
, rather than introducing a shadowed variable, we would need to use a match
guard conditional instead. We’ll talk about match guards later in the “Extra
Conditionals with Match Guards” section.
要创建一个比较外部x
和y
值的match
表达式,而不是引入隐藏变量,我们需要使用匹配防护条件。我们稍后将在“带有匹配卫士的额外条件”忽略部分讨论匹配卫士。
Multiple Patterns 多种模式
In match
expressions, you can match multiple patterns using the |
syntax,
which is the pattern or operator. For example, in the following code we match
the value of x
against the match arms, the first of which has an or option,
meaning if the value of x
matches either of the values in that arm, that
arm’s code will run:
在match
表达式中,您可以使用|
来匹配多个模式。语法,即模式或运算符。例如,在下面的代码中,我们将x
的值与匹配臂进行匹配,其中第一个匹配臂有一个or选项,这意味着如果x
的值与该臂中的任何一个值匹配,则该臂的代码将运行:
This code prints one or two
.
此代码打印one or two
.
Matching Ranges of Values with ..=
使用..=
匹配值范围
The ..=
syntax allows us to match to an inclusive range of values. In the
following code, when a pattern matches any of the values within the given
range, that arm will execute:..=
语法允许我们匹配包含范围的值。在以下代码中,当模式与给定范围内的任何值匹配时,该臂将执行:
If x
is 1, 2, 3, 4, or 5, the first arm will match. This syntax is more
convenient for multiple match values than using the |
operator to express the
same idea; if we were to use |
we would have to specify 1 | 2 | 3 | 4 | 5
.
Specifying a range is much shorter, especially if we want to match, say, any
number between 1 and 1,000!
如果x
为 1、2、3、4 或 5,则第一个臂将匹配。对于多个匹配值,此语法比使用|
更方便。运算符表达相同的想法;如果我们要使用|
我们必须指定1 | 2 | 3 | 4 | 5
.指定范围要短得多,尤其是当我们想要匹配 1 到 1,000 之间的任何数字时!
The compiler checks that the range isn’t empty at compile time, and because the
only types for which Rust can tell if a range is empty or not are char
and
numeric values, ranges are only allowed with numeric or char
values.
编译器在编译时检查范围是否为空,并且由于 Rust 可以判断范围是否为空的唯一类型是char
和数值,因此范围仅允许包含数字或char
值。
Here is an example using ranges of char
values:
以下是使用char
值范围的示例:
Rust can tell that 'c'
is within the first pattern’s range and prints early ASCII letter
.
Rust 可以判断'c'
在第一个模式的范围内并打印early ASCII letter
。
Destructuring to Break Apart Values
解构以分解价值观
We can also use patterns to destructure structs, enums, and tuples to use
different parts of these values. Let’s walk through each value.
我们还可以使用模式来解构结构、枚举和元组,以使用这些值的不同部分。让我们来看看每个值。
Destructuring Structs 解构结构
Listing 18-12 shows a Point
struct with two fields, x
and y
, that we can
break apart using a pattern with a let
statement.
清单 18-12 显示了一个具有两个字段x
和y
的Point
结构,我们可以使用带有let
语句的模式将其分解。
Filename: src/main.rs 文件名:src/main.rs
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);
}
This code creates the variables a
and b
that match the values of the x
and y
fields of the p
struct. This example shows that the names of the
variables in the pattern don’t have to match the field names of the struct.
However, it’s common to match the variable names to the field names to make it
easier to remember which variables came from which fields. Because of this
common usage, and because writing let Point { x: x, y: y } = p;
contains a
lot of duplication, Rust has a shorthand for patterns that match struct fields:
you only need to list the name of the struct field, and the variables created
from the pattern will have the same names. Listing 18-13 behaves in the same
way as the code in Listing 18-12, but the variables created in the let
pattern are x
and y
instead of a
and b
.
此代码创建与p
结构的x
和y
字段的值匹配的变量a
和b
。此示例表明模式中变量的名称不必与结构的字段名称匹配。但是,通常将变量名称与字段名称相匹配,以便更容易记住哪些变量来自哪些字段。由于这种常见用法,并且因为写作let Point { x: x, y: y } = p;
包含大量重复,Rust 有一个匹配结构体字段的模式的简写:你只需要列出结构体字段的名称,从该模式创建的变量将具有相同的名称。清单 18-13 的行为方式与清单 18-12 中的代码相同,但在let
模式中创建的变量是x
和y
而不是a
和b
。
Filename: src/main.rs 文件名:src/main.rs
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);
}
This code creates the variables x
and y
that match the x
and y
fields
of the p
variable. The outcome is that the variables x
and y
contain the
values from the p
struct.
此代码创建与p
变量的x
和y
字段匹配的变量x
和y
。结果是变量x
和y
包含p
结构中的值。
We can also destructure with literal values as part of the struct pattern
rather than creating variables for all the fields. Doing so allows us to test
some of the fields for particular values while creating variables to
destructure the other fields.
我们还可以使用文字值作为结构模式的一部分进行解构,而不是为所有字段创建变量。这样做允许我们测试某些字段的特定值,同时创建变量来解构其他字段。
In Listing 18-14, we have a match
expression that separates Point
values
into three cases: points that lie directly on the x
axis (which is true when
y = 0
), on the y
axis (x = 0
), or neither.
在清单 18-14 中,我们有一个match
表达式,它将Point
值分为三种情况:直接位于x
轴上的点(当y = 0
时为真)、位于y
轴上的点 ( x = 0
) 或两者都不位于。
Filename: src/main.rs 文件名:src/main.rs
The first arm will match any point that lies on the x
axis by specifying that
the y
field matches if its value matches the literal 0
. The pattern still
creates an x
variable that we can use in the code for this arm.
第一个臂将通过指定y
字段的值与文字0
匹配来匹配位于x
轴上的任何点。该模式仍然创建一个x
变量,我们可以在该手臂的代码中使用它。
Similarly, the second arm matches any point on the y
axis by specifying that
the x
field matches if its value is 0
and creates a variable y
for the
value of the y
field. The third arm doesn’t specify any literals, so it
matches any other Point
and creates variables for both the x
and y
fields.
类似地,第二个臂通过指定x
字段的值为0
时匹配y
轴上的任意点,并为y
字段的值创建变量y
。第三个臂没有指定任何文字,因此它匹配任何其他Point
并为x
和y
字段创建变量。
In this example, the value p
matches the second arm by virtue of x
containing a 0, so this code will print On the y axis at 7
.
在此示例中,值p
通过x
包含 0 来匹配第二个臂,因此此代码将打印On the y axis at 7
。
Remember that a match
expression stops checking arms once it has found the
first matching pattern, so even though Point { x: 0, y: 0}
is on the x
axis
and the y
axis, this code would only print On the x axis at 0
.
请记住,一旦找到第一个匹配模式, match
表达式就会停止检查臂,因此即使Point { x: 0, y: 0}
位于x
轴和y
轴上,此代码也只会打印On the x axis at 0
.
Destructuring Enums 解构枚举
We’ve destructured enums in this book (for example, Listing 6-5 in Chapter 6),
but haven’t yet explicitly discussed that the pattern to destructure an enum
corresponds to the way the data stored within the enum is defined. As an
example, in Listing 18-15 we use the Message
enum from Listing 6-2 and write
a match
with patterns that will destructure each inner value.
我们在本书中解构了枚举(例如,第 6 章中的清单 6-5),但尚未明确讨论解构枚举的模式对应于枚举中存储的数据的定义方式。例如,在清单 18-15 中,我们使用清单 6-2 中的Message
枚举,并编写一个match
模式,该模式将解构每个内部值。
Filename: src/main.rs 文件名:src/main.rs
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 => {
println!("The Quit variant has no data to destructure.");
}
Message::Move { x, y } => {
println!("Move in the x direction {x} and in the y direction {y}");
}
Message::Write(text) => {
println!("Text message: {text}");
}
Message::ChangeColor(r, g, b) => {
println!("Change the color to red {r}, green {g}, and blue {b}")
}
}
}
This code will print Change the color to red 0, green 160, and blue 255
. Try
changing the value of msg
to see the code from the other arms run.
此代码将打印Change the color to red 0, green 160, and blue 255
。尝试更改msg
的值以查看其他分支的代码运行情况。
For enum variants without any data, like Message::Quit
, we can’t destructure
the value any further. We can only match on the literal Message::Quit
value,
and no variables are in that pattern.
对于没有任何数据的枚举变体,例如Message::Quit
,我们无法进一步解构该值。我们只能匹配文字Message::Quit
值,并且该模式中没有变量。
For struct-like enum variants, such as Message::Move
, we can use a pattern
similar to the pattern we specify to match structs. After the variant name, we
place curly brackets and then list the fields with variables so we break apart
the pieces to use in the code for this arm. Here we use the shorthand form as
we did in Listing 18-13.
对于类似结构体的枚举变体,例如Message::Move
,我们可以使用与我们指定的模式类似的模式来匹配结构体。在变体名称之后,我们放置大括号,然后列出带有变量的字段,以便我们分解各个部分以在该手臂的代码中使用。这里我们使用简写形式,如清单 18-13 所示。
For tuple-like enum variants, like Message::Write
that holds a tuple with one
element and Message::ChangeColor
that holds a tuple with three elements, the
pattern is similar to the pattern we specify to match tuples. The number of
variables in the pattern must match the number of elements in the variant we’re
matching.
对于类似元组的枚举变体,例如Message::Write
保存一个包含一个元素的元组, Message::ChangeColor
保存一个包含三个元素的元组,该模式类似于我们指定匹配元组的模式。模式中的变量数量必须与我们要匹配的变体中的元素数量相匹配。
Destructuring Nested Structs and Enums
解构嵌套结构和枚举
So far, our examples have all been matching structs or enums one level deep,
but matching can work on nested items too! For example, we can refactor the
code in Listing 18-15 to support RGB and HSV colors in the ChangeColor
message, as shown in Listing 18-16.
到目前为止,我们的示例都匹配一级深度的结构或枚举,但匹配也可以用于嵌套项!例如,我们可以重构清单18-15中的代码,以支持ChangeColor
消息中的RGB和HSV颜色,如清单18-16所示。
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)) => {
println!("Change color to red {r}, green {g}, and blue {b}");
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!("Change color to hue {h}, saturation {s}, value {v}")
}
_ => (),
}
}
The pattern of the first arm in the match
expression matches a
Message::ChangeColor
enum variant that contains a Color::Rgb
variant; then
the pattern binds to the three inner i32
values. The pattern of the second
arm also matches a Message::ChangeColor
enum variant, but the inner enum
matches Color::Hsv
instead. We can specify these complex conditions in one
match
expression, even though two enums are involved.match
表达式中第一个臂的模式与包含Color::Rgb
变体的Message::ChangeColor
枚举变体相匹配;然后该模式绑定到三个内部i32
值。第二个臂的模式也与Message::ChangeColor
枚举变体匹配,但内部枚举与Color::Hsv
匹配。即使涉及两个枚举,我们也可以在一个match
表达式中指定这些复杂的条件。
Destructuring Structs and Tuples
解构结构和元组
We can mix, match, and nest destructuring patterns in even more complex ways.
The following example shows a complicated destructure where we nest structs and
tuples inside a tuple and destructure all the primitive values out:
我们可以以更复杂的方式混合、匹配和嵌套解构模式。以下示例显示了一个复杂的解构,其中我们将结构和元组嵌套在元组内,并解构所有原始值:
This code lets us break complex types into their component parts so we can use
the values we’re interested in separately.
这段代码让我们可以将复杂类型分解为它们的组成部分,这样我们就可以单独使用我们感兴趣的值。
Destructuring with patterns is a convenient way to use pieces of values, such
as the value from each field in a struct, separately from each other.
使用模式解构是一种使用值片段的便捷方法,例如结构中每个字段的值,彼此分开。
Ignoring Values in a Pattern
忽略模式中的值
You’ve seen that it’s sometimes useful to ignore values in a pattern, such as
in the last arm of a match
, to get a catchall that doesn’t actually do
anything but does account for all remaining possible values. There are a few
ways to ignore entire values or parts of values in a pattern: using the _
pattern (which you’ve seen), using the _
pattern within another pattern,
using a name that starts with an underscore, or using ..
to ignore remaining
parts of a value. Let’s explore how and why to use each of these patterns.
您已经看到,有时忽略模式中的值很有用,例如在match
的最后一个分支中,以获得一个实际上不执行任何操作但确实考虑了所有剩余可能值的包罗万象的内容。有几种方法可以忽略模式中的整个值或部分值:使用_
模式(您已经见过)、在另一个模式中使用_
模式、使用以下划线开头的名称或使用..
忽略值的剩余部分。让我们探讨一下如何以及为何使用这些模式。
Ignoring an Entire Value with _
使用_
忽略整个值
We’ve used the underscore as a wildcard pattern that will match any value but
not bind to the value. This is especially useful as the last arm in a match
expression, but we can also use it in any pattern, including function
parameters, as shown in Listing 18-17.
我们使用下划线作为通配符模式,它将匹配任何值但不绑定到该值。这作为match
表达式中的最后一个分支特别有用,但我们也可以在任何模式中使用它,包括函数参数,如清单 18-17 所示。
Filename: src/main.rs 文件名:src/main.rs
fn foo(_: i32, y: i32) {
println!("This code only uses the y parameter: {y}");
}
fn main() {
foo(3, 4);
}
This code will completely ignore the value 3
passed as the first argument,
and will print This code only uses the y parameter: 4
.
此代码将完全忽略作为第一个参数传递的值3
,并打印This code only uses the y parameter: 4
。
In most cases when you no longer need a particular function parameter, you
would change the signature so it doesn’t include the unused parameter. Ignoring
a function parameter can be especially useful in cases when, for example,
you’re implementing a trait when you need a certain type signature but the
function body in your implementation doesn’t need one of the parameters. You
then avoid getting a compiler warning about unused function parameters, as you
would if you used a name instead.
在大多数情况下,当您不再需要特定的函数参数时,您可以更改签名,使其不包含未使用的参数。例如,当您需要某种类型签名但实现中的函数体不需要其中一个参数时,忽略函数参数可能特别有用。这样,您就可以避免收到有关未使用的函数参数的编译器警告,就像您使用名称一样。
Ignoring Parts of a Value with a Nested _
忽略带有嵌套_
的部分值
We can also use _
inside another pattern to ignore just part of a value, for
example, when we want to test for only part of a value but have no use for the
other parts in the corresponding code we want to run. Listing 18-18 shows code
responsible for managing a setting’s value. The business requirements are that
the user should not be allowed to overwrite an existing customization of a
setting but can unset the setting and give it a value if it is currently unset.
我们还可以在另一个模式中使用_
来忽略值的一部分,例如,当我们只想测试值的一部分但对我们要运行的相应代码中的其他部分没有用处时。清单 18-18 显示了负责管理设置值的代码。业务要求是不允许用户覆盖设置的现有自定义,但可以取消设置并为其指定值(如果当前未设置)。
This code will print Can't overwrite an existing customized value
and then
setting is Some(5)
. In the first match arm, we don’t need to match on or use
the values inside either Some
variant, but we do need to test for the case
when setting_value
and new_setting_value
are the Some
variant. In that
case, we print the reason for not changing setting_value
, and it doesn’t get
changed.
此代码将打印Can't overwrite an existing customized value
,然后setting is Some(5)
。在第一个匹配臂中,我们不需要匹配或使用Some
变体中的值,但我们确实需要测试setting_value
和new_setting_value
是Some
变体时的情况。在这种情况下,我们打印不更改setting_value
的原因,并且它不会改变。
In all other cases (if either setting_value
or new_setting_value
are
None
) expressed by the _
pattern in the second arm, we want to allow
new_setting_value
to become setting_value
.
在第二个分支中的_
模式表示的所有其他情况下(如果setting_value
或new_setting_value
为None
),我们希望允许new_setting_value
变为setting_value
。
We can also use underscores in multiple places within one pattern to ignore
particular values. Listing 18-19 shows an example of ignoring the second and
fourth values in a tuple of five items.
我们还可以在一种模式中的多个位置使用下划线来忽略特定值。清单 18-19 显示了忽略五个项目的元组中的第二个和第四个值的示例。
This code will print Some numbers: 2, 8, 32
, and the values 4 and 16 will be
ignored.
此代码将打印Some numbers: 2, 8, 32
,并且值 4 和 16 将被忽略。
Ignoring an Unused Variable by Starting Its Name with _
通过名称以_
开头来忽略未使用的变量
If you create a variable but don’t use it anywhere, Rust will usually issue a
warning because an unused variable could be a bug. However, sometimes it’s
useful to be able to create a variable you won’t use yet, such as when you’re
prototyping or just starting a project. In this situation, you can tell Rust
not to warn you about the unused variable by starting the name of the variable
with an underscore. In Listing 18-20, we create two unused variables, but when
we compile this code, we should only get a warning about one of them.
如果您创建一个变量但不在任何地方使用它,Rust 通常会发出警告,因为未使用的变量可能是一个错误。然而,有时能够创建一个您还不会使用的变量是很有用的,例如当您正在制作原型或刚刚启动一个项目时。在这种情况下,您可以通过以下划线开头的变量名称来告诉 Rust 不要警告您有关未使用变量的信息。在清单 18-20 中,我们创建了两个未使用的变量,但是当我们编译此代码时,我们应该只收到有关其中一个的警告。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let _x = 5;
let y = 10;
}
Here we get a warning about not using the variable y
, but we don’t get a
warning about not using _x
.
在这里,我们收到有关不使用变量y
警告,但没有收到有关不使用_x
警告。
Note that there is a subtle difference between using only _
and using a name
that starts with an underscore. The syntax _x
still binds the value to the
variable, whereas _
doesn’t bind at all. To show a case where this
distinction matters, Listing 18-21 will provide us with an error.
请注意,仅使用_
和使用以下划线开头的名称之间存在细微差别。语法_x
仍然将值绑定到变量,而_
根本不绑定。为了展示这种区别很重要的情况,清单 18-21 将为我们提供一个错误。
We’ll receive an error because the s
value will still be moved into _s
,
which prevents us from using s
again. However, using the underscore by itself
doesn’t ever bind to the value. Listing 18-22 will compile without any errors
because s
doesn’t get moved into _
.
我们会收到一个错误,因为s
值仍会被移动到_s
中,这会阻止我们再次使用s
。但是,单独使用下划线不会绑定到该值。清单 18-22 编译时不会出现任何错误,因为s
不会移动到_
中。
This code works just fine because we never bind s
to anything; it isn’t moved.
这段代码工作得很好,因为我们从不将s
绑定到任何东西;它没有被移动。
Ignoring Remaining Parts of a Value with ..
使用..
忽略值的剩余部分
With values that have many parts, we can use the ..
syntax to use specific
parts and ignore the rest, avoiding the need to list underscores for each
ignored value. The ..
pattern ignores any parts of a value that we haven’t
explicitly matched in the rest of the pattern. In Listing 18-23, we have a
Point
struct that holds a coordinate in three-dimensional space. In the
match
expression, we want to operate only on the x
coordinate and ignore
the values in the y
and z
fields.
对于包含多个部分的值,我们可以使用..
语法来使用特定部分并忽略其余部分,从而避免需要为每个忽略的值列出下划线。 ..
模式会忽略我们在模式的其余部分中未显式匹配的值的任何部分。在清单 18-23 中,我们有一个Point
结构,它保存三维空间中的坐标。在match
表达式中,我们只想对x
坐标进行操作,而忽略y
和z
字段中的值。
We list the x
value and then just include the ..
pattern. This is quicker
than having to list y: _
and z: _
, particularly when we’re working with
structs that have lots of fields in situations where only one or two fields are
relevant.
我们列出x
值,然后仅包含..
模式。这比列出y: _
和z: _
更快,特别是当我们在只有一两个字段相关的情况下使用具有大量字段的结构时。
The syntax ..
will expand to as many values as it needs to be. Listing 18-24
shows how to use ..
with a tuple.
语法..
将扩展为所需数量的值。清单 18-24 展示了如何将..
与元组一起使用。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, .., last) => {
println!("Some numbers: {first}, {last}");
}
}
}
In this code, the first and last value are matched with first
and last
. The
..
will match and ignore everything in the middle.
在此代码中,第一个和最后一个值与first
和last
匹配。 ..
将匹配并忽略中间的所有内容。
However, using ..
must be unambiguous. If it is unclear which values are
intended for matching and which should be ignored, Rust will give us an error.
Listing 18-25 shows an example of using ..
ambiguously, so it will not
compile.
然而,使用..
必须是明确的。如果不清楚哪些值要匹配,哪些值应该被忽略,Rust 会给我们一个错误。清单 18-25 显示了一个不明确地使用..
的示例,因此它无法编译。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(.., second, ..) => {
println!("Some numbers: {second}")
},
}
}
When we compile this example, we get this error:
当我们编译这个例子时,我们得到这个错误:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error: `..` can only be used once per tuple pattern
--> src/main.rs:5:22
|
5 | (.., second, ..) => {
| -- ^^ can only be used once per tuple pattern
| |
| previously used here
error: could not compile `patterns` (bin "patterns") due to 1 previous error
It’s impossible for Rust to determine how many values in the tuple to ignore
before matching a value with second
and then how many further values to
ignore thereafter. This code could mean that we want to ignore 2
, bind
second
to 4
, and then ignore 8
, 16
, and 32
; or that we want to ignore
2
and 4
, bind second
to 8
, and then ignore 16
and 32
; and so forth.
The variable name second
doesn’t mean anything special to Rust, so we get a
compiler error because using ..
in two places like this is ambiguous.
Rust 不可能确定在将某个值与second
值匹配之前要忽略元组中的多少个值,以及之后要忽略多少个值。这段代码可能意味着我们想要忽略2
,将second
绑定到4
,然后忽略8
、 16
和32
;或者我们想忽略2
和4
,将second
绑定到8
,然后忽略16
和32
;等等。变量名second
对 Rust 来说没有任何特殊意义,因此我们会得到一个编译器错误,因为在这样的两个地方使用..
是不明确的。
Extra Conditionals with Match Guards
带有 Match Guard 的额外条件
A match guard is an additional if
condition, specified after the pattern in
a match
arm, that must also match for that arm to be chosen. Match guards are
useful for expressing more complex ideas than a pattern alone allows.
匹配防护是一个附加的if
条件,在match
臂中的模式之后指定,它也必须匹配才能选择该臂。匹配守卫对于表达比单独模式所允许的更复杂的想法非常有用。
The condition can use variables created in the pattern. Listing 18-26 shows a
match
where the first arm has the pattern Some(x)
and also has a match
guard of if x % 2 == 0
(which will be true if the number is even).
条件可以使用模式中创建的变量。清单 18-26 显示了一个match
,其中第一个臂具有模式Some(x)
,并且还具有if x % 2 == 0
的匹配防护(如果数字为偶数,则为 true)。
This example will print The number 4 is even
. When num
is compared to the
pattern in the first arm, it matches, because Some(4)
matches Some(x)
. Then
the match guard checks whether the remainder of dividing x
by 2 is equal to
0, and because it is, the first arm is selected.
此示例将打印The number 4 is even
。当num
与第一个臂中的模式进行比较时,它匹配,因为Some(4)
匹配Some(x)
。然后比赛守卫检查x
除以 2 的余数是否等于 0,因为是,所以选择第一个臂。
If num
had been Some(5)
instead, the match guard in the first arm would
have been false because the remainder of 5 divided by 2 is 1, which is not
equal to 0. Rust would then go to the second arm, which would match because the
second arm doesn’t have a match guard and therefore matches any Some
variant.
如果num
为Some(5)
,则第一个分支中的匹配守卫将为 false,因为 5 除以 2 的余数为 1,不等于 0。然后 Rust 将转到第二个分支,这将匹配,因为第二条臂没有匹配守卫,因此匹配任何Some
变体。
There is no way to express the if x % 2 == 0
condition within a pattern, so
the match guard gives us the ability to express this logic. The downside of
this additional expressiveness is that the compiler doesn’t try to check for
exhaustiveness when match guard expressions are involved.
无法在模式中表达if x % 2 == 0
条件,因此匹配守卫使我们能够表达此逻辑。这种额外表达能力的缺点是,当涉及匹配保护表达式时,编译器不会尝试检查是否详尽。
In Listing 18-11, we mentioned that we could use match guards to solve our
pattern-shadowing problem. Recall that we created a new variable inside the
pattern in the match
expression instead of using the variable outside the
match
. That new variable meant we couldn’t test against the value of the
outer variable. Listing 18-27 shows how we can use a match guard to fix this
problem.
在清单 18-11 中,我们提到可以使用匹配守卫来解决模式阴影问题。回想一下,我们在match
表达式的模式内部创建了一个新变量,而不是使用match
外部的变量。这个新变量意味着我们无法测试外部变量的值。清单18-27展示了我们如何使用匹配守卫来解决这个问题。
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = Some(5);
let y = 10;
match x {
Some(50) => println!("Got 50"),
Some(n) if n == y => println!("Matched, n = {n}"),
_ => println!("Default case, x = {x:?}"),
}
println!("at the end: x = {x:?}, y = {y}");
}
This code will now print Default case, x = Some(5)
. The pattern in the second
match arm doesn’t introduce a new variable y
that would shadow the outer y
,
meaning we can use the outer y
in the match guard. Instead of specifying the
pattern as Some(y)
, which would have shadowed the outer y
, we specify
Some(n)
. This creates a new variable n
that doesn’t shadow anything because
there is no n
variable outside the match
.
此代码现在将打印Default case, x = Some(5)
。第二个匹配臂中的模式不会引入会遮蔽外部y
的新变量y
,这意味着我们可以在匹配防护中使用外部y
。我们没有将模式指定为Some(y)
,这会遮盖外部y
,而是指定Some(n)
。这会创建一个新变量n
,它不会隐藏任何内容,因为在match
之外没有n
变量。
The match guard if n == y
is not a pattern and therefore doesn’t introduce
new variables. This y
is the outer y
rather than a new shadowed y
, and
we can look for a value that has the same value as the outer y
by comparing
n
to y
.
匹配守卫if n == y
不是模式,因此不会引入新变量。这个y
是外部y
而不是新的阴影y
,我们可以通过比较n
和y
来查找与外部y
具有相同值的值。
You can also use the or operator |
in a match guard to specify multiple
patterns; the match guard condition will apply to all the patterns. Listing
18-28 shows the precedence when combining a pattern that uses |
with a match
guard. The important part of this example is that the if y
match guard
applies to 4
, 5
, and 6
, even though it might look like if y
only
applies to 6
.
您还可以使用或运算符|
在比赛守卫中指定多种模式;比赛守卫条件将应用于所有模式。清单 18-28 显示了组合使用|
的模式时的优先级。与一名比赛后卫。这个例子的重要部分是if y
匹配守卫适用于4
、 5
和6
,尽管它可能看起来像if y
仅适用于6
。
The match condition states that the arm only matches if the value of x
is
equal to 4
, 5
, or 6
and if y
is true
. When this code runs, the
pattern of the first arm matches because x
is 4
, but the match guard if y
is false, so the first arm is not chosen. The code moves on to the second arm,
which does match, and this program prints no
. The reason is that the if
condition applies to the whole pattern 4 | 5 | 6
, not only to the last value
6
. In other words, the precedence of a match guard in relation to a pattern
behaves like this:
匹配条件规定,仅当x
的值等于4
、 5
或6
且y
为true
时,该臂才匹配。当此代码运行时,第一个臂的模式匹配,因为x
是4
,但if y
为 false,则匹配守卫,因此不会选择第一个臂。代码移至第二个臂,它确实匹配,并且该程序打印no
。原因是if
条件适用于整个模式4 | 5 | 6
、不只到最后一个值6
。换句话说,匹配守卫相对于模式的优先级的行为如下:
(4 | 5 | 6) if y => ...
rather than this: 而不是这个:
4 | 5 | (6 if y) => ...
After running the code, the precedence behavior is evident: if the match guard
were applied only to the final value in the list of values specified using the
|
operator, the arm would have matched and the program would have printed
yes
.
运行代码后,优先行为很明显:如果匹配守卫仅应用于使用|
指定的值列表中的最终值。操作员,手臂会匹配,程序会打印yes
。
@
Bindings
@
绑定
The at operator @
lets us create a variable that holds a value at the same
time as we’re testing that value for a pattern match. In Listing 18-29, we want
to test that a Message::Hello
id
field is within the range 3..=7
. We also
want to bind the value to the variable id_variable
so we can use it in the
code associated with the arm. We could name this variable id
, the same as the
field, but for this example we’ll use a different name.
at运算符@
允许我们创建一个变量,该变量在测试模式匹配值的同时保存一个值。在清单 18-29 中,我们要测试Message::Hello
id
字段是否在3..=7
范围内。我们还希望将该值绑定到变量id_variable
,以便我们可以在与手臂相关的代码中使用它。我们可以将此变量命名为id
,与字段相同,但在本例中我们将使用不同的名称。
This example will print Found an id in range: 5
. By specifying id_variable @
before the range 3..=7
, we’re capturing whatever value matched the range
while also testing that the value matched the range pattern.
此示例将打印Found an id in range: 5
。通过在范围3..=7
之前指定id_variable @
,我们捕获与范围匹配的任何值,同时还测试该值是否与范围模式匹配。
In the second arm, where we only have a range specified in the pattern, the code
associated with the arm doesn’t have a variable that contains the actual value
of the id
field. The id
field’s value could have been 10, 11, or 12, but
the code that goes with that pattern doesn’t know which it is. The pattern code
isn’t able to use the value from the id
field, because we haven’t saved the
id
value in a variable.
在第二个臂中,我们仅在模式中指定了一个范围,与该臂关联的代码没有包含id
字段实际值的变量。 id
字段的值可能是 10、11 或 12,但使用该模式的代码不知道它是什么。模式代码无法使用id
字段中的值,因为我们尚未将id
值保存在变量中。
In the last arm, where we’ve specified a variable without a range, we do have
the value available to use in the arm’s code in a variable named id
. The
reason is that we’ve used the struct field shorthand syntax. But we haven’t
applied any test to the value in the id
field in this arm, as we did with the
first two arms: any value would match this pattern.
在最后一个手臂中,我们指定了一个没有范围的变量,我们确实有可在手臂代码中名为id
的变量中使用的值。原因是我们使用了 struct field 简写语法。但是我们没有像对前两个臂所做的那样对此臂中的id
字段中的值应用任何测试:任何值都将与此模式匹配。
Using @
lets us test a value and save it in a variable within one pattern.
使用@
可以让我们测试一个值并将其保存在一个模式内的变量中。
Summary 概括
Rust’s patterns are very useful in distinguishing between different kinds of
data. When used in match
expressions, Rust ensures your patterns cover every
possible value, or your program won’t compile. Patterns in let
statements and
function parameters make those constructs more useful, enabling the
destructuring of values into smaller parts at the same time as assigning to
variables. We can create simple or complex patterns to suit our needs.
Rust 的模式对于区分不同类型的数据非常有用。当在match
表达式中使用时,Rust 确保您的模式覆盖所有可能的值,否则您的程序将无法编译。 let
语句和函数参数中的模式使这些构造更加有用,可以在分配给变量的同时将值解构为更小的部分。我们可以创建简单或复杂的图案来满足我们的需求。
Next, for the penultimate chapter of the book, we’ll look at some advanced
aspects of a variety of Rust’s features.
接下来,在本书的倒数第二章中,我们将了解 Rust 各种功能的一些高级方面。
Advanced Features 高级功能
By now, you’ve learned the most commonly used parts of the Rust programming
language. Before we do one more project in Chapter 20, we’ll look at a few
aspects of the language you might run into every once in a while, but may not
use every day. You can use this chapter as a reference for when you encounter
any unknowns. The features covered here are useful in very specific situations.
Although you might not reach for them often, we want to make sure you have a
grasp of all the features Rust has to offer.
到目前为止,您已经学习了 Rust 编程语言最常用的部分。在我们在第 20 章中进行另一个项目之前,我们将了解一下您可能偶尔会遇到但可能不会每天使用的语言的几个方面。当您遇到任何未知的情况时,可以将本章作为参考。这里介绍的功能在非常特定的情况下非常有用。尽管您可能不会经常接触它们,但我们希望确保您掌握 Rust 提供的所有功能。
In this chapter, we’ll cover:
在本章中,我们将介绍:
- Unsafe Rust: how to opt out of some of Rust’s guarantees and take
responsibility for manually upholding those guarantees
不安全的 Rust:如何选择退出 Rust 的一些保证并负责手动维护这些保证 - Advanced traits: associated types, default type parameters, fully qualified
syntax, supertraits, and the newtype pattern in relation to traits
高级特征:关联类型、默认类型参数、完全限定语法、超级特征以及与特征相关的新类型模式 - Advanced types: more about the newtype pattern, type aliases, the never type,
and dynamically sized types
高级类型:有关 newtype 模式、类型别名、never 类型和动态大小类型的更多信息 - Advanced functions and closures: function pointers and returning closures
高级函数和闭包:函数指针和返回闭包 - Macros: ways to define code that defines more code at compile time
宏:定义代码的方法,在编译时定义更多代码
It’s a panoply of Rust features with something for everyone! Let’s dive in!
这是一整套 Rust 功能,适合每个人!让我们深入了解吧!
Unsafe Rust 不安全的生锈
All the code we’ve discussed so far has had Rust’s memory safety guarantees
enforced at compile time. However, Rust has a second language hidden inside it
that doesn’t enforce these memory safety guarantees: it’s called unsafe Rust
and works just like regular Rust, but gives us extra superpowers.
到目前为止我们讨论的所有代码都在编译时强制执行 Rust 的内存安全保证。然而,Rust 内部隐藏着第二种语言,它不会强制执行这些内存安全保证:它被称为不安全 Rust ,其工作方式与常规 Rust 一样,但为我们提供了额外的超能力。
Unsafe Rust exists because, by nature, static analysis is conservative. When
the compiler tries to determine whether or not code upholds the guarantees,
it’s better for it to reject some valid programs than to accept some invalid
programs. Although the code might be okay, if the Rust compiler doesn’t have
enough information to be confident, it will reject the code. In these cases,
you can use unsafe code to tell the compiler, “Trust me, I know what I’m
doing.” Be warned, however, that you use unsafe Rust at your own risk: if you
use unsafe code incorrectly, problems can occur due to memory unsafety, such as
null pointer dereferencing.
不安全 Rust 的存在是因为静态分析本质上是保守的。当编译器尝试确定代码是否支持保证时,拒绝一些有效程序比接受一些无效程序更好。尽管代码可能没问题,但如果 Rust 编译器没有足够的信息来确定,它会拒绝该代码。在这些情况下,您可以使用不安全代码告诉编译器,“相信我,我知道我在做什么。”但请注意,使用不安全的 Rust 需要您自担风险:如果不正确地使用不安全的代码,可能会因内存不安全而出现问题,例如空指针取消引用。
Another reason Rust has an unsafe alter ego is that the underlying computer
hardware is inherently unsafe. If Rust didn’t let you do unsafe operations, you
couldn’t do certain tasks. Rust needs to allow you to do low-level systems
programming, such as directly interacting with the operating system or even
writing your own operating system. Working with low-level systems programming
is one of the goals of the language. Let’s explore what we can do with unsafe
Rust and how to do it.
Rust 具有不安全的另一个自我的另一个原因是底层计算机硬件本质上是不安全的。如果 Rust 不允许您执行不安全的操作,您就无法执行某些任务。 Rust 需要允许您进行低级系统编程,例如直接与操作系统交互,甚至编写自己的操作系统。使用低级系统编程是该语言的目标之一。让我们探讨一下我们可以用不安全的 Rust 做什么以及如何做。
Unsafe Superpowers 不安全的超能力
To switch to unsafe Rust, use the unsafe
keyword and then start a new block
that holds the unsafe code. You can take five actions in unsafe Rust that you
can’t in safe Rust, which we call unsafe superpowers. Those superpowers
include the ability to:
要切换到不安全的 Rust,请使用unsafe
关键字,然后启动一个包含不安全代码的新块。您可以在不安全的 Rust 中执行五种在安全 Rust 中无法执行的操作,我们称之为不安全的超级大国。这些超能力包括以下能力:
- Dereference a raw pointer
取消引用原始指针 - Call an unsafe function or method
调用不安全的函数或方法 - Access or modify a mutable static variable
访问或修改可变静态变量 - Implement an unsafe trait
实施不安全特征 - Access fields of a
union
访问union
的字段
It’s important to understand that unsafe
doesn’t turn off the borrow checker
or disable any other of Rust’s safety checks: if you use a reference in unsafe
code, it will still be checked. The unsafe
keyword only gives you access to
these five features that are then not checked by the compiler for memory
safety. You’ll still get some degree of safety inside of an unsafe block.
重要的是要了解unsafe
不会关闭借用检查器或禁用 Rust 的任何其他安全检查:如果您在不安全代码中使用引用,它仍然会被检查。 unsafe
关键字仅允许您访问这五个功能,编译器不会检查这些功能的内存安全性。在不安全的区块内,你仍然可以获得一定程度的安全。
In addition, unsafe
does not mean the code inside the block is necessarily
dangerous or that it will definitely have memory safety problems: the intent is
that as the programmer, you’ll ensure the code inside an unsafe
block will
access memory in a valid way.
此外, unsafe
并不意味着块内的代码一定是危险的或者肯定会存在内存安全问题:其目的是作为程序员,您将确保unsafe
块内的代码将以有效的方式访问内存。
People are fallible, and mistakes will happen, but by requiring these five
unsafe operations to be inside blocks annotated with unsafe
you’ll know that
any errors related to memory safety must be within an unsafe
block. Keep
unsafe
blocks small; you’ll be thankful later when you investigate memory
bugs.
人们容易犯错,并且会发生错误,但是通过要求这五个不安全操作位于带有unsafe
注释的块内,您将知道与内存安全相关的任何错误都必须位于unsafe
块内。保持unsafe
块较小;当您稍后调查内存错误时,您会心存感激。
To isolate unsafe code as much as possible, it’s best to enclose unsafe code
within a safe abstraction and provide a safe API, which we’ll discuss later in
the chapter when we examine unsafe functions and methods. Parts of the standard
library are implemented as safe abstractions over unsafe code that has been
audited. Wrapping unsafe code in a safe abstraction prevents uses of unsafe
from leaking out into all the places that you or your users might want to use
the functionality implemented with unsafe
code, because using a safe
abstraction is safe.
为了尽可能隔离不安全代码,最好将不安全代码包含在安全抽象中,并提供安全 API,我们将在本章稍后检查不安全函数和方法时对此进行讨论。标准库的部分内容是作为经过审计的不安全代码的安全抽象来实现的。将不安全代码包装在安全抽象中可以防止unsafe
使用泄漏到您或您的用户可能想要使用通过unsafe
代码实现的功能的所有位置,因为使用安全抽象是安全的。
Let’s look at each of the five unsafe superpowers in turn. We’ll also look at
some abstractions that provide a safe interface to unsafe code.
让我们依次看看五种不安全的超能力。我们还将研究一些为不安全代码提供安全接口的抽象。
Dereferencing a Raw Pointer
取消引用原始指针
In Chapter 4, in the “Dangling References” section, we mentioned that the compiler ensures references are always
valid. Unsafe Rust has two new types called raw pointers that are similar to
references. As with references, raw pointers can be immutable or mutable and
are written as *const T
and *mut T
, respectively. The asterisk isn’t the
dereference operator; it’s part of the type name. In the context of raw
pointers, immutable means that the pointer can’t be directly assigned to
after being dereferenced.
在第 4 章的“悬空引用”忽略部分中,我们提到编译器确保引用始终有效。不安全 Rust 有两种称为原始指针的新类型,它们与引用类似。与引用一样,原始指针可以是不可变的或可变的,并分别写为*const T
和*mut T
。星号不是取消引用运算符;而是它是类型名称的一部分。在原始指针的上下文中,不可变意味着指针在取消引用后不能直接分配。
Different from references and smart pointers, raw pointers:
与引用和智能指针不同,原始指针:
- Are allowed to ignore the borrowing rules by having both immutable and
mutable pointers or multiple mutable pointers to the same location
允许通过同时拥有不可变和可变指针或指向同一位置的多个可变指针来忽略借用规则 - Aren’t guaranteed to point to valid memory
不保证指向有效的内存 - Are allowed to be null
允许为空 - Don’t implement any automatic cleanup
不实施任何自动清理
By opting out of having Rust enforce these guarantees, you can give up
guaranteed safety in exchange for greater performance or the ability to
interface with another language or hardware where Rust’s guarantees don’t apply.
通过选择不让 Rust 强制执行这些保证,您可以放弃有保证的安全性,以换取更高的性能或与 Rust 保证不适用的其他语言或硬件进行交互的能力。
Listing 19-1 shows how to create an immutable and a mutable raw pointer from
references.
清单 19-1 展示了如何从引用创建不可变和可变的原始指针。
Notice that we don’t include the unsafe
keyword in this code. We can create
raw pointers in safe code; we just can’t dereference raw pointers outside an
unsafe block, as you’ll see in a bit.
请注意,我们在此代码中不包含unsafe
关键字。我们可以在安全代码中创建原始指针;我们只是不能在不安全块之外取消引用原始指针,稍后您就会看到。
We’ve created raw pointers by using as
to cast an immutable and a mutable
reference into their corresponding raw pointer types. Because we created them
directly from references guaranteed to be valid, we know these particular raw
pointers are valid, but we can’t make that assumption about just any raw
pointer.
我们通过使用as
将不可变引用和可变引用转换为其相应的原始指针类型来创建原始指针。因为我们直接从保证有效的引用创建它们,所以我们知道这些特定的原始指针是有效的,但我们不能对任何原始指针做出这样的假设。
To demonstrate this, next we’ll create a raw pointer whose validity we can’t be
so certain of. Listing 19-2 shows how to create a raw pointer to an arbitrary
location in memory. Trying to use arbitrary memory is undefined: there might be
data at that address or there might not, the compiler might optimize the code
so there is no memory access, or the program might error with a segmentation
fault. Usually, there is no good reason to write code like this, but it is
possible.
为了演示这一点,接下来我们将创建一个原始指针,我们无法确定其有效性。清单 19-2 展示了如何创建指向内存中任意位置的原始指针。尝试使用任意内存是未定义的:该地址可能有数据,也可能没有,编译器可能会优化代码,因此不会进行内存访问,或者程序可能会出现分段错误。通常,没有充分的理由编写这样的代码,但这是可能的。
Recall that we can create raw pointers in safe code, but we can’t dereference
raw pointers and read the data being pointed to. In Listing 19-3, we use the
dereference operator *
on a raw pointer that requires an unsafe
block.
回想一下,我们可以在安全代码中创建原始指针,但我们不能取消引用原始指针并读取所指向的数据。在清单 19-3 中,我们对需要unsafe
块的原始指针使用取消引用运算符*
。
Creating a pointer does no harm; it’s only when we try to access the value that
it points at that we might end up dealing with an invalid value.
创建一个指针并没有什么坏处;只有当我们尝试访问它指向的值时,我们最终可能会处理一个无效值。
Note also that in Listing 19-1 and 19-3, we created *const i32
and *mut i32
raw pointers that both pointed to the same memory location, where num
is
stored. If we instead tried to create an immutable and a mutable reference to
num
, the code would not have compiled because Rust’s ownership rules don’t
allow a mutable reference at the same time as any immutable references. With
raw pointers, we can create a mutable pointer and an immutable pointer to the
same location and change data through the mutable pointer, potentially creating
a data race. Be careful!
另请注意,在清单 19-1 和 19-3 中,我们创建了*const i32
和*mut i32
原始指针,它们都指向存储num
同一内存位置。如果我们尝试创建对num
的不可变引用和可变引用,则代码将无法编译,因为 Rust 的所有权规则不允许与任何不可变引用同时存在可变引用。使用原始指针,我们可以创建指向同一位置的可变指针和不可变指针,并通过可变指针更改数据,这可能会造成数据争用。当心!
With all of these dangers, why would you ever use raw pointers? One major use
case is when interfacing with C code, as you’ll see in the next section,
“Calling an Unsafe Function or
Method.” Another case is
when building up safe abstractions that the borrow checker doesn’t understand.
We’ll introduce unsafe functions and then look at an example of a safe
abstraction that uses unsafe code.
面对所有这些危险,为什么还要使用原始指针呢?一个主要用例是与 C 代码交互,正如您将在下一节“调用不安全的函数或方法”中看到的那样。忽略 另一种情况是在构建借用检查器不理解的安全抽象时。我们将介绍不安全函数,然后查看使用不安全代码的安全抽象的示例。
Calling an Unsafe Function or Method
调用不安全的函数或方法
The second type of operation you can perform in an unsafe block is calling
unsafe functions. Unsafe functions and methods look exactly like regular
functions and methods, but they have an extra unsafe
before the rest of the
definition. The unsafe
keyword in this context indicates the function has
requirements we need to uphold when we call this function, because Rust can’t
guarantee we’ve met these requirements. By calling an unsafe function within an
unsafe
block, we’re saying that we’ve read this function’s documentation and
take responsibility for upholding the function’s contracts.
您可以在不安全块中执行的第二种操作是调用不安全函数。不安全的函数和方法看起来与常规函数和方法完全相同,但它们在定义的其余部分之前有一个额外的unsafe
。此上下文中的unsafe
关键字表示该函数具有我们在调用该函数时需要遵守的要求,因为 Rust 无法保证我们满足这些要求。通过在unsafe
块中调用不安全函数,我们表示我们已经阅读了该函数的文档并负责维护该函数的契约。
Here is an unsafe function named dangerous
that doesn’t do anything in its
body:
这是一个名为dangerous
不安全函数,它在函数体内不执行任何操作:
We must call the dangerous
function within a separate unsafe
block. If we
try to call dangerous
without the unsafe
block, we’ll get an error:
我们必须在单独的unsafe
块中调用dangerous
函数。如果我们尝试在没有unsafe
块的情况下调用dangerous
,我们会收到错误:
$ 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
--> 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
With the unsafe
block, we’re asserting to Rust that we’ve read the function’s
documentation, we understand how to use it properly, and we’ve verified that
we’re fulfilling the contract of the function.
通过unsafe
块,我们向 Rust 断言我们已经阅读了该函数的文档,我们了解如何正确使用它,并且我们已经验证了我们正在履行该函数的约定。
Bodies of unsafe functions are effectively unsafe
blocks, so to perform other
unsafe operations within an unsafe function, we don’t need to add another
unsafe
block.
不安全函数体实际上是unsafe
块,因此要在不安全函数内执行其他不安全操作,我们不需要添加另一个unsafe
块。
Creating a Safe Abstraction over Unsafe Code
创建针对不安全代码的安全抽象
Just because a function contains unsafe code doesn’t mean we need to mark the
entire function as unsafe. In fact, wrapping unsafe code in a safe function is
a common abstraction. As an example, let’s study the split_at_mut
function
from the standard library, which requires some unsafe code. We’ll explore how
we might implement it. This safe method is defined on mutable slices: it takes
one slice and makes it two by splitting the slice at the index given as an
argument. Listing 19-4 shows how to use split_at_mut
.
仅仅因为函数包含不安全代码并不意味着我们需要将整个函数标记为不安全。事实上,将不安全代码包装在安全函数中是一种常见的抽象。作为一个例子,让我们研究标准库中的split_at_mut
函数,它需要一些不安全的代码。我们将探讨如何实施它。这种安全方法是在可变切片上定义的:它采用一个切片,并通过在作为参数给出的索引处分割该切片将其变成两个切片。清单 19-4 显示了如何使用split_at_mut
。
We can’t implement this function using only safe Rust. An attempt might look
something like Listing 19-5, which won’t compile. For simplicity, we’ll
implement split_at_mut
as a function rather than a method and only for slices
of i32
values rather than for a generic type T
.
我们无法仅使用安全的 Rust 来实现此功能。尝试可能类似于清单 19-5,但无法编译。为简单起见,我们将split_at_mut
实现为函数而不是方法,并且仅针对i32
值的切片而不是泛型类型T
。
This function first gets the total length of the slice. Then it asserts that
the index given as a parameter is within the slice by checking whether it’s
less than or equal to the length. The assertion means that if we pass an index
that is greater than the length to split the slice at, the function will panic
before it attempts to use that index.
该函数首先获取切片的总长度。然后它通过检查它是否小于或等于长度来断言作为参数给出的索引位于切片内。该断言意味着,如果我们传递的索引大于分割切片的长度,则该函数在尝试使用该索引之前将发生恐慌。
Then we return two mutable slices in a tuple: one from the start of the
original slice to the mid
index and another from mid
to the end of the
slice.
然后,我们在元组中返回两个可变切片:一个从原始切片的开头到mid
索引,另一个从切片的mid
到末尾。
When we try to compile the code in Listing 19-5, we’ll get an error.
当我们尝试编译清单 19-5 中的代码时,我们会得到一个错误。
$ 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
--> src/main.rs:6:31
|
1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
| - let's call the lifetime of this reference `'1`
...
6 | (&mut values[..mid], &mut values[mid..])
| --------------------------^^^^^^--------
| | | |
| | | second mutable borrow occurs here
| | first mutable borrow occurs here
| returning this value requires that `*values` is borrowed for `'1`
For more information about this error, try `rustc --explain E0499`.
error: could not compile `unsafe-example` (bin "unsafe-example") due to 1 previous error
Rust’s borrow checker can’t understand that we’re borrowing different parts of
the slice; it only knows that we’re borrowing from the same slice twice.
Borrowing different parts of a slice is fundamentally okay because the two
slices aren’t overlapping, but Rust isn’t smart enough to know this. When we
know code is okay, but Rust doesn’t, it’s time to reach for unsafe code.
Rust 的借用检查器无法理解我们正在借用切片的不同部分;它只知道我们从同一个切片借用了两次。借用切片的不同部分基本上是可以的,因为两个切片不重叠,但 Rust 不够聪明,无法知道这一点。当我们知道代码没问题,但 Rust 不行时,就该寻找不安全的代码了。
Listing 19-6 shows how to use an unsafe
block, a raw pointer, and some calls
to unsafe functions to make the implementation of split_at_mut
work.
清单 19-6 显示了如何使用unsafe
块、原始指针以及对不安全函数的一些调用来使split_at_mut
的实现正常工作。
Recall from “The Slice Type” section in
Chapter 4 that slices are a pointer to some data and the length of the slice.
We use the len
method to get the length of a slice and the as_mut_ptr
method to access the raw pointer of a slice. In this case, because we have a
mutable slice to i32
values, as_mut_ptr
returns a raw pointer with the type
*mut i32
, which we’ve stored in the variable ptr
.
回想一下第 4 章中的“切片类型”忽略部分,切片是指向某些数据和切片长度的指针。我们使用len
方法来获取切片的长度,并使用as_mut_ptr
方法来访问切片的原始指针。在本例中,因为我们有一个i32
值的可变切片,所以as_mut_ptr
返回类型为*mut i32
原始指针,我们将其存储在变量ptr
中。
We keep the assertion that the mid
index is within the slice. Then we get to
the unsafe code: the slice::from_raw_parts_mut
function takes a raw pointer
and a length, and it creates a slice. We use this function to create a slice
that starts from ptr
and is mid
items long. Then we call the add
method on ptr
with mid
as an argument to get a raw pointer that starts at
mid
, and we create a slice using that pointer and the remaining number of
items after mid
as the length.
我们保留mid
索引位于切片内的断言。然后我们看到不安全的代码: slice::from_raw_parts_mut
函数接受一个原始指针和一个长度,并创建一个切片。我们使用此函数创建一个从ptr
开始、长度为mid
items 的切片。然后我们以mid
作为参数调用ptr
上的add
方法来获取从mid
开始的原始指针,并使用该指针和mid
之后的剩余项目数作为长度创建一个切片。
The function slice::from_raw_parts_mut
is unsafe because it takes a raw
pointer and must trust that this pointer is valid. The add
method on raw
pointers is also unsafe, because it must trust that the offset location is also
a valid pointer. Therefore, we had to put an unsafe
block around our calls to
slice::from_raw_parts_mut
and add
so we could call them. By looking at
the code and by adding the assertion that mid
must be less than or equal to
len
, we can tell that all the raw pointers used within the unsafe
block
will be valid pointers to data within the slice. This is an acceptable and
appropriate use of unsafe
.
函数slice::from_raw_parts_mut
是不安全的,因为它采用原始指针并且必须相信该指针是有效的。原始指针上的add
方法也是不安全的,因为它必须相信偏移位置也是一个有效的指针。因此,我们必须在对slice::from_raw_parts_mut
和add
调用周围放置一个unsafe
块,以便我们可以调用它们。通过查看代码并添加mid
必须小于或等于len
断言,我们可以知道unsafe
块中使用的所有原始指针都将是指向切片内数据的有效指针。这是unsafe
的可接受且适当的使用。
Note that we don’t need to mark the resulting split_at_mut
function as
unsafe
, and we can call this function from safe Rust. We’ve created a safe
abstraction to the unsafe code with an implementation of the function that uses
unsafe
code in a safe way, because it creates only valid pointers from the
data this function has access to.
请注意,我们不需要将生成的split_at_mut
函数标记为unsafe
,并且我们可以从安全的 Rust 中调用该函数。我们通过以安全方式使用不安全代码的函数实现创建了对unsafe
代码的安全抽象,因为它仅根据该函数有权访问的数据创建有效指针。
In contrast, the use of slice::from_raw_parts_mut
in Listing 19-7 would
likely crash when the slice is used. This code takes an arbitrary memory
location and creates a slice 10,000 items long.
相反,清单 19-7 中使用slice::from_raw_parts_mut
可能会在使用切片时崩溃。此代码采用任意内存位置并创建一个长度为 10,000 个项目的切片。
We don’t own the memory at this arbitrary location, and there is no guarantee
that the slice this code creates contains valid i32
values. Attempting to use
values
as though it’s a valid slice results in undefined behavior.
我们不拥有这个任意位置的内存,并且不能保证此代码创建的切片包含有效的i32
值。尝试将values
视为有效切片会导致未定义的行为。
Using extern
Functions to Call External Code
使用extern
函数调用外部代码
Sometimes, your Rust code might need to interact with code written in another
language. For this, Rust has the keyword extern
that facilitates the creation
and use of a Foreign Function Interface (FFI). An FFI is a way for a
programming language to define functions and enable a different (foreign)
programming language to call those functions.
有时,您的 Rust 代码可能需要与用另一种语言编写的代码进行交互。为此,Rust 有关键字extern
,它有助于外部函数接口 (FFI)的创建和使用。 FFI 是编程语言定义函数并使不同(外国)编程语言能够调用这些函数的一种方式。
Listing 19-8 demonstrates how to set up an integration with the abs
function
from the C standard library. Functions declared within extern
blocks are
always unsafe to call from Rust code. The reason is that other languages don’t
enforce Rust’s rules and guarantees, and Rust can’t check them, so
responsibility falls on the programmer to ensure safety.
清单19-8演示了如何设置与C标准库中的abs
函数的集成。从 Rust 代码调用extern
块中声明的函数始终是不安全的。原因是其他语言不执行 Rust 的规则和保证,并且 Rust 无法检查它们,因此确保安全的责任落在程序员身上。
Filename: src/main.rs 文件名:src/main.rs
extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
unsafe {
println!("Absolute value of -3 according to C: {}", abs(-3));
}
}
Within the extern "C"
block, we list the names and signatures of external
functions from another language we want to call. The "C"
part defines which
application binary interface (ABI) the external function uses: the ABI
defines how to call the function at the assembly level. The "C"
ABI is the
most common and follows the C programming language’s ABI.
在extern "C"
块中,我们列出了我们想要调用的另一种语言的外部函数的名称和签名。 "C"
部分定义外部函数使用哪个应用程序二进制接口(ABI) :ABI 定义如何在汇编级别调用该函数。 "C"
ABI 是最常见的,并且遵循 C 编程语言的 ABI。
Calling Rust Functions from Other Languages
从其他语言调用 Rust 函数
We can also use extern
to create an interface that allows other languages
to call Rust functions. Instead of creating a whole extern
block, we add
the extern
keyword and specify the ABI to use just before the fn
keyword
for the relevant function. We also need to add a #[no_mangle]
annotation to
tell the Rust compiler not to mangle the name of this function. Mangling is
when a compiler changes the name we’ve given a function to a different name
that contains more information for other parts of the compilation process to
consume but is less human readable. Every programming language compiler
mangles names slightly differently, so for a Rust function to be nameable by
other languages, we must disable the Rust compiler’s name mangling.
我们还可以使用extern
创建一个接口,允许其他语言调用 Rust 函数。我们没有创建整个extern
块,而是添加extern
关键字并指定要在相关函数的fn
关键字之前使用的 ABI。我们还需要添加#[no_mangle]
注释来告诉Rust编译器不要破坏这个函数的名称。重整是指编译器将我们赋予函数的名称更改为不同的名称,该名称包含更多信息供编译过程的其他部分使用,但人类可读性较差。每种编程语言编译器对名称的修改都略有不同,因此要使 Rust 函数可以由其他语言命名,我们必须禁用 Rust 编译器的名称修改。
In the following example, we make the call_from_c
function accessible from
C code, after it’s compiled to a shared library and linked from C:
在下面的示例中,我们将call_from_c
函数编译为共享库并从 C 链接后,可以从 C 代码访问该函数:
This usage of extern
does not require unsafe
.extern
的这种用法不需要unsafe
。
Accessing or Modifying a Mutable Static Variable
访问或修改可变静态变量
In this book, we’ve not yet talked about global variables, which Rust does
support but can be problematic with Rust’s ownership rules. If two threads are
accessing the same mutable global variable, it can cause a data race.
在本书中,我们还没有讨论全局变量,Rust 确实支持全局变量,但可能会对 Rust 的所有权规则产生问题。如果两个线程访问同一个可变全局变量,则可能会导致数据争用。
In Rust, global variables are called static variables. Listing 19-9 shows an
example declaration and use of a static variable with a string slice as a
value.
在 Rust 中,全局变量称为静态变量。清单 19-9 显示了以字符串切片作为值的静态变量的声明和使用示例。
Filename: src/main.rs 文件名:src/main.rs
static HELLO_WORLD: &str = "Hello, world!";
fn main() {
println!("name is: {HELLO_WORLD}");
}
Static variables are similar to constants, which we discussed in the
“Differences Between Variables and
Constants” section
in Chapter 3. The names of static variables are in SCREAMING_SNAKE_CASE
by
convention. Static variables can only store references with the 'static
lifetime, which means the Rust compiler can figure out the lifetime and we
aren’t required to annotate it explicitly. Accessing an immutable static
variable is safe.
静态变量与常量类似,我们在第 3 章“变量与常量之间的差异”忽略部分中讨论过。按照惯例,静态变量的名称采用SCREAMING_SNAKE_CASE
格式。静态变量只能存储具有'static
生命周期的引用,这意味着 Rust 编译器可以计算出生命周期,我们不需要显式注释它。访问不可变的静态变量是安全的。
A subtle difference between constants and immutable static variables is that
values in a static variable have a fixed address in memory. Using the value
will always access the same data. Constants, on the other hand, are allowed to
duplicate their data whenever they’re used. Another difference is that static
variables can be mutable. Accessing and modifying mutable static variables is
unsafe. Listing 19-10 shows how to declare, access, and modify a mutable
static variable named COUNTER
.
常量和不可变静态变量之间的一个细微区别是静态变量中的值在内存中具有固定地址。使用该值将始终访问相同的数据。另一方面,常量在使用时可以复制其数据。另一个区别是静态变量可以是可变的。访问和修改可变静态变量是不安全的。清单 19-10 显示了如何声明、访问和修改名为COUNTER
的可变静态变量。
Filename: src/main.rs 文件名:src/main.rs
static mut COUNTER: u32 = 0;
fn add_to_count(inc: u32) {
unsafe {
COUNTER += inc;
}
}
fn main() {
add_to_count(3);
unsafe {
println!("COUNTER: {COUNTER}");
}
}
As with regular variables, we specify mutability using the mut
keyword. Any
code that reads or writes from COUNTER
must be within an unsafe
block. This
code compiles and prints COUNTER: 3
as we would expect because it’s single
threaded. Having multiple threads access COUNTER
would likely result in data
races.
与常规变量一样,我们使用mut
关键字指定可变性。从COUNTER
读取或写入的任何代码都必须位于unsafe
块内。此代码按照我们的预期编译并打印COUNTER: 3
因为它是单线程的。让多个线程访问COUNTER
可能会导致数据竞争。
With mutable data that is globally accessible, it’s difficult to ensure there
are no data races, which is why Rust considers mutable static variables to be
unsafe. Where possible, it’s preferable to use the concurrency techniques and
thread-safe smart pointers we discussed in Chapter 16 so the compiler checks
that data accessed from different threads is done safely.
对于全局可访问的可变数据,很难确保不存在数据争用,这就是 Rust 认为可变静态变量不安全的原因。在可能的情况下,最好使用我们在第 16 章中讨论的并发技术和线程安全智能指针,以便编译器检查从不同线程访问的数据是否安全。
Implementing an Unsafe Trait
实施不安全特征
We can use unsafe
to implement an unsafe trait. A trait is unsafe when at
least one of its methods has some invariant that the compiler can’t verify. We
declare that a trait is unsafe
by adding the unsafe
keyword before trait
and marking the implementation of the trait as unsafe
too, as shown in
Listing 19-11.
我们可以使用unsafe
来实现不安全的特征。当特征的至少一个方法具有编译器无法验证的某些不变量时,该特征是不安全的。我们通过在trait
之前添加unsafe
关键字并将该 Trait 的实现也标记为unsafe
来声明 Trait unsafe
,如清单 19-11 所示。
unsafe trait Foo {
// methods go here
}
unsafe impl Foo for i32 {
// method implementations go here
}
fn main() {}
By using unsafe impl
, we’re promising that we’ll uphold the invariants that
the compiler can’t verify.
通过使用unsafe impl
,我们承诺将维护编译器无法验证的不变量。
As an example, recall the Sync
and Send
marker traits we discussed in the
“Extensible Concurrency with the Sync
and Send
Traits”
section in Chapter 16: the compiler implements these traits automatically if
our types are composed entirely of Send
and Sync
types. If we implement a
type that contains a type that is not Send
or Sync
, such as raw pointers,
and we want to mark that type as Send
or Sync
, we must use unsafe
. Rust
can’t verify that our type upholds the guarantees that it can be safely sent
across threads or accessed from multiple threads; therefore, we need to do
those checks manually and indicate as such with unsafe
.
作为一个例子,回想一下我们在第 16 章的“具有Sync
和Send
特征的可扩展并发”忽略部分中讨论的Sync
和Send
标记特征:如果我们的类型完全由Send
和Sync
类型组成,编译器会自动实现这些特征。如果我们实现的类型包含非Send
或Sync
的类型(例如原始指针),并且我们希望将该类型标记为Send
或Sync
,则必须使用unsafe
。 Rust 无法验证我们的类型是否能够保证它可以安全地跨线程发送或从多个线程访问;因此,我们需要手动进行这些检查并用unsafe
进行指示。
Accessing Fields of a Union
访问联合的字段
The final action that works only with unsafe
is accessing fields of a
union. A union
is similar to a struct
, but only one declared field is
used in a particular instance at one time. Unions are primarily used to
interface with unions in C code. Accessing union fields is unsafe because Rust
can’t guarantee the type of the data currently being stored in the union
instance. You can learn more about unions in the Rust Reference.
仅适用于unsafe
的最后一个操作是访问union的字段。 union
类似于struct
,但在特定实例中一次仅使用一个声明的字段。联合主要用于与 C 代码中的联合进行交互。访问联合字段是不安全的,因为 Rust 无法保证当前存储在联合实例中的数据的类型。您可以在Rust 参考中了解有关联合的更多信息。
When to Use Unsafe Code
何时使用不安全代码
Using unsafe
to take one of the five actions (superpowers) just discussed
isn’t wrong or even frowned upon. But it is trickier to get unsafe
code
correct because the compiler can’t help uphold memory safety. When you have a
reason to use unsafe
code, you can do so, and having the explicit unsafe
annotation makes it easier to track down the source of problems when they occur.
使用unsafe
来采取刚才讨论的五种行动(超能力)之一并没有错,甚至不会令人皱眉。但要使unsafe
代码正确是比较棘手的,因为编译器无法帮助维护内存安全。当您有理由使用unsafe
代码时,您可以这样做,并且使用显式unsafe
注释可以更轻松地在问题发生时追踪问题的根源。
Advanced Traits 高级特质
We first covered traits in the “Traits: Defining Shared
Behavior” section of Chapter
10, but we didn’t discuss the more advanced details. Now that you know more
about Rust, we can get into the nitty-gritty.
我们首先在第 10 章的“特征:定义共享行为”忽略部分中介绍了特征,但我们没有讨论更高级的细节。现在您对 Rust 了解更多了,我们可以深入了解细节了。
Specifying Placeholder Types in Trait Definitions with Associated Types
在具有关联类型的特征定义中指定占位符类型
Associated types connect a type placeholder with a trait such that the trait
method definitions can use these placeholder types in their signatures. The
implementor of a trait will specify the concrete type to be used instead of the
placeholder type for the particular implementation. That way, we can define a
trait that uses some types without needing to know exactly what those types are
until the trait is implemented.
关联类型将类型占位符与特征连接起来,以便特征方法定义可以在其签名中使用这些占位符类型。特征的实现者将指定要使用的具体类型,而不是特定实现的占位符类型。这样,我们就可以定义一个使用某些类型的特征,而无需在该特征实现之前确切地知道这些类型是什么。
We’ve described most of the advanced features in this chapter as being rarely
needed. Associated types are somewhere in the middle: they’re used more rarely
than features explained in the rest of the book but more commonly than many of
the other features discussed in this chapter.
我们在本章中描述了大多数很少需要的高级功能。关联类型处于中间位置:它们比本书其余部分中解释的功能更少使用,但比本章讨论的许多其他功能更常见。
One example of a trait with an associated type is the Iterator
trait that the
standard library provides. The associated type is named Item
and stands in
for the type of the values the type implementing the Iterator
trait is
iterating over. The definition of the Iterator
trait is as shown in Listing
19-12.
具有关联类型的特征的一个示例是标准库提供的Iterator
特征。关联的类型名为Item
,代表实现Iterator
特征的类型正在迭代的值的类型。 Iterator
特征的定义如清单 19-12 所示。
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
The type Item
is a placeholder, and the next
method’s definition shows that
it will return values of type Option<Self::Item>
. Implementors of the
Iterator
trait will specify the concrete type for Item
, and the next
method will return an Option
containing a value of that concrete type.Item
类型是占位符, next
方法的定义显示它将返回Option<Self::Item>
类型的值。 Iterator
特征的实现者将指定Item
的具体类型,并且next
方法将返回包含该具体类型的值的Option
。
Associated types might seem like a similar concept to generics, in that the
latter allow us to define a function without specifying what types it can
handle. To examine the difference between the two concepts, we’ll look at an
implementation of the Iterator
trait on a type named Counter
that specifies
the Item
type is u32
:
关联类型可能看起来与泛型类似,因为后者允许我们定义一个函数而不指定它可以处理什么类型。为了检查这两个概念之间的差异,我们将查看Iterator
特征在名为Counter
类型上的实现,该类型指定Item
类型为u32
:
Filename: src/lib.rs 文件名:src/lib.rs
This syntax seems comparable to that of generics. So why not just define the
Iterator
trait with generics, as shown in Listing 19-13?
这种语法看起来与泛型相当。那么为什么不直接使用泛型定义Iterator
特征,如清单 19-13 所示?
pub trait Iterator<T> {
fn next(&mut self) -> Option<T>;
}
The difference is that when using generics, as in Listing 19-13, we must
annotate the types in each implementation; because we can also implement
Iterator<String> for Counter
or any other type, we could have multiple
implementations of Iterator
for Counter
. In other words, when a trait has a
generic parameter, it can be implemented for a type multiple times, changing
the concrete types of the generic type parameters each time. When we use the
next
method on Counter
, we would have to provide type annotations to
indicate which implementation of Iterator
we want to use.
不同之处在于,当使用泛型时,如清单 19-13 所示,我们必须在每个实现中注释类型;因为我们还可Iterator<String> for Counter
,所以我们可以为Counter
实现Iterator
的多个实现。换句话说,当一个特征具有泛型参数时,它可以针对一个类型多次实现,每次都更改泛型类型参数的具体类型。当我们在Counter
上使用next
方法时,我们必须提供类型注释来指示我们要使用的Iterator
的实现。
With associated types, we don’t need to annotate types because we can’t
implement a trait on a type multiple times. In Listing 19-12 with the
definition that uses associated types, we can only choose what the type of
Item
will be once, because there can only be one impl Iterator for Counter
.
We don’t have to specify that we want an iterator of u32
values everywhere
that we call next
on Counter
.
对于关联类型,我们不需要注释类型,因为我们不能多次在类型上实现特征。在清单 19-12 中,使用关联类型的定义,我们只能选择一次Item
的类型,因为impl Iterator for Counter
。我们不必指定我们想要一个u32
值的迭代器,我们在Counter
上调用next
。
Associated types also become part of the trait’s contract: implementors of the
trait must provide a type to stand in for the associated type placeholder.
Associated types often have a name that describes how the type will be used,
and documenting the associated type in the API documentation is good practice.
关联类型也成为特征契约的一部分:特征的实现者必须提供一个类型来代表关联类型占位符。关联类型通常有一个名称来描述如何使用该类型,并且在 API 文档中记录关联类型是一种很好的做法。
Default Generic Type Parameters and Operator Overloading
默认泛型类型参数和运算符重载
When we use generic type parameters, we can specify a default concrete type for
the generic type. This eliminates the need for implementors of the trait to
specify a concrete type if the default type works. You specify a default type
when declaring a generic type with the <PlaceholderType=ConcreteType>
syntax.
当我们使用泛型类型参数时,我们可以为泛型类型指定一个默认的具体类型。如果默认类型有效,则特征的实现者无需指定具体类型。使用<PlaceholderType=ConcreteType>
语法声明泛型类型时指定默认类型。
A great example of a situation where this technique is useful is with operator
overloading, in which you customize the behavior of an operator (such as +
)
in particular situations.
此技术有用的情况的一个很好的例子是运算符重载,其中您可以在特定情况下自定义运算符(例如+
)的行为。
Rust doesn’t allow you to create your own operators or overload arbitrary
operators. But you can overload the operations and corresponding traits listed
in std::ops
by implementing the traits associated with the operator. For
example, in Listing 19-14 we overload the +
operator to add two Point
instances together. We do this by implementing the Add
trait on a Point
struct:
Rust 不允许您创建自己的运算符或重载任意运算符。但是您可以通过实现与运算符关联的特征来重载std::ops
中列出的操作和相应特征。例如,在清单 19-14 中,我们重载了+
运算符以将两个Point
实例添加在一起。我们通过在Point
结构上实现Add
特征来做到这一点:
Filename: src/main.rs 文件名:src/main.rs
use std::ops::Add;
#[derive(Debug, Copy, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
assert_eq!(
Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
Point { x: 3, y: 3 }
);
}
The add
method adds the x
values of two Point
instances and the y
values of two Point
instances to create a new Point
. The Add
trait has an
associated type named Output
that determines the type returned from the add
method.add
方法将两个Point
实例的x
值和两个Point
实例的y
值相加以创建一个新Point
。 Add
特征有一个名为Output
关联类型,它确定从add
方法返回的类型。
The default generic type in this code is within the Add
trait. Here is its
definition:
此代码中的默认泛型类型位于Add
特征内。这是它的定义:
This code should look generally familiar: a trait with one method and an
associated type. The new part is Rhs=Self
: this syntax is called default
type parameters. The Rhs
generic type parameter (short for “right hand
side”) defines the type of the rhs
parameter in the add
method. If we don’t
specify a concrete type for Rhs
when we implement the Add
trait, the type
of Rhs
will default to Self
, which will be the type we’re implementing
Add
on.
这段代码看起来应该很熟悉:具有一个方法和关联类型的特征。新部分是Rhs=Self
:此语法称为默认类型参数。 Rhs
泛型类型参数(“右手边”的缩写)定义了add
方法中rhs
参数的类型。如果我们在实现Add
特征时没有为Rhs
指定具体类型,则Rhs
的类型将默认为Self
,这将是我们正在实现Add
的类型。
When we implemented Add
for Point
, we used the default for Rhs
because we
wanted to add two Point
instances. Let’s look at an example of implementing
the Add
trait where we want to customize the Rhs
type rather than using the
default.
当我们为Point
实现Add
时,我们使用了Rhs
的默认值,因为我们想要添加两个Point
实例。让我们看一个实现Add
特征的示例,其中我们想要自定义Rhs
类型而不是使用默认值。
We have two structs, Millimeters
and Meters
, holding values in different
units. This thin wrapping of an existing type in another struct is known as the
newtype pattern, which we describe in more detail in the “Using the Newtype
Pattern to Implement External Traits on External Types” section. We want to add values in millimeters to values in meters and have
the implementation of Add
do the conversion correctly. We can implement Add
for Millimeters
with Meters
as the Rhs
, as shown in Listing 19-15.
我们有两个结构体, Millimeters
和Meters
,保存不同单位的值。这种对现有类型在另一个结构中的薄包装称为newtype 模式,我们在“使用 Newtype 模式在外部类型上实现外部特征”忽略部分中更详细地描述了它。我们希望将以毫米为单位的值与以米为单位的值相加,并让Add
的实现正确执行转换。我们可以使用Millimeters
作为Rhs
来实现Meters
的Add
,如清单 19-15 所示。
Filename: src/lib.rs 文件名:src/lib.rs
use std::ops::Add;
struct Millimeters(u32);
struct Meters(u32);
impl Add<Meters> for Millimeters {
type Output = Millimeters;
fn add(self, other: Meters) -> Millimeters {
Millimeters(self.0 + (other.0 * 1000))
}
}
To add Millimeters
and Meters
, we specify impl Add<Meters>
to set the
value of the Rhs
type parameter instead of using the default of Self
.
要添加Millimeters
和Meters
,我们指定impl Add<Meters>
来设置Rhs
类型参数的值,而不是使用默认的Self
。
You’ll use default type parameters in two main ways:
您将通过两种主要方式使用默认类型参数:
- To extend a type without breaking existing code
在不破坏现有代码的情况下扩展类型 - To allow customization in specific cases most users won’t need
允许在大多数用户不需要的特定情况下进行自定义
The standard library’s Add
trait is an example of the second purpose:
usually, you’ll add two like types, but the Add
trait provides the ability to
customize beyond that. Using a default type parameter in the Add
trait
definition means you don’t have to specify the extra parameter most of the
time. In other words, a bit of implementation boilerplate isn’t needed, making
it easier to use the trait.
标准库的Add
特征是第二个目的的一个示例:通常,您将添加两个类似的类型,但Add
特征提供了除此之外的自定义功能。在Add
特征定义中使用默认类型参数意味着您大多数时候不必指定额外的参数。换句话说,不需要一些实现样板,从而更容易使用该特征。
The first purpose is similar to the second but in reverse: if you want to add a
type parameter to an existing trait, you can give it a default to allow
extension of the functionality of the trait without breaking the existing
implementation code.
第一个目的与第二个目的类似,但相反:如果您想向现有特征添加类型参数,您可以为其指定默认值,以允许扩展特征的功能而不破坏现有的实现代码。
Fully Qualified Syntax for Disambiguation: Calling Methods with the Same Name
用于消除歧义的完全限定语法:调用同名方法
Nothing in Rust prevents a trait from having a method with the same name as
another trait’s method, nor does Rust prevent you from implementing both traits
on one type. It’s also possible to implement a method directly on the type with
the same name as methods from traits.
Rust 中的任何内容都不会阻止一个特征具有与另一个特征的方法同名的方法,Rust 也不会阻止您在一种类型上实现这两个特征。还可以直接在类型上实现与特征中的方法同名的方法。
When calling methods with the same name, you’ll need to tell Rust which one you
want to use. Consider the code in Listing 19-16 where we’ve defined two traits,
Pilot
and Wizard
, that both have a method called fly
. We then implement
both traits on a type Human
that already has a method named fly
implemented
on it. Each fly
method does something different.
当调用同名方法时,你需要告诉 Rust 你想使用哪一个。考虑清单 19-16 中的代码,其中我们定义了两个特征Pilot
和Wizard
,它们都有一个名为fly
的方法。然后,我们在Human
类型上实现这两个特征,该类型已经实现了名为fly
方法。每种fly
方法都有不同的作用。
Filename: src/main.rs 文件名:src/main.rs
When we call fly
on an instance of Human
, the compiler defaults to calling
the method that is directly implemented on the type, as shown in Listing 19-17.
当我们在Human
的实例上调用fly
时,编译器默认调用直接在该类型上实现的方法,如清单 19-17 所示。
Filename: src/main.rs 文件名:src/main.rs
Running this code will print *waving arms furiously*
, showing that Rust
called the fly
method implemented on Human
directly.
运行这段代码会打印出*waving arms furiously*
,表明Rust直接调用了Human
上实现的fly
方法。
To call the fly
methods from either the Pilot
trait or the Wizard
trait,
we need to use more explicit syntax to specify which fly
method we mean.
Listing 19-18 demonstrates this syntax.
要从Pilot
特征或Wizard
特征调用fly
方法,我们需要使用更明确的语法来指定我们指的是哪个fly
方法。清单 19-18 演示了这种语法。
Filename: src/main.rs 文件名:src/main.rs
Specifying the trait name before the method name clarifies to Rust which
implementation of fly
we want to call. We could also write
Human::fly(&person)
, which is equivalent to the person.fly()
that we used
in Listing 19-18, but this is a bit longer to write if we don’t need to
disambiguate.
在方法名称之前指定特征名称可以向 Rust 阐明我们要调用哪个fly
实现。我们还可以编写Human::fly(&person)
,它相当于我们在清单 19-18 中使用的person.fly()
,但是如果我们不需要消除歧义,那么写起来会有点长。
Running this code prints the following:
运行此代码会打印以下内容:
$ 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*
Because the fly
method takes a self
parameter, if we had two types that
both implement one trait, Rust could figure out which implementation of a
trait to use based on the type of self
.
因为fly
方法采用self
参数,所以如果我们有两种类型都实现一个Trait ,Rust 可以根据self
的类型找出要使用的 Trait 的哪种实现。
However, associated functions that are not methods don’t have a self
parameter. When there are multiple types or traits that define non-method
functions with the same function name, Rust doesn’t always know which type you
mean unless you use fully qualified syntax. For example, in Listing 19-19 we
create a trait for an animal shelter that wants to name all baby dogs Spot.
We make an Animal
trait with an associated non-method function baby_name
.
The Animal
trait is implemented for the struct Dog
, on which we also
provide an associated non-method function baby_name
directly.
但是,不是方法的关联函数没有self
参数。当有多个类型或特征定义具有相同函数名的非方法函数时,Rust 并不总是知道您指的是哪种类型,除非您使用完全限定语法。例如,在清单 19-19 中,我们为动物收容所创建了一个特征,想要将所有小狗命名为 Spot 。我们使用关联的非方法函数baby_name
创建一个Animal
特征。 Animal
特征是为 struct Dog
实现的,我们还直接提供了一个关联的非方法函数baby_name
。
Filename: src/main.rs 文件名:src/main.rs
trait Animal {
fn baby_name() -> String;
}
struct Dog;
impl Dog {
fn baby_name() -> String {
String::from("Spot")
}
}
impl Animal for Dog {
fn baby_name() -> String {
String::from("puppy")
}
}
fn main() {
println!("A baby dog is called a {}", Dog::baby_name());
}
We implement the code for naming all puppies Spot in the baby_name
associated
function that is defined on Dog
. The Dog
type also implements the trait
Animal
, which describes characteristics that all animals have. Baby dogs are
called puppies, and that is expressed in the implementation of the Animal
trait on Dog
in the baby_name
function associated with the Animal
trait.
我们在Dog
上定义的baby_name
关联函数中实现了用于命名所有小狗 Spot 的代码。 Dog
类型还实现了Animal
特征,它描述了所有动物都具有的特征。小狗被称为小狗,这通过与Animal
特征关联的baby_name
函数中Dog
上的Animal
特征的实现来表达。
In main
, we call the Dog::baby_name
function, which calls the associated
function defined on Dog
directly. This code prints the following:
在main
中,我们调用Dog::baby_name
函数,该函数直接调用Dog
上定义的关联函数。此代码打印以下内容:
$ 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
This output isn’t what we wanted. We want to call the baby_name
function that
is part of the Animal
trait that we implemented on Dog
so the code prints
A baby dog is called a puppy
. The technique of specifying the trait name that
we used in Listing 19-18 doesn’t help here; if we change main
to the code in
Listing 19-20, we’ll get a compilation error.
这个输出不是我们想要的。我们想要调用baby_name
函数,该函数是我们在Dog
上实现的Animal
特征的一部分,因此代码会打印A baby dog is called a puppy
。我们在清单 19-18 中使用的指定特征名称的技术在这里没有帮助;如果我们将main
更改为清单 19-20 中的代码,我们将收到编译错误。
Filename: src/main.rs 文件名:src/main.rs
Because Animal::baby_name
doesn’t have a self
parameter, and there could be
other types that implement the Animal
trait, Rust can’t figure out which
implementation of Animal::baby_name
we want. We’ll get this compiler error:
因为Animal::baby_name
没有self
参数,并且可能有其他类型实现Animal
特征,Rust 无法确定我们想要哪种Animal::baby_name
实现。我们会得到这个编译器错误:
$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> src/main.rs:20:43
|
2 | fn baby_name() -> String;
| ------------------------- `Animal::baby_name` defined here
...
20 | println!("A baby dog is called a {}", Animal::baby_name());
| ^^^^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use the fully-qualified path to the only available implementation
|
20 | println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
| +++++++ +
For more information about this error, try `rustc --explain E0790`.
error: could not compile `traits-example` (bin "traits-example") due to 1 previous error
To disambiguate and tell Rust that we want to use the implementation of
Animal
for Dog
as opposed to the implementation of Animal
for some other
type, we need to use fully qualified syntax. Listing 19-21 demonstrates how to
use fully qualified syntax.
为了消除歧义并告诉 Rust 我们想要使用Dog
的Animal
实现,而不是其他类型的Animal
实现,我们需要使用完全限定语法。清单 19-21 演示了如何使用完全限定语法。
Filename: src/main.rs 文件名:src/main.rs
We’re providing Rust with a type annotation within the angle brackets, which
indicates we want to call the baby_name
method from the Animal
trait as
implemented on Dog
by saying that we want to treat the Dog
type as an
Animal
for this function call. This code will now print what we want:
我们为 Rust 提供了尖括号内的类型注释,这表明我们希望从Animal
特征中调用baby_name
方法(如在Dog
上实现),表示我们希望在此函数调用中将Dog
类型视为Animal
。此代码现在将打印我们想要的内容:
$ 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
In general, fully qualified syntax is defined as follows:
一般来说,完全限定语法定义如下:
<Type as Trait>::function(receiver_if_method, next_arg, ...);
For associated functions that aren’t methods, there would not be a receiver
:
there would only be the list of other arguments. You could use fully qualified
syntax everywhere that you call functions or methods. However, you’re allowed
to omit any part of this syntax that Rust can figure out from other information
in the program. You only need to use this more verbose syntax in cases where
there are multiple implementations that use the same name and Rust needs help
to identify which implementation you want to call.
对于不是方法的关联函数,不会有receiver
:只会有其他参数的列表。您可以在调用函数或方法的任何地方使用完全限定语法。但是,您可以省略此语法中 Rust 可以从程序中的其他信息中找出的任何部分。仅当存在多个使用相同名称的实现并且 Rust 需要帮助来识别您要调用哪个实现时,您才需要使用这种更详细的语法。
Using Supertraits to Require One Trait’s Functionality Within Another Trait
使用超级特征来要求一个特征在另一个特征中具有功能
Sometimes, you might write a trait definition that depends on another trait:
for a type to implement the first trait, you want to require that type to also
implement the second trait. You would do this so that your trait definition can
make use of the associated items of the second trait. The trait your trait
definition is relying on is called a supertrait of your trait.
有时,您可能会编写依赖于另一个特征的特征定义:对于实现第一个特征的类型,您希望要求该类型也实现第二个特征。您可以这样做,以便您的特征定义可以利用第二个特征的关联项。你的特质定义所依赖的特质被称为你特质的超特质。
For example, let’s say we want to make an OutlinePrint
trait with an
outline_print
method that will print a given value formatted so that it’s
framed in asterisks. That is, given a Point
struct that implements the
standard library trait Display
to result in (x, y)
, when we call
outline_print
on a Point
instance that has 1
for x
and 3
for y
, it
should print the following:
例如,假设我们想要使用outline_print
方法创建一个OutlinePrint
特征,该方法将打印给定的格式化值,以便将其用星号框起来。也就是说,给定一个实现标准库特征Display
来生成(x, y)
的Point
结构,当我们在x
为1
、 y
为3
Point
实例上调用outline_print
时,它应该打印以下内容:
**********
* *
* (1, 3) *
* *
**********
In the implementation of the outline_print
method, we want to use the
Display
trait’s functionality. Therefore, we need to specify that the
OutlinePrint
trait will work only for types that also implement Display
and
provide the functionality that OutlinePrint
needs. We can do that in the
trait definition by specifying OutlinePrint: Display
. This technique is
similar to adding a trait bound to the trait. Listing 19-22 shows an
implementation of the OutlinePrint
trait.
在outline_print
方法的实现中,我们想要使用Display
特征的功能。因此,我们需要指定OutlinePrint
特征仅适用于也实现Display
并提供OutlinePrint
所需功能的类型。我们可以在特征定义中通过指定OutlinePrint: Display
做到这一点。此技术类似于添加与特征绑定的特征。清单 19-22 显示了OutlinePrint
特征的实现。
Filename: src/main.rs 文件名:src/main.rs
Because we’ve specified that OutlinePrint
requires the Display
trait, we
can use the to_string
function that is automatically implemented for any type
that implements Display
. If we tried to use to_string
without adding a
colon and specifying the Display
trait after the trait name, we’d get an
error saying that no method named to_string
was found for the type &Self
in
the current scope.
因为我们已经指定OutlinePrint
需要Display
特征,所以我们可以使用为任何实现Display
类型自动实现的to_string
函数。如果我们尝试使用to_string
而不添加冒号并在特征名称后指定Display
特征,我们会收到一条错误消息,指出在当前作用域中未找到类型&Self
的名为to_string
的方法。
Let’s see what happens when we try to implement OutlinePrint
on a type that
doesn’t implement Display
, such as the Point
struct:
让我们看看当我们尝试在未实现Display
类型(例如Point
结构)上实现OutlinePrint
时会发生什么:
Filename: src/main.rs 文件名:src/main.rs
We get an error saying that Display
is required but not implemented:
我们收到一条错误消息,指出Display
是必需的但未实现:
$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
error[E0277]: `Point` doesn't implement `std::fmt::Display`
--> src/main.rs:20:23
|
20 | impl OutlinePrint for Point {}
| ^^^^^ `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`
--> src/main.rs:3:21
|
3 | trait OutlinePrint: fmt::Display {
| ^^^^^^^^^^^^ required by this bound in `OutlinePrint`
error[E0277]: `Point` doesn't implement `std::fmt::Display`
--> src/main.rs:24:7
|
24 | p.outline_print();
| ^^^^^^^^^^^^^ `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`
--> src/main.rs:3:21
|
3 | trait OutlinePrint: fmt::Display {
| ^^^^^^^^^^^^ required by this bound in `OutlinePrint::outline_print`
4 | fn outline_print(&self) {
| ------------- required by a bound in this associated function
For more information about this error, try `rustc --explain E0277`.
error: could not compile `traits-example` (bin "traits-example") due to 2 previous errors
To fix this, we implement Display
on Point
and satisfy the constraint that
OutlinePrint
requires, like so:
为了解决这个问题,我们实现Display
on Point
并满足OutlinePrint
所需的约束,如下所示:
Filename: src/main.rs 文件名:src/main.rs
Then implementing the OutlinePrint
trait on Point
will compile
successfully, and we can call outline_print
on a Point
instance to display
it within an outline of asterisks.
然后在Point
上实现OutlinePrint
特征将成功编译,我们可以在Point
实例上调用outline_print
将其显示在星号轮廓内。
Using the Newtype Pattern to Implement External Traits on External Types
使用 Newtype 模式在外部类型上实现外部特征
In Chapter 10 in the “Implementing a Trait on a
Type” section, we mentioned the
orphan rule that states we’re only allowed to implement a trait on a type if
either the trait or the type are local to our crate. It’s possible to get
around this restriction using the newtype pattern, which involves creating a
new type in a tuple struct. (We covered tuple structs in the “Using Tuple
Structs without Named Fields to Create Different Types” section of Chapter 5.) The tuple struct will have one field and be a
thin wrapper around the type we want to implement a trait for. Then the wrapper
type is local to our crate, and we can implement the trait on the wrapper.
Newtype is a term that originates from the Haskell programming language.
There is no runtime performance penalty for using this pattern, and the wrapper
type is elided at compile time.
在第 10 章“在类型上实现特征”忽略部分中,我们提到了孤儿规则,该规则规定,只有当特征或类型对于我们的板条箱而言是本地的时,才允许我们在类型上实现特征。可以使用newtype 模式来绕过此限制,该模式涉及在元组结构中创建新类型。 (我们在第 5 章的“使用不带命名字段的元组结构创建不同类型”忽略部分中介绍了元组结构。)元组结构将有一个字段,并且是我们要为其实现特征的类型的薄包装器。那么包装器类型对于我们的板条箱来说是本地的,我们可以在包装器上实现该特征。 Newtype是一个源自 Haskell 编程语言的术语。使用此模式不会造成运行时性能损失,并且包装器类型会在编译时被忽略。
As an example, let’s say we want to implement Display
on Vec<T>
, which the
orphan rule prevents us from doing directly because the Display
trait and the
Vec<T>
type are defined outside our crate. We can make a Wrapper
struct
that holds an instance of Vec<T>
; then we can implement Display
on
Wrapper
and use the Vec<T>
value, as shown in Listing 19-23.
举个例子,假设我们想要在Vec<T>
上实现Display
,孤儿规则阻止我们直接执行此操作,因为Display
特征和Vec<T>
类型是在我们的板条箱外部定义的。我们可以创建一个Wrapper
结构体来保存Vec<T>
的实例;那么我们可以在Wrapper
上实现Display
并使用Vec<T>
值,如清单 19-23 所示。
Filename: src/main.rs 文件名:src/main.rs
use std::fmt;
struct Wrapper(Vec<String>);
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
fn main() {
let w = Wrapper(vec![String::from("hello"), String::from("world")]);
println!("w = {w}");
}
The implementation of Display
uses self.0
to access the inner Vec<T>
,
because Wrapper
is a tuple struct and Vec<T>
is the item at index 0 in the
tuple. Then we can use the functionality of the Display
trait on Wrapper
.Display
的实现使用self.0
来访问内部Vec<T>
,因为Wrapper
是一个元组结构,而Vec<T>
是元组中索引 0 处的项。然后我们可以在Wrapper
上使用Display
特征的功能。
The downside of using this technique is that Wrapper
is a new type, so it
doesn’t have the methods of the value it’s holding. We would have to implement
all the methods of Vec<T>
directly on Wrapper
such that the methods
delegate to self.0
, which would allow us to treat Wrapper
exactly like a
Vec<T>
. If we wanted the new type to have every method the inner type has,
implementing the Deref
trait (discussed in Chapter 15 in the “Treating Smart
Pointers Like Regular References with the Deref
Trait” section) on the Wrapper
to return
the inner type would be a solution. If we don’t want the Wrapper
type to have
all the methods of the inner type—for example, to restrict the Wrapper
type’s
behavior—we would have to implement just the methods we do want manually.
使用此技术的缺点是Wrapper
是一种新类型,因此它没有其所保存的值的方法。我们必须直接在Wrapper
上实现Vec<T>
的所有方法,以便这些方法委托给self.0
,这将允许我们像对待Vec<T>
一样对待Wrapper
。如果我们希望新类型具有内部类型所具有的所有方法,则在Wrapper
上实现Deref
特征(在第 15 章“使用Deref
特征像常规引用一样对待智能指针”忽略部分中讨论)以返回内部类型将成为一个解决方案。如果我们不希望Wrapper
类型拥有内部类型的所有方法(例如,限制Wrapper
类型的行为),我们就必须手动实现我们确实想要的方法。
This newtype pattern is also useful even when traits are not involved. Let’s
switch focus and look at some advanced ways to interact with Rust’s type system.
即使不涉及特征,这种新类型模式也很有用。让我们转移焦点,看看一些与 Rust 类型系统交互的高级方法。
Advanced Types 高级类型
The Rust type system has some features that we’ve so far mentioned but haven’t
yet discussed. We’ll start by discussing newtypes in general as we examine why
newtypes are useful as types. Then we’ll move on to type aliases, a feature
similar to newtypes but with slightly different semantics. We’ll also discuss
the !
type and dynamically sized types.
Rust 类型系统具有一些我们到目前为止已经提到但尚未讨论的功能。当我们研究为什么新类型作为类型有用时,我们将首先讨论新类型。然后我们将继续讨论类型别名,这是一个与新类型类似的功能,但语义略有不同。我们还将讨论!
类型和动态大小的类型。
Using the Newtype Pattern for Type Safety and Abstraction
使用 Newtype 模式实现类型安全和抽象
Note: This section assumes you’ve read the earlier section “Using the
Newtype Pattern to Implement External Traits on External
Types.”
注意:本节假设您已经阅读了前面的部分“使用 Newtype 模式在外部类型上实现外部特征”。
The newtype pattern is also useful for tasks beyond those we’ve discussed so
far, including statically enforcing that values are never confused and
indicating the units of a value. You saw an example of using newtypes to
indicate units in Listing 19-15: recall that the Millimeters
and Meters
structs wrapped u32
values in a newtype. If we wrote a function with a
parameter of type Millimeters
, we couldn’t compile a program that
accidentally tried to call that function with a value of type Meters
or a
plain u32
.
newtype 模式对于我们迄今为止讨论过的任务也很有用,包括静态地强制值永远不会混淆以及指示值的单位。您在清单 19-15 中看到了一个使用新类型来指示单位的示例:回想一下, Millimeters
和Meters
结构将u32
值包装在新类型中。如果我们编写一个带有Millimeters
类型参数的函数,则无法编译意外尝试使用Meters
类型值或普通u32
调用该函数的程序。
We can also use the newtype pattern to abstract away some implementation
details of a type: the new type can expose a public API that is different from
the API of the private inner type.
我们还可以使用 newtype 模式来抽象出类型的一些实现细节:新类型可以公开与私有内部类型的 API 不同的公共 API。
Newtypes can also hide internal implementation. For example, we could provide a
People
type to wrap a HashMap<i32, String>
that stores a person’s ID
associated with their name. Code using People
would only interact with the
public API we provide, such as a method to add a name string to the People
collection; that code wouldn’t need to know that we assign an i32
ID to names
internally. The newtype pattern is a lightweight way to achieve encapsulation
to hide implementation details, which we discussed in the “Encapsulation that
Hides Implementation
Details”
section of Chapter 17.
新类型还可以隐藏内部实现。例如,我们可以提供People
类型来包装HashMap<i32, String>
,用于存储与其姓名关联的人员 ID。使用People
代码只会与我们提供的公共 API 进行交互,例如向People
集合添加名称字符串的方法;该代码不需要知道我们在内部为名称分配了i32
ID。 newtype 模式是一种实现封装以隐藏实现细节的轻量级方法,我们在第 17 章的“隐藏实现细节的封装”忽略部分中对此进行了讨论。
Creating Type Synonyms with Type Aliases
使用类型别名创建类型同义词
Rust provides the ability to declare a type alias to give an existing type
another name. For this we use the type
keyword. For example, we can create
the alias Kilometers
to i32
like so:
Rust 提供了声明类型别名的能力,以便为现有类型提供另一个名称。为此,我们使用type
关键字。例如,我们可以创建i32
的别名Kilometers
,如下所示:
Now, the alias Kilometers
is a synonym for i32
; unlike the Millimeters
and Meters
types we created in Listing 19-15, Kilometers
is not a separate,
new type. Values that have the type Kilometers
will be treated the same as
values of type i32
:
现在,别名Kilometers
是i32
的同义词;与我们在清单 19-15 中创建的Millimeters
和Meters
类型不同, Kilometers
不是一个单独的新类型。 Kilometers
类型的值将被视为与i32
类型的值相同:
Because Kilometers
and i32
are the same type, we can add values of both
types and we can pass Kilometers
values to functions that take i32
parameters. However, using this method, we don’t get the type checking benefits
that we get from the newtype pattern discussed earlier. In other words, if we
mix up Kilometers
and i32
values somewhere, the compiler will not give us
an error.
由于Kilometers
和i32
是相同类型,因此我们可以将两种类型的值相加,并且可以将Kilometers
值传递给采用i32
参数的函数。但是,使用此方法,我们无法获得从前面讨论的 newtype 模式中获得的类型检查优势。换句话说,如果我们在某处混合了Kilometers
和i32
值,编译器不会给我们错误。
The main use case for type synonyms is to reduce repetition. For example, we
might have a lengthy type like this:
类型同义词的主要用例是减少重复。例如,我们可能有一个像这样的冗长类型:
Box<dyn Fn() + Send + 'static>
Writing this lengthy type in function signatures and as type annotations all
over the code can be tiresome and error prone. Imagine having a project full of
code like that in Listing 19-24.
在整个代码中将这种冗长的类型写入函数签名和类型注释可能会很烦人并且容易出错。想象一下,有一个项目充满了如清单 19-24 所示的代码。
A type alias makes this code more manageable by reducing the repetition. In
Listing 19-25, we’ve introduced an alias named Thunk
for the verbose type and
can replace all uses of the type with the shorter alias Thunk
.
类型别名通过减少重复使该代码更易于管理。在清单 19-25 中,我们为详细类型引入了一个名为Thunk
的别名,并且可以用较短的别名Thunk
替换该类型的所有使用。
This code is much easier to read and write! Choosing a meaningful name for a
type alias can help communicate your intent as well (thunk is a word for code
to be evaluated at a later time, so it’s an appropriate name for a closure that
gets stored).
这段代码更容易阅读和编写!为类型别名选择一个有意义的名称也可以帮助传达您的意图( thunk是一个词,表示稍后要评估的代码,因此它是存储闭包的合适名称)。
Type aliases are also commonly used with the Result<T, E>
type for reducing
repetition. Consider the std::io
module in the standard library. I/O
operations often return a Result<T, E>
to handle situations when operations
fail to work. This library has a std::io::Error
struct that represents all
possible I/O errors. Many of the functions in std::io
will be returning
Result<T, E>
where the E
is std::io::Error
, such as these functions in
the Write
trait:
类型别名也常与Result<T, E>
类型一起使用,以减少重复。考虑标准库中的std::io
模块。 I/O 操作通常返回Result<T, E>
以处理操作失败的情况。该库有一个std::io::Error
结构,表示所有可能的 I/O 错误。 std::io
中的许多函数将返回Result<T, E>
其中E
是std::io::Error
,例如Write
特征中的这些函数:
use std::fmt;
use std::io::Error;
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error>;
fn flush(&mut self) -> Result<(), Error>;
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>;
fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>;
}
The Result<..., Error>
is repeated a lot. As such, std::io
has this type
alias declaration:Result<..., Error>
重复了很多次。因此, std::io
具有以下类型别名声明:
Because this declaration is in the std::io
module, we can use the fully
qualified alias std::io::Result<T>
; that is, a Result<T, E>
with the E
filled in as std::io::Error
. The Write
trait function signatures end up
looking like this:
因为此声明位于std::io
模块中,所以我们可以使用完全限定别名std::io::Result<T>
;即Result<T, E>
其中E
填写为std::io::Error
。 Write
特征函数签名最终看起来像这样:
The type alias helps in two ways: it makes code easier to write and it gives
us a consistent interface across all of std::io
. Because it’s an alias, it’s
just another Result<T, E>
, which means we can use any methods that work on
Result<T, E>
with it, as well as special syntax like the ?
operator.
类型别名有两个作用:它使代码更容易编写,并为我们提供了跨所有std::io
一致接口。因为它是一个别名,所以它只是另一个Result<T, E>
,这意味着我们可以使用任何适用于Result<T, E>
方法,以及像?
这样的特殊语法。操作员。
The Never Type that Never Returns
永不返回的 Never 类型
Rust has a special type named !
that’s known in type theory lingo as the
empty type because it has no values. We prefer to call it the never type
because it stands in the place of the return type when a function will never
return. Here is an example:
Rust 有一个特殊的类型,名为!
这在类型论术语中被称为空类型,因为它没有值。我们更喜欢将其称为never 类型,因为当函数永远不会返回时,它代表返回类型。这是一个例子:
This code is read as “the function bar
returns never.” Functions that return
never are called diverging functions. We can’t create values of the type !
so bar
can never possibly return.
这段代码被解读为“函数bar
从不返回”。从不返回的函数称为发散函数。我们无法创建该类型的值!
所以bar
永远不可能回来。
But what use is a type you can never create values for? Recall the code from
Listing 2-5, part of the number guessing game; we’ve reproduced a bit of it
here in Listing 19-26.
但是,永远无法为其创建值的类型有什么用呢?回想一下清单 2-5 中的代码,这是猜数字游戏的一部分;我们在清单 19-26 中重现了其中的一部分。
At the time, we skipped over some details in this code. In Chapter 6 in “The
match
Control Flow Operator”
section, we discussed that match
arms must all return the same type. So, for
example, the following code doesn’t work:
当时,我们跳过了这段代码中的一些细节。在第 6 章“ match
控制流运算符”忽略部分中,我们讨论了match
臂必须返回相同的类型。因此,例如,以下代码不起作用:
The type of guess
in this code would have to be an integer and a string,
and Rust requires that guess
have only one type. So what does continue
return? How were we allowed to return a u32
from one arm and have another arm
that ends with continue
in Listing 19-26?
这段代码中的guess
类型必须是整数和字符串,而 Rust 要求guess
只有一种类型。那么continue
返回什么?我们如何被允许从一个分支返回u32
并让另一个分支以清单 19-26 中的continue
结尾?
As you might have guessed, continue
has a !
value. That is, when Rust
computes the type of guess
, it looks at both match arms, the former with a
value of u32
and the latter with a !
value. Because !
can never have a
value, Rust decides that the type of guess
is u32
.
正如您可能已经猜到的, continue
有一个!
价值。也就是说,当 Rust 计算guess
的类型时,它会查看两个匹配臂,前者的值为u32
,后者的值为!
价值。因为!
永远不可能有值,Rust 决定guess
的类型是u32
。
The formal way of describing this behavior is that expressions of type !
can
be coerced into any other type. We’re allowed to end this match
arm with
continue
because continue
doesn’t return a value; instead, it moves control
back to the top of the loop, so in the Err
case, we never assign a value to
guess
.
描述这种行为的正式方式是类型表达式!
可以强制转换为任何其他类型。我们可以用continue
来结束这个match
臂,因为continue
不返回值;相反,它将控制权移回循环顶部,因此在Err
情况下,我们永远不会为guess
分配值。
The never type is useful with the panic!
macro as well. Recall the unwrap
function that we call on Option<T>
values to produce a value or panic with
this definition:
never 类型对于panic!
宏观也是如此。回想一下我们对Option<T>
值调用的unwrap
函数,以使用以下定义生成值或恐慌:
In this code, the same thing happens as in the match
in Listing 19-26: Rust
sees that val
has the type T
and panic!
has the type !
, so the result
of the overall match
expression is T
. This code works because panic!
doesn’t produce a value; it ends the program. In the None
case, we won’t be
returning a value from unwrap
, so this code is valid.
在此代码中,发生了与清单 19-26 中的match
相同的情况:Rust 看到val
具有类型T
并panic!
有型!
,所以整体match
表达式的结果是T
。这段代码之所以有效,是因为panic!
不产生价值;它结束程序。在None
情况下,我们不会从unwrap
返回值,因此此代码是有效的。
One final expression that has the type !
is a loop
:
具有以下类型的最终表达式!
是一个loop
:
Here, the loop never ends, so !
is the value of the expression. However, this
wouldn’t be true if we included a break
, because the loop would terminate
when it got to the break
.
在这里,循环永远不会结束,所以!
是表达式的值。然而,如果我们包含一个break
,情况就不是这样了,因为循环在到达break
时就会终止。
Dynamically Sized Types and the Sized
Trait
动态大小类型和Sized
特征
Rust needs to know certain details about its types, such as how much space to
allocate for a value of a particular type. This leaves one corner of its type
system a little confusing at first: the concept of dynamically sized types.
Sometimes referred to as DSTs or unsized types, these types let us write
code using values whose size we can know only at runtime.
Rust 需要了解有关其类型的某些详细信息,例如为特定类型的值分配多少空间。这使得其类型系统的一个角落一开始有点令人困惑:动态大小类型的概念。有时称为DST或未调整大小的类型,这些类型允许我们使用只能在运行时知道其大小的值来编写代码。
Let’s dig into the details of a dynamically sized type called str
, which
we’ve been using throughout the book. That’s right, not &str
, but str
on
its own, is a DST. We can’t know how long the string is until runtime, meaning
we can’t create a variable of type str
, nor can we take an argument of type
str
. Consider the following code, which does not work:
让我们深入研究一个名为str
的动态大小类型的细节,我们在整本书中一直在使用它。没错,不是&str
,而是str
本身是 DST。直到运行时我们才知道字符串有多长,这意味着我们不能创建str
类型的变量,也不能接受str
类型的参数。考虑下面的代码,它不起作用:
Rust needs to know how much memory to allocate for any value of a particular
type, and all values of a type must use the same amount of memory. If Rust
allowed us to write this code, these two str
values would need to take up the
same amount of space. But they have different lengths: s1
needs 12 bytes of
storage and s2
needs 15. This is why it’s not possible to create a variable
holding a dynamically sized type.
Rust 需要知道为特定类型的任何值分配多少内存,并且同一类型的所有值必须使用相同的内存量。如果 Rust 允许我们编写这段代码,那么这两个str
值将需要占用相同的空间量。但它们的长度不同: s1
需要 12 个字节的存储空间,而s2
需要 15 个字节。这就是为什么无法创建保存动态大小类型的变量的原因。
So what do we do? In this case, you already know the answer: we make the types
of s1
and s2
a &str
rather than a str
. Recall from the “String
Slices” section of Chapter 4 that the slice data
structure just stores the starting position and the length of the slice. So
although a &T
is a single value that stores the memory address of where the
T
is located, a &str
is two values: the address of the str
and its
length. As such, we can know the size of a &str
value at compile time: it’s
twice the length of a usize
. That is, we always know the size of a &str
, no
matter how long the string it refers to is. In general, this is the way in
which dynamically sized types are used in Rust: they have an extra bit of
metadata that stores the size of the dynamic information. The golden rule of
dynamically sized types is that we must always put values of dynamically sized
types behind a pointer of some kind.
那么我们该怎么办呢?在这种情况下,您已经知道答案:我们将s1
和s2
的类型设为&str
而不是str
。回想一下第 4 章的“字符串切片”忽略部分,切片数据结构只存储切片的起始位置和长度。因此,虽然&T
是存储T
所在内存地址的单个值,但&str
是两个值: str
的地址及其长度。因此,我们可以在编译时知道&str
值的大小:它是usize
长度的两倍。也就是说,我们总是知道&str
的大小,无论它引用的字符串有多长。一般来说,这是 Rust 中使用动态大小类型的方式:它们有一个额外的元数据来存储动态信息的大小。动态大小类型的黄金法则是,我们必须始终将动态大小类型的值放在某种指针后面。
We can combine str
with all kinds of pointers: for example, Box<str>
or
Rc<str>
. In fact, you’ve seen this before but with a different dynamically
sized type: traits. Every trait is a dynamically sized type we can refer to by
using the name of the trait. In Chapter 17 in the “Using Trait Objects That
Allow for Values of Different
Types” section, we mentioned that to use traits as trait objects, we must
put them behind a pointer, such as &dyn Trait
or Box<dyn Trait>
(Rc<dyn Trait>
would work too).
我们可以将str
与各种指针组合:例如Box<str>
或Rc<str>
。事实上,您以前已经见过这种情况,但具有不同的动态大小类型:特征。每个特征都是动态大小的类型,我们可以通过使用特征的名称来引用。在第 17 章“使用允许不同类型值的 Trait 对象”忽略部分中,我们提到要将 Trait 用作 Trait 对象,我们必须将它们放在指针后面,例如&dyn Trait
或Box<dyn Trait>
( Rc<dyn Trait>
也可以工作)。
To work with DSTs, Rust provides the Sized
trait to determine whether or not
a type’s size is known at compile time. This trait is automatically implemented
for everything whose size is known at compile time. In addition, Rust
implicitly adds a bound on Sized
to every generic function. That is, a
generic function definition like this:
为了使用 DST,Rust 提供了Sized
特征来确定类型的大小在编译时是否已知。对于编译时大小已知的所有内容,都会自动实现此特征。此外,Rust 隐式地为每个泛型函数添加了Sized
绑定。也就是说,像这样的通用函数定义:
fn generic<T>(t: T) {
// --snip--
}
is actually treated as though we had written this:
实际上就像我们写了这样:
fn generic<T: Sized>(t: T) {
// --snip--
}
By default, generic functions will work only on types that have a known size at
compile time. However, you can use the following special syntax to relax this
restriction:
默认情况下,泛型函数仅适用于编译时大小已知的类型。但是,您可以使用以下特殊语法来放宽此限制:
fn generic<T: ?Sized>(t: &T) {
// --snip--
}
A trait bound on ?Sized
means “T
may or may not be Sized
” and this
notation overrides the default that generic types must have a known size at
compile time. The ?Trait
syntax with this meaning is only available for
Sized
, not any other traits.?Sized
上的特征绑定意味着“ T
可能会或可能不会被Sized
”,并且此表示法会覆盖泛型类型在编译时必须具有已知大小的默认值。具有此含义的?Trait
语法仅适用于Sized
,不适用于任何其他特征。
Also note that we switched the type of the t
parameter from T
to &T
.
Because the type might not be Sized
, we need to use it behind some kind of
pointer. In this case, we’ve chosen a reference.
另请注意,我们将t
参数的类型从T
切换为&T
。因为类型可能不是Sized
,所以我们需要在某种指针后面使用它。在本例中,我们选择了一个参考。
Next, we’ll talk about functions and closures!
接下来,我们来谈谈函数和闭包!
Advanced Functions and Closures
高级函数和闭包
This section explores some advanced features related to functions and closures,
including function pointers and returning closures.
本节探讨与函数和闭包相关的一些高级功能,包括函数指针和返回闭包。
Function Pointers 函数指针
We’ve talked about how to pass closures to functions; you can also pass regular
functions to functions! This technique is useful when you want to pass a
function you’ve already defined rather than defining a new closure. Functions
coerce to the type fn
(with a lowercase f), not to be confused with the Fn
closure trait. The fn
type is called a function pointer. Passing functions
with function pointers will allow you to use functions as arguments to other
functions.
我们已经讨论了如何将闭包传递给函数;您还可以将常规函数传递给函数!当您想要传递已经定义的函数而不是定义新的闭包时,此技术非常有用。函数强制转换为fn
类型(f 小写),不要与Fn
闭包特征混淆。 fn
类型称为函数指针。使用函数指针传递函数将允许您将函数用作其他函数的参数。
The syntax for specifying that a parameter is a function pointer is similar to
that of closures, as shown in Listing 19-27, where we’ve defined a function
add_one
that adds one to its parameter. The function do_twice
takes two
parameters: a function pointer to any function that takes an i32
parameter
and returns an i32
, and one i32
value. The do_twice
function calls the
function f
twice, passing it the arg
value, then adds the two function call
results together. The main
function calls do_twice
with the arguments
add_one
and 5
.
指定参数为函数指针的语法与闭包的语法类似,如清单 19-27 所示,其中我们定义了一个函数add_one
,该函数将其参数加一。函数do_twice
采用两个参数:一个函数指针,指向任何采用i32
参数并返回i32
函数,以及一个i32
值。 do_twice
函数调用函数f
两次,向其传递arg
值,然后将两次函数调用结果相加。 main
函数使用参数add_one
和5
调用do_twice
。
Filename: src/main.rs 文件名:src/main.rs
fn add_one(x: i32) -> i32 {
x + 1
}
fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
f(arg) + f(arg)
}
fn main() {
let answer = do_twice(add_one, 5);
println!("The answer is: {answer}");
}
This code prints The answer is: 12
. We specify that the parameter f
in
do_twice
is an fn
that takes one parameter of type i32
and returns an
i32
. We can then call f
in the body of do_twice
. In main
, we can pass
the function name add_one
as the first argument to do_twice
.
此代码打印The answer is: 12
。我们指定do_twice
中的参数f
是一个fn
,它接受一个i32
类型的参数并返回一个i32
。然后我们可以在do_twice
的主体中调用f
。在main
中,我们可以将函数名称add_one
作为第一个参数传递给do_twice
。
Unlike closures, fn
is a type rather than a trait, so we specify fn
as the
parameter type directly rather than declaring a generic type parameter with one
of the Fn
traits as a trait bound.
与闭包不同, fn
是一种类型而不是特征,因此我们直接指定fn
作为参数类型,而不是使用Fn
特征之一作为特征边界来声明泛型类型参数。
Function pointers implement all three of the closure traits (Fn
, FnMut
, and
FnOnce
), meaning you can always pass a function pointer as an argument for a
function that expects a closure. It’s best to write functions using a generic
type and one of the closure traits so your functions can accept either
functions or closures.
函数指针实现了所有三个闭包特征( Fn
、 FnMut
和FnOnce
),这意味着您始终可以将函数指针作为参数传递给需要闭包的函数。最好使用泛型类型和闭包特征之一来编写函数,以便您的函数可以接受函数或闭包。
That said, one example of where you would want to only accept fn
and not
closures is when interfacing with external code that doesn’t have closures: C
functions can accept functions as arguments, but C doesn’t have closures.
也就是说,您只想接受fn
而不是闭包的一个例子是与没有闭包的外部代码交互时:C 函数可以接受函数作为参数,但 C 没有闭包。
As an example of where you could use either a closure defined inline or a named
function, let’s look at a use of the map
method provided by the Iterator
trait in the standard library. To use the map
function to turn a vector of
numbers into a vector of strings, we could use a closure, like this:
作为可以使用内联定义的闭包或命名函数的示例,让我们看一下标准库中Iterator
特征提供的map
方法的使用。要使用map
函数将数字向量转换为字符串向量,我们可以使用闭包,如下所示:
Or we could name a function as the argument to map
instead of the closure,
like this:
或者我们可以将函数命名为map
而不是闭包的参数,如下所示:
Note that we must use the fully qualified syntax that we talked about earlier
in the “Advanced Traits” section because
there are multiple functions available named to_string
. Here, we’re using the
to_string
function defined in the ToString
trait, which the standard
library has implemented for any type that implements Display
.
请注意,我们必须使用前面在“高级特征”忽略部分中讨论过的完全限定语法,因为有多个名为to_string
函数可用。在这里,我们使用ToString
特征中定义的to_string
函数,标准库已为任何实现Display
类型实现了该函数。
Recall from the “Enum values” section of Chapter
6 that the name of each enum variant that we define also becomes an initializer
function. We can use these initializer functions as function pointers that
implement the closure traits, which means we can specify the initializer
functions as arguments for methods that take closures, like so:
回想一下第 6 章的“枚举值”忽略部分,我们定义的每个枚举变量的名称也成为一个初始化函数。我们可以使用这些初始化函数作为实现闭包特征的函数指针,这意味着我们可以将初始化函数指定为采用闭包的方法的参数,如下所示:
Here we create Status::Value
instances using each u32
value in the range
that map
is called on by using the initializer function of Status::Value
.
Some people prefer this style, and some people prefer to use closures. They
compile to the same code, so use whichever style is clearer to you.
在这里,我们使用Status::Value
Value 的初始化函数调用map
范围内的每个u32
值来创建 Status Status::Value
Value 实例。有些人喜欢这种风格,有些人喜欢使用闭包。它们编译为相同的代码,因此请使用您更清楚的样式。
Returning Closures 返回关闭
Closures are represented by traits, which means you can’t return closures
directly. In most cases where you might want to return a trait, you can instead
use the concrete type that implements the trait as the return value of the
function. However, you can’t do that with closures because they don’t have a
concrete type that is returnable; you’re not allowed to use the function
pointer fn
as a return type, for example.
闭包由特征表示,这意味着您不能直接返回闭包。在大多数情况下,您可能想要返回特征,您可以使用实现该特征的具体类型作为函数的返回值。然而,你不能用闭包来做到这一点,因为它们没有可返回的具体类型;例如,您不能使用函数指针fn
作为返回类型。
The following code tries to return a closure directly, but it won’t compile:
以下代码尝试直接返回闭包,但无法编译:
fn returns_closure() -> dyn Fn(i32) -> i32 {
|x| x + 1
}
The compiler error is as follows:
编译器错误如下:
$ cargo build
Compiling functions-example v0.1.0 (file:///projects/functions-example)
error[E0746]: return type cannot have an unboxed trait object
--> src/lib.rs:1:25
|
1 | fn returns_closure() -> dyn Fn(i32) -> i32 {
| ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
help: return an `impl Trait` instead of a `dyn Trait`, if all returned values are the same type
|
1 | fn returns_closure() -> impl Fn(i32) -> i32 {
| ~~~~
help: box the return type, and wrap all of the returned values in `Box::new`
|
1 ~ fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
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
The error references the Sized
trait again! Rust doesn’t know how much space
it will need to store the closure. We saw a solution to this problem earlier.
We can use a trait object:
该错误再次引用了Sized
特征! Rust 不知道需要多少空间来存储闭包。我们之前看到了这个问题的解决方案。我们可以使用特征对象:
fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
Box::new(|x| x + 1)
}
This code will compile just fine. For more about trait objects, refer to the
section “Using Trait Objects That Allow for Values of Different
Types” in Chapter 17.
这段代码可以很好地编译。有关特征对象的更多信息,请参阅第 17 章中的“使用允许不同类型值的特征对象”部分。
Next, let’s look at macros!
接下来我们就来看看宏吧!
Macros 宏
We’ve used macros like println!
throughout this book, but we haven’t fully
explored what a macro is and how it works. The term macro refers to a family
of features in Rust: declarative macros with macro_rules!
and three kinds
of procedural macros:
我们使用过像println!
贯穿本书,但我们还没有完全探讨什么是宏以及它是如何工作的。术语“宏”指的是 Rust 中的一系列功能:带有 Macro_rules 的声明性宏macro_rules!
以及三种过程宏:
- Custom
#[derive]
macros that specify code added with thederive
attribute used on structs and enums
自定义#[derive]
宏,指定使用结构和枚举上使用的derive
属性添加的代码 - Attribute-like macros that define custom attributes usable on any item
类似属性的宏,定义可用于任何项目的自定义属性 - Function-like macros that look like function calls but operate on the tokens
specified as their argument
类似函数的宏,看起来像函数调用,但对指定为其参数的标记进行操作
We’ll talk about each of these in turn, but first, let’s look at why we even
need macros when we already have functions.
我们将依次讨论其中的每一个,但首先,让我们看看为什么当我们已经有了函数时我们还需要宏。
The Difference Between Macros and Functions
宏和函数的区别
Fundamentally, macros are a way of writing code that writes other code, which
is known as metaprogramming. In Appendix C, we discuss the derive
attribute, which generates an implementation of various traits for you. We’ve
also used the println!
and vec!
macros throughout the book. All of these
macros expand to produce more code than the code you’ve written manually.
从根本上讲,宏是一种编写代码来编写其他代码的方法,这称为元编程。在附录 C 中,我们讨论了derive
属性,它为您生成各种特征的实现。我们还使用了println!
和vec!
贯穿整本书的宏。所有这些宏都会扩展以生成比您手动编写的代码更多的代码。
Metaprogramming is useful for reducing the amount of code you have to write and
maintain, which is also one of the roles of functions. However, macros have
some additional powers that functions don’t.
元编程对于减少必须编写和维护的代码量很有用,这也是函数的作用之一。但是,宏具有一些函数所没有的附加功能。
A function signature must declare the number and type of parameters the
function has. Macros, on the other hand, can take a variable number of
parameters: we can call println!("hello")
with one argument or
println!("hello {}", name)
with two arguments. Also, macros are expanded
before the compiler interprets the meaning of the code, so a macro can, for
example, implement a trait on a given type. A function can’t, because it gets
called at runtime and a trait needs to be implemented at compile time.
函数签名必须声明函数具有的参数的数量和类型。另一方面,宏可以采用可变数量的参数:我们可以使用一个参数调用println!("hello")
,或者使用两个参数调用println!("hello {}", name)
。此外,宏在编译器解释代码含义之前会被扩展,因此宏可以在给定类型上实现特征。函数不能,因为它在运行时被调用,并且特征需要在编译时实现。
The downside to implementing a macro instead of a function is that macro
definitions are more complex than function definitions because you’re writing
Rust code that writes Rust code. Due to this indirection, macro definitions are
generally more difficult to read, understand, and maintain than function
definitions.
实现宏而不是函数的缺点是宏定义比函数定义更复杂,因为您正在编写 Rust 代码,而 Rust 代码又在编写 Rust 代码。由于这种间接性,宏定义通常比函数定义更难以阅读、理解和维护。
Another important difference between macros and functions is that you must
define macros or bring them into scope before you call them in a file, as
opposed to functions you can define anywhere and call anywhere.
宏和函数之间的另一个重要区别是,在文件中调用宏之前,您必须定义宏或将它们纳入范围,这与您可以在任何地方定义和调用任何地方的函数相反。
Declarative Macros with macro_rules!
for General Metaprogramming
带有macro_rules!
用于通用元编程
The most widely used form of macros in Rust is the declarative macro. These
are also sometimes referred to as “macros by example,” “macro_rules!
macros,”
or just plain “macros.” At their core, declarative macros allow you to write
something similar to a Rust match
expression. As discussed in Chapter 6,
match
expressions are control structures that take an expression, compare the
resulting value of the expression to patterns, and then run the code associated
with the matching pattern. Macros also compare a value to patterns that are
associated with particular code: in this situation, the value is the literal
Rust source code passed to the macro; the patterns are compared with the
structure of that source code; and the code associated with each pattern, when
matched, replaces the code passed to the macro. This all happens during
compilation.
Rust 中使用最广泛的宏形式是声明性宏。这些有时也被称为“宏示例”、“ macro_rules!
宏”,或者只是简单的“宏”。从本质上讲,声明性宏允许您编写类似于 Rust match
表达式的内容。正如第 6 章中所讨论的, match
表达式是控制结构,它采用表达式,将表达式的结果值与模式进行比较,然后运行与匹配模式关联的代码。宏还将值与与特定代码关联的模式进行比较:在这种情况下,该值是传递给宏的文字 Rust 源代码;将模式与源代码的结构进行比较;与每个模式关联的代码在匹配时将替换传递给宏的代码。这一切都发生在编译期间。
To define a macro, you use the macro_rules!
construct. Let’s explore how to
use macro_rules!
by looking at how the vec!
macro is defined. Chapter 8
covered how we can use the vec!
macro to create a new vector with particular
values. For example, the following macro creates a new vector containing three
integers:
要定义宏,请使用macro_rules!
构造。让我们探索一下如何使用macro_rules!
通过查看vec!
宏已定义。第 8 章介绍了如何使用vec!
宏创建具有特定值的新向量。例如,以下宏创建一个包含三个整数的新向量:
We could also use the vec!
macro to make a vector of two integers or a vector
of five string slices. We wouldn’t be able to use a function to do the same
because we wouldn’t know the number or type of values up front.
我们还可以使用vec!
宏来创建两个整数的向量或五个字符串切片的向量。我们无法使用函数来执行相同的操作,因为我们无法预先知道值的数量或类型。
Listing 19-28 shows a slightly simplified definition of the vec!
macro.
清单 19-28 显示了vec!
的稍微简化的定义。宏。
Filename: src/lib.rs 文件名:src/lib.rs
#[macro_export]
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
Note: The actual definition of the vec!
macro in the standard library
includes code to preallocate the correct amount of memory up front. That code
is an optimization that we don’t include here to make the example simpler.
注意: vec!
标准库中的宏包含预先分配正确内存量的代码。该代码是一种优化,为了使示例更简单,我们没有在此处包含该代码。
The #[macro_export]
annotation indicates that this macro should be made
available whenever the crate in which the macro is defined is brought into
scope. Without this annotation, the macro can’t be brought into scope.#[macro_export]
注释指示每当定义该宏的包进入作用域时,该宏就应该可用。如果没有此注释,宏就无法进入作用域。
We then start the macro definition with macro_rules!
and the name of the
macro we’re defining without the exclamation mark. The name, in this case
vec
, is followed by curly brackets denoting the body of the macro definition.
然后我们用macro_rules!
以及我们定义的不带感叹号的宏的名称。名称(在本例中为vec
)后面跟着大括号,表示宏定义的主体。
The structure in the vec!
body is similar to the structure of a match
expression. Here we have one arm with the pattern ( $( $x:expr ),* )
,
followed by =>
and the block of code associated with this pattern. If the
pattern matches, the associated block of code will be emitted. Given that this
is the only pattern in this macro, there is only one valid way to match; any
other pattern will result in an error. More complex macros will have more than
one arm.vec!
中的结构body 类似于match
表达式的结构。这里我们有一个手臂,其模式为( $( $x:expr ),* )
,后跟=>
以及与该模式关联的代码块。如果模式匹配,则将发出关联的代码块。鉴于这是该宏中的唯一模式,因此只有一种有效的匹配方式;任何其他模式都会导致错误。更复杂的宏将有多个臂。
Valid pattern syntax in macro definitions is different than the pattern syntax
covered in Chapter 18 because macro patterns are matched against Rust code
structure rather than values. Let’s walk through what the pattern pieces in
Listing 19-28 mean; for the full macro pattern syntax, see the Rust
Reference.
宏定义中的有效模式语法与第 18 章中介绍的模式语法不同,因为宏模式与 Rust 代码结构而不是值进行匹配。让我们看一下清单 19-28 中的模式片段的含义;有关完整的宏模式语法,请参阅Rust 参考。
First, we use a set of parentheses to encompass the whole pattern. We use a
dollar sign ($
) to declare a variable in the macro system that will contain
the Rust code matching the pattern. The dollar sign makes it clear this is a
macro variable as opposed to a regular Rust variable. Next comes a set of
parentheses that captures values that match the pattern within the parentheses
for use in the replacement code. Within $()
is $x:expr
, which matches any
Rust expression and gives the expression the name $x
.
首先,我们使用一组括号来包含整个模式。我们使用美元符号 ( $
) 在宏系统中声明一个变量,该变量将包含与模式匹配的 Rust 代码。美元符号清楚地表明这是一个宏变量,而不是常规的 Rust 变量。接下来是一组括号,它们捕获与括号内的模式匹配的值,以便在替换代码中使用。 $()
中是$x:expr
,它匹配任何 Rust 表达式,并为表达式指定名称$x
。
The comma following $()
indicates that a literal comma separator character
could optionally appear after the code that matches the code in $()
. The *
specifies that the pattern matches zero or more of whatever precedes the *
.$()
后面的逗号表示文字逗号分隔符可以选择出现在$()
中的代码匹配的代码之后。 *
指定模式与*
之前的零个或多个内容匹配。
When we call this macro with vec![1, 2, 3];
, the $x
pattern matches three
times with the three expressions 1
, 2
, and 3
.
当我们用vec![1, 2, 3];
调用这个宏时, $x
模式与三个表达式1
、 2
和3
匹配三次。
Now let’s look at the pattern in the body of the code associated with this arm:
temp_vec.push()
within $()*
is generated for each part that matches $()
in the pattern zero or more times depending on how many times the pattern
matches. The $x
is replaced with each expression matched. When we call this
macro with vec![1, 2, 3];
, the code generated that replaces this macro call
will be the following:
现在让我们看看与该手臂相关的代码主体中的模式: $()*
中的temp_vec.push()
是为与模式中的$()
匹配零次或多次的每个部分生成的,具体取决于匹配的次数模式匹配。 $x
被替换为每个匹配的表达式。当我们用vec![1, 2, 3];
调用这个宏时,生成的替换该宏调用的代码如下:
{
let mut temp_vec = Vec::new();
temp_vec.push(1);
temp_vec.push(2);
temp_vec.push(3);
temp_vec
}
We’ve defined a macro that can take any number of arguments of any type and can
generate code to create a vector containing the specified elements.
我们定义了一个宏,它可以接受任意数量、任意类型的参数,并且可以生成代码来创建包含指定元素的向量。
To learn more about how to write macros, consult the online documentation or
other resources, such as “The Little Book of Rust Macros” started by
Daniel Keep and continued by Lukas Wirth.
要了解有关如何编写宏的更多信息,请查阅在线文档或其他资源,例如由 Daniel Keep 撰写并由 Lukas Wirth 继续编写的“The Little Book of Rust Macros” 。
Procedural Macros for Generating Code from Attributes
用于从属性生成代码的过程宏
The second form of macros is the procedural macro, which acts more like a
function (and is a type of procedure). Procedural macros accept some code as an
input, operate on that code, and produce some code as an output rather than
matching against patterns and replacing the code with other code as declarative
macros do. The three kinds of procedural macros are custom derive,
attribute-like, and function-like, and all work in a similar fashion.
宏的第二种形式是过程宏,它的作用更像是一个函数(并且是一种过程)。过程宏接受一些代码作为输入,对该代码进行操作,并生成一些代码作为输出,而不是像声明性宏那样匹配模式并用其他代码替换代码。这三种过程宏是自定义派生宏、类属性宏和类函数宏,并且都以类似的方式工作。
When creating procedural macros, the definitions must reside in their own crate
with a special crate type. This is for complex technical reasons that we hope
to eliminate in the future. In Listing 19-29, we show how to define a
procedural macro, where some_attribute
is a placeholder for using a specific
macro variety.
创建过程宏时,定义必须驻留在其自己的具有特殊 crate 类型的 crate 中。这是出于复杂的技术原因,我们希望将来能够消除这些原因。在清单 19-29 中,我们展示了如何定义过程宏,其中some_attribute
是使用特定宏种类的占位符。
Filename: src/lib.rs 文件名:src/lib.rs
use proc_macro;
#[some_attribute]
pub fn some_name(input: TokenStream) -> TokenStream {
}
The function that defines a procedural macro takes a TokenStream
as an input
and produces a TokenStream
as an output. The TokenStream
type is defined by
the proc_macro
crate that is included with Rust and represents a sequence of
tokens. This is the core of the macro: the source code that the macro is
operating on makes up the input TokenStream
, and the code the macro produces
is the output TokenStream
. The function also has an attribute attached to it
that specifies which kind of procedural macro we’re creating. We can have
multiple kinds of procedural macros in the same crate.
定义过程宏的函数将TokenStream
作为输入并生成TokenStream
作为输出。 TokenStream
类型由 Rust 附带的proc_macro
箱定义,表示令牌序列。这是宏的核心:宏正在操作的源代码构成了输入TokenStream
,宏生成的代码是输出TokenStream
。该函数还附加了一个属性,用于指定我们正在创建哪种类型的过程宏。我们可以在同一个 crate 中拥有多种类型的程序宏。
Let’s look at the different kinds of procedural macros. We’ll start with a
custom derive macro and then explain the small dissimilarities that make the
other forms different.
让我们看看不同类型的过程宏。我们将从自定义派生宏开始,然后解释使其他形式不同的微小差异。
How to Write a Custom derive
Macro
如何编写自定义derive
宏
Let’s create a crate named hello_macro
that defines a trait named
HelloMacro
with one associated function named hello_macro
. Rather than
making our users implement the HelloMacro
trait for each of their types,
we’ll provide a procedural macro so users can annotate their type with
#[derive(HelloMacro)]
to get a default implementation of the hello_macro
function. The default implementation will print Hello, Macro! My name is TypeName!
where TypeName
is the name of the type on which this trait has
been defined. In other words, we’ll write a crate that enables another
programmer to write code like Listing 19-30 using our crate.
让我们创建一个名为hello_macro
的包,它定义了一个名为HelloMacro
的特征以及一个名为hello_macro
的关联函数。我们不会让用户为每种类型实现HelloMacro
特征,而是提供一个过程宏,以便用户可以使用#[derive(HelloMacro)]
注释其类型,以获得hello_macro
函数的默认实现。默认实现将打印Hello, Macro! My name is TypeName!
其中TypeName
是定义此特征的类型的名称。换句话说,我们将编写一个 crate,使其他程序员能够使用我们的 crate 编写如清单 19-30 所示的代码。
Filename: src/main.rs 文件名:src/main.rs
use hello_macro::HelloMacro;
use hello_macro_derive::HelloMacro;
#[derive(HelloMacro)]
struct Pancakes;
fn main() {
Pancakes::hello_macro();
}
This code will print Hello, Macro! My name is Pancakes!
when we’re done. The
first step is to make a new library crate, like this:
此代码将打印Hello, Macro! My name is Pancakes!
当我们完成时。第一步是创建一个新的库箱,如下所示:
$ cargo new hello_macro --lib
Next, we’ll define the HelloMacro
trait and its associated function:
接下来,我们将定义HelloMacro
特征及其关联函数:
Filename: src/lib.rs 文件名:src/lib.rs
pub trait HelloMacro {
fn hello_macro();
}
We have a trait and its function. At this point, our crate user could implement
the trait to achieve the desired functionality, like so:
我们有一个特质及其功能。此时,我们的板条箱用户可以实现该特征来实现所需的功能,如下所示:
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();
}
However, they would need to write the implementation block for each type they
wanted to use with hello_macro
; we want to spare them from having to do this
work.
然而,他们需要为他们想要与hello_macro
一起使用的每种类型编写实现块;我们想让他们不必做这项工作。
Additionally, we can’t yet provide the hello_macro
function with default
implementation that will print the name of the type the trait is implemented
on: Rust doesn’t have reflection capabilities, so it can’t look up the type’s
name at runtime. We need a macro to generate code at compile time.
此外,我们还无法为hello_macro
函数提供默认实现,该实现将打印实现该特征的类型的名称:Rust 没有反射功能,因此它无法在运行时查找类型的名称。我们需要一个宏来在编译时生成代码。
The next step is to define the procedural macro. At the time of this writing,
procedural macros need to be in their own crate. Eventually, this restriction
might be lifted. The convention for structuring crates and macro crates is as
follows: for a crate named foo
, a custom derive procedural macro crate is
called foo_derive
. Let’s start a new crate called hello_macro_derive
inside
our hello_macro
project:
下一步是定义程序宏。在撰写本文时,程序宏需要位于其自己的包中。最终,这一限制可能会被取消。构造板条箱和宏板条箱的约定如下:对于名为foo
的板条箱,自定义派生过程宏板条箱称为foo_derive
。让我们在hello_macro
项目中启动一个名为hello_macro_derive
的新包:
$ cargo new hello_macro_derive --lib
Our two crates are tightly related, so we create the procedural macro crate
within the directory of our hello_macro
crate. If we change the trait
definition in hello_macro
, we’ll have to change the implementation of the
procedural macro in hello_macro_derive
as well. The two crates will need to
be published separately, and programmers using these crates will need to add
both as dependencies and bring them both into scope. We could instead have the
hello_macro
crate use hello_macro_derive
as a dependency and re-export the
procedural macro code. However, the way we’ve structured the project makes it
possible for programmers to use hello_macro
even if they don’t want the
derive
functionality.
我们的两个 crate 紧密相关,因此我们在hello_macro
crate 的目录中创建程序宏 crate。如果我们更改hello_macro
中的特征定义,我们也必须更改hello_macro_derive
中过程宏的实现。这两个包需要单独发布,使用这些包的程序员需要将它们添加为依赖项并将它们纳入范围。我们可以让hello_macro
箱使用hello_macro_derive
作为依赖项并重新导出过程宏代码。然而,我们构建项目的方式使程序员可以使用hello_macro
即使他们不想要derive
功能。
We need to declare the hello_macro_derive
crate as a procedural macro crate.
We’ll also need functionality from the syn
and quote
crates, as you’ll see
in a moment, so we need to add them as dependencies. Add the following to the
Cargo.toml file for hello_macro_derive
:
我们需要将hello_macro_derive
箱声明为程序宏箱。我们还需要来自syn
和quote
包的功能,稍后您将看到,因此我们需要将它们添加为依赖项。将以下内容添加到hello_macro_derive
的Cargo.toml文件中:
Filename: hello_macro_derive/Cargo.toml
文件名:hello_macro_derive/Cargo.toml
[lib]
proc-macro = true
[dependencies]
syn = "2.0"
quote = "1.0"
To start defining the procedural macro, place the code in Listing 19-31 into
your src/lib.rs file for the hello_macro_derive
crate. Note that this code
won’t compile until we add a definition for the impl_hello_macro
function.
要开始定义过程宏,请将清单 19-31 中的代码放入hello_macro_derive
crate 的src/lib.rs文件中。请注意,在我们添加impl_hello_macro
函数的定义之前,此代码不会编译。
Filename: hello_macro_derive/src/lib.rs
文件名:hello_macro_derive/src/lib.rs
use proc_macro::TokenStream;
use quote::quote;
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> 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(&ast)
}
Notice that we’ve split the code into the hello_macro_derive
function, which
is responsible for parsing the TokenStream
, and the impl_hello_macro
function, which is responsible for transforming the syntax tree: this makes
writing a procedural macro more convenient. The code in the outer function
(hello_macro_derive
in this case) will be the same for almost every
procedural macro crate you see or create. The code you specify in the body of
the inner function (impl_hello_macro
in this case) will be different
depending on your procedural macro’s purpose.
请注意,我们已将代码拆分为hello_macro_derive
函数(负责解析TokenStream
和impl_hello_macro
函数(负责转换语法树):这使得编写过程宏更加方便。对于您看到或创建的几乎每个过程宏包,外部函数中的代码(在本例中为hello_macro_derive
)都是相同的。您在内部函数主体中指定的代码(本例中为impl_hello_macro
)将根据过程宏的用途而有所不同。
We’ve introduced three new crates: proc_macro
, syn
, and quote
. The
proc_macro
crate comes with Rust, so we didn’t need to add that to the
dependencies in Cargo.toml. The proc_macro
crate is the compiler’s API that
allows us to read and manipulate Rust code from our code.
我们引入了三个新的 crate: proc_macro
、 syn
和quote
。 proc_macro
crate 附带 Rust,因此我们不需要将其添加到Cargo.toml中的依赖项中。 proc_macro
crate 是编译器的 API,允许我们从代码中读取和操作 Rust 代码。
The syn
crate parses Rust code from a string into a data structure that we
can perform operations on. The quote
crate turns syn
data structures back
into Rust code. These crates make it much simpler to parse any sort of Rust
code we might want to handle: writing a full parser for Rust code is no simple
task.syn
crate 将 Rust 代码从字符串解析为我们可以执行操作的数据结构。 quote
crate 将syn
数据结构重新转换为 Rust 代码。这些板条箱使解析我们可能想要处理的任何类型的 Rust 代码变得更加简单:为 Rust 代码编写完整的解析器并不是一件简单的任务。
The hello_macro_derive
function will be called when a user of our library
specifies #[derive(HelloMacro)]
on a type. This is possible because we’ve
annotated the hello_macro_derive
function here with proc_macro_derive
and
specified the name HelloMacro
, which matches our trait name; this is the
convention most procedural macros follow.
当我们库的用户在类型上指定#[derive(HelloMacro)]
时,将调用hello_macro_derive
函数。这是可能的,因为我们在这里用proc_macro_derive
注释了hello_macro_derive
函数,并指定了名称HelloMacro
,它与我们的特征名称相匹配;这是大多数程序宏遵循的约定。
The hello_macro_derive
function first converts the input
from a
TokenStream
to a data structure that we can then interpret and perform
operations on. This is where syn
comes into play. The parse
function in
syn
takes a TokenStream
and returns a DeriveInput
struct representing the
parsed Rust code. Listing 19-32 shows the relevant parts of the DeriveInput
struct we get from parsing the struct Pancakes;
string:hello_macro_derive
函数首先将input
从TokenStream
转换为我们可以解释和执行操作的数据结构。这就是syn
发挥作用的地方。 syn
中的parse
函数采用TokenStream
并返回表示解析后的 Rust 代码的DeriveInput
结构。清单 19-32 显示了我们通过解析 struct Pancakes 得到的DeriveInput
结构体的相关部分struct Pancakes;
细绳:
DeriveInput {
// --snip--
ident: Ident {
ident: "Pancakes",
span: #0 bytes(95..103)
},
data: Struct(
DataStruct {
struct_token: Struct,
fields: Unit,
semi_token: Some(
Semi
)
}
)
}
The fields of this struct show that the Rust code we’ve parsed is a unit struct
with the ident
(identifier, meaning the name) of Pancakes
. There are more
fields on this struct for describing all sorts of Rust code; check the syn
documentation for DeriveInput
for more information.
该结构体的字段表明我们解析的 Rust 代码是一个单位结构体,其ident
(标识符,意思是名称)为Pancakes
。该结构体上还有更多字段用于描述各种 Rust 代码;检查DeriveInput
的syn
文档以获取更多信息。
Soon we’ll define the impl_hello_macro
function, which is where we’ll build
the new Rust code we want to include. But before we do, note that the output
for our derive macro is also a TokenStream
. The returned TokenStream
is
added to the code that our crate users write, so when they compile their crate,
they’ll get the extra functionality that we provide in the modified
TokenStream
.
很快我们将定义impl_hello_macro
函数,我们将在其中构建我们想要包含的新 Rust 代码。但在此之前,请注意派生宏的输出也是TokenStream
。返回的TokenStream
被添加到我们的板条箱用户编写的代码中,因此当他们编译他们的板条箱时,他们将获得我们在修改后的TokenStream
中提供的额外功能。
You might have noticed that we’re calling unwrap
to cause the
hello_macro_derive
function to panic if the call to the syn::parse
function
fails here. It’s necessary for our procedural macro to panic on errors because
proc_macro_derive
functions must return TokenStream
rather than Result
to
conform to the procedural macro API. We’ve simplified this example by using
unwrap
; in production code, you should provide more specific error messages
about what went wrong by using panic!
or expect
.
您可能已经注意到,如果对syn::parse
函数的调用在此失败,我们调用unwrap
会导致hello_macro_derive
函数出现恐慌。我们的过程宏有必要对错误进行恐慌,因为proc_macro_derive
函数必须返回TokenStream
而不是Result
以符合过程宏 API。我们通过使用unwrap
简化了这个示例;在生产代码中,您应该通过使用panic!
或expect
。
Now that we have the code to turn the annotated Rust code from a TokenStream
into a DeriveInput
instance, let’s generate the code that implements the
HelloMacro
trait on the annotated type, as shown in Listing 19-33.
现在我们有了将带注释的 Rust 代码从TokenStream
转换为DeriveInput
实例的代码,让我们生成在带注释的类型上实现HelloMacro
特征的代码,如清单 19-33 所示。
Filename: hello_macro_derive/src/lib.rs
文件名:hello_macro_derive/src/lib.rs
We get an Ident
struct instance containing the name (identifier) of the
annotated type using ast.ident
. The struct in Listing 19-32 shows that when
we run the impl_hello_macro
function on the code in Listing 19-30, the
ident
we get will have the ident
field with a value of "Pancakes"
. Thus,
the name
variable in Listing 19-33 will contain an Ident
struct instance
that, when printed, will be the string "Pancakes"
, the name of the struct in
Listing 19-30.
我们使用ast.ident
获得一个Ident
结构实例,其中包含带注释的类型的名称(标识符)。清单 19-32 中的结构体显示,当我们对清单 19-30 中的代码运行impl_hello_macro
函数时,我们得到的ident
将具有值为"Pancakes"
的ident
字段。因此,清单 19-33 中的name
变量将包含一个Ident
结构体实例,打印时该实例将是字符串"Pancakes"
,即清单 19-30 中的结构体名称。
The quote!
macro lets us define the Rust code that we want to return. The
compiler expects something different to the direct result of the quote!
macro’s execution, so we need to convert it to a TokenStream
. We do this by
calling the into
method, which consumes this intermediate representation and
returns a value of the required TokenStream
type.quote!
宏让我们定义要返回的 Rust 代码。编译器期望的结果与quote!
宏的执行,因此我们需要将其转换为TokenStream
。我们通过调用into
方法来完成此操作,该方法使用此中间表示并返回所需的TokenStream
类型的值。
The quote!
macro also provides some very cool templating mechanics: we can
enter #name
, and quote!
will replace it with the value in the variable
name
. You can even do some repetition similar to the way regular macros work.
Check out the quote
crate’s docs for a thorough introduction.quote!
宏还提供了一些非常酷的模板机制:我们可以输入#name
,然后quote!
将用变量name
中的值替换它。您甚至可以像常规宏的工作方式一样进行一些重复。查看quote
crate 的文档以获取完整的介绍。
We want our procedural macro to generate an implementation of our HelloMacro
trait for the type the user annotated, which we can get by using #name
. The
trait implementation has the one function hello_macro
, whose body contains the
functionality we want to provide: printing Hello, Macro! My name is
and then
the name of the annotated type.
我们希望我们的程序宏为用户注释的类型生成HelloMacro
特征的实现,我们可以通过使用#name
来获得它。特征实现有一个函数hello_macro
,其主体包含我们想要提供的功能:打印Hello, Macro! My name is
,然后是注释类型的名称。
The stringify!
macro used here is built into Rust. It takes a Rust
expression, such as 1 + 2
, and at compile time turns the expression into a
string literal, such as "1 + 2"
. This is different than format!
or
println!
, macros which evaluate the expression and then turn the result into
a String
. There is a possibility that the #name
input might be an
expression to print literally, so we use stringify!
. Using stringify!
also
saves an allocation by converting #name
to a string literal at compile time.stringify!
这里使用的宏内置于 Rust 中。它采用 Rust 表达式,例如1 + 2
,并在编译时将表达式转换为字符串文字,例如"1 + 2"
。这与format!
或println!
、宏,它计算表达式,然后将结果转换为String
。 #name
输入有可能是一个按字面打印的表达式,所以我们使用stringify!
。使用stringify!
还通过在编译时将#name
转换为字符串文字来保存分配。
At this point, cargo build
should complete successfully in both hello_macro
and hello_macro_derive
. Let’s hook up these crates to the code in Listing
19-30 to see the procedural macro in action! Create a new binary project in
your projects directory using cargo new pancakes
. We need to add
hello_macro
and hello_macro_derive
as dependencies in the pancakes
crate’s Cargo.toml. If you’re publishing your versions of hello_macro
and
hello_macro_derive
to crates.io, they would be regular
dependencies; if not, you can specify them as path
dependencies as follows:
此时, cargo build
应该在hello_macro
和hello_macro_derive
中成功完成。让我们将这些 crate 连接到清单 19-30 中的代码来查看过程宏的运行情况!使用cargo new pancakes
在项目目录中创建一个新的二进制项目。我们需要在pancakes
箱的Cargo.toml中添加hello_macro
和hello_macro_derive
作为依赖项。如果您将hello_macro
和hello_macro_derive
版本发布到crates.io ,它们将是常规依赖项;如果没有,您可以将它们指定为path
依赖项,如下所示:
hello_macro = { path = "../hello_macro" }
hello_macro_derive = { path = "../hello_macro/hello_macro_derive" }
Put the code in Listing 19-30 into src/main.rs, and run cargo run
: it
should print Hello, Macro! My name is Pancakes!
The implementation of the
HelloMacro
trait from the procedural macro was included without the
pancakes
crate needing to implement it; the #[derive(HelloMacro)]
added the
trait implementation.
将清单 19-30 中的代码放入src/main.rs中,然后运行cargo run
:它应该打印Hello, Macro! My name is Pancakes!
程序宏中的HelloMacro
特征的实现被包含在内,而pancakes
crate 不需要实现它; #[derive(HelloMacro)]
添加了特征实现。
Next, let’s explore how the other kinds of procedural macros differ from custom
derive macros.
接下来,让我们探讨其他类型的过程宏与自定义派生宏有何不同。
Attribute-like macros 类似属性的宏
Attribute-like macros are similar to custom derive macros, but instead of
generating code for the derive
attribute, they allow you to create new
attributes. They’re also more flexible: derive
only works for structs and
enums; attributes can be applied to other items as well, such as functions.
Here’s an example of using an attribute-like macro: say you have an attribute
named route
that annotates functions when using a web application framework:
类属性宏与自定义派生宏类似,但它们不是为derive
属性生成代码,而是允许您创建新属性。它们也更灵活: derive
仅适用于结构和枚举;属性也可以应用于其他项目,例如函数。下面是使用类似属性的宏的示例:假设您有一个名为route
的属性,该属性在使用 Web 应用程序框架时注释函数:
#[route(GET, "/")]
fn index() {
This #[route]
attribute would be defined by the framework as a procedural
macro. The signature of the macro definition function would look like this:
该#[route]
属性将由框架定义为过程宏。宏定义函数的签名如下所示:
#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
Here, we have two parameters of type TokenStream
. The first is for the
contents of the attribute: the GET, "/"
part. The second is the body of the
item the attribute is attached to: in this case, fn index() {}
and the rest
of the function’s body.
这里,我们有两个TokenStream
类型的参数。第一个是属性的内容: GET, "/"
部分。第二个是属性附加到的项目的主体:在本例中是fn index() {}
和函数主体的其余部分。
Other than that, attribute-like macros work the same way as custom derive
macros: you create a crate with the proc-macro
crate type and implement a
function that generates the code you want!
除此之外,类属性宏的工作方式与自定义派生宏相同:您使用proc-macro
crate 类型创建一个 crate,并实现一个生成所需代码的函数!
Function-like macros 类似函数的宏
Function-like macros define macros that look like function calls. Similarly to
macro_rules!
macros, they’re more flexible than functions; for example, they
can take an unknown number of arguments. However, macro_rules!
macros can be
defined only using the match-like syntax we discussed in the section
“Declarative Macros with macro_rules!
for General
Metaprogramming” earlier. Function-like macros take a
TokenStream
parameter and their definition manipulates that TokenStream
using Rust code as the other two types of procedural macros do. An example of a
function-like macro is an sql!
macro that might be called like so:
类函数宏定义看起来像函数调用的宏。与macro_rules!
宏,它们比函数更灵活;例如,它们可以接受未知数量的参数。然而, macro_rules!
宏只能使用我们在“带有macro_rules!
”一节中讨论的类似匹配的语法来定义。对于通用元编程”,之前忽略。类似函数的宏采用TokenStream
参数,并且它们的定义使用 Rust 代码操作该TokenStream
,就像其他两种类型的过程宏一样。类函数宏的一个例子是sql!
宏可以这样调用:
let sql = sql!(SELECT * FROM posts WHERE id=1);
This macro would parse the SQL statement inside it and check that it’s
syntactically correct, which is much more complex processing than a
macro_rules!
macro can do. The sql!
macro would be defined like this:
该宏将解析其中的 SQL 语句并检查其语法是否正确,这比macro_rules!
宏可以做。 sql!
宏定义如下:
#[proc_macro]
pub fn sql(input: TokenStream) -> TokenStream {
This definition is similar to the custom derive macro’s signature: we receive
the tokens that are inside the parentheses and return the code we wanted to
generate.
此定义类似于自定义派生宏的签名:我们接收括号内的标记并返回我们想要生成的代码。
Summary 概括
Whew! Now you have some Rust features in your toolbox that you likely won’t use
often, but you’ll know they’re available in very particular circumstances.
We’ve introduced several complex topics so that when you encounter them in
error message suggestions or in other peoples’ code, you’ll be able to
recognize these concepts and syntax. Use this chapter as a reference to guide
you to solutions.
哇!现在,您的工具箱中有一些您可能不会经常使用的 Rust 功能,但您会知道它们在非常特殊的情况下可用。我们介绍了几个复杂的主题,以便当您在错误消息建议或其他人的代码中遇到它们时,您将能够识别这些概念和语法。使用本章作为参考来指导您找到解决方案。
Next, we’ll put everything we’ve discussed throughout the book into practice
and do one more project!
接下来,我们将把整本书中讨论的所有内容付诸实践,并再做一个项目!
Final Project: Building a Multithreaded Web Server
最终项目:构建多线程 Web 服务器
It’s been a long journey, but we’ve reached the end of the book. In this
chapter, we’ll build one more project together to demonstrate some of the
concepts we covered in the final chapters, as well as recap some earlier
lessons.
这是一段漫长的旅程,但我们已经到达了本书的结尾。在本章中,我们将一起构建另一个项目来演示我们在最后几章中介绍的一些概念,并回顾一些早期的课程。
For our final project, we’ll make a web server that says “hello” and looks like
Figure 20-1 in a web browser.
对于我们的最终项目,我们将制作一个显示“hello”的 Web 服务器,在 Web 浏览器中如图 20-1 所示。
Here is our plan for building the web server:
这是我们构建 Web 服务器的计划:
- Learn a bit about TCP and HTTP.
了解一些有关 TCP 和 HTTP 的知识。 - Listen for TCP connections on a socket.
侦听套接字上的 TCP 连接。 - Parse a small number of HTTP requests.
解析少量 HTTP 请求。 - Create a proper HTTP response.
创建正确的 HTTP 响应。 - Improve the throughput of our server with a thread pool.
使用线程池提高服务器的吞吐量。
Before we get started, we should mention one detail: the method we’ll use won’t
be the best way to build a web server with Rust. Community members have
published a number of production-ready crates available on
crates.io that provide more complete web server and
thread pool implementations than we’ll build. However, our intention in this
chapter is to help you learn, not to take the easy route. Because Rust is a
systems programming language, we can choose the level of abstraction we want to
work with and can go to a lower level than is possible or practical in other
languages. We’ll therefore write the basic HTTP server and thread pool manually
so you can learn the general ideas and techniques behind the crates you might
use in the future.
在开始之前,我们应该提到一个细节:我们将使用的方法并不是使用 Rust 构建 Web 服务器的最佳方法。社区成员在crates.io上发布了许多可用于生产的 crate,它们提供了比我们构建的更完整的 Web 服务器和线程池实现。然而,我们本章的目的是帮助您学习,而不是走捷径。因为 Rust 是一种系统编程语言,所以我们可以选择我们想要使用的抽象级别,并且可以达到比其他语言可能或实用的更低的级别。因此,我们将手动编写基本的 HTTP 服务器和线程池,以便您可以了解将来可能使用的 crate 背后的一般思想和技术。
Building a Single-Threaded Web Server
构建单线程 Web 服务器
We’ll start by getting a single-threaded web server working. Before we begin,
let’s look at a quick overview of the protocols involved in building web
servers. The details of these protocols are beyond the scope of this book, but
a brief overview will give you the information you need.
我们将从让单线程 Web 服务器运行开始。在开始之前,让我们快速概述一下构建 Web 服务器所涉及的协议。这些协议的详细信息超出了本书的范围,但简要概述将为您提供所需的信息。
The two main protocols involved in web servers are Hypertext Transfer
Protocol (HTTP) and Transmission Control Protocol (TCP). Both protocols
are request-response protocols, meaning a client initiates requests and a
server listens to the requests and provides a response to the client. The
contents of those requests and responses are defined by the protocols.
Web 服务器涉及的两个主要协议是超文本传输协议(HTTP)和传输控制协议(TCP) 。这两种协议都是请求-响应协议,这意味着客户端发起请求,服务器监听请求并向客户端提供响应。这些请求和响应的内容由协议定义。
TCP is the lower-level protocol that describes the details of how information
gets from one server to another but doesn’t specify what that information is.
HTTP builds on top of TCP by defining the contents of the requests and
responses. It’s technically possible to use HTTP with other protocols, but in
the vast majority of cases, HTTP sends its data over TCP. We’ll work with the
raw bytes of TCP and HTTP requests and responses.
TCP 是较低级别的协议,它描述信息如何从一台服务器传输到另一台服务器的详细信息,但不指定该信息是什么。 HTTP 通过定义请求和响应的内容构建在 TCP 之上。从技术上讲,可以将 HTTP 与其他协议结合使用,但在绝大多数情况下,HTTP 通过 TCP 发送数据。我们将使用 TCP 和 HTTP 请求和响应的原始字节。
Listening to the TCP Connection
监听 TCP 连接
Our web server needs to listen to a TCP connection, so that’s the first part
we’ll work on. The standard library offers a std::net
module that lets us do
this. Let’s make a new project in the usual fashion:
我们的 Web 服务器需要侦听 TCP 连接,因此这是我们要处理的第一部分。标准库提供了一个std::net
模块,可以让我们做到这一点。让我们以通常的方式创建一个新项目:
$ cargo new hello
Created binary (application) `hello` project
$ cd hello
Now enter the code in Listing 20-1 in src/main.rs to start. This code will
listen at the local address 127.0.0.1:7878
for incoming TCP streams. When it
gets an incoming stream, it will print Connection established!
.
现在在src/main.rs中输入清单 20-1 中的代码来启动。此代码将在本地地址127.0.0.1:7878
侦听传入的 TCP 流。当它收到传入流时,它会打印Connection established!
。
Filename: src/main.rs 文件名:src/main.rs
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!");
}
}
Using TcpListener
, we can listen for TCP connections at the address
127.0.0.1:7878
. In the address, the section before the colon is an IP address
representing your computer (this is the same on every computer and doesn’t
represent the authors’ computer specifically), and 7878
is the port. We’ve
chosen this port for two reasons: HTTP isn’t normally accepted on this port so
our server is unlikely to conflict with any other web server you might have
running on your machine, and 7878 is rust typed on a telephone.
使用TcpListener
,我们可以监听地址127.0.0.1:7878
的 TCP 连接。在地址中,冒号之前的部分是代表您计算机的IP地址(这在每台计算机上都是相同的,并不具体代表作者的计算机), 7878
是端口。我们选择此端口有两个原因:此端口通常不接受 HTTP,因此我们的服务器不太可能与您计算机上运行的任何其他 Web 服务器发生冲突,并且 7878 是在电话上键入的。
The bind
function in this scenario works like the new
function in that it
will return a new TcpListener
instance. The function is called bind
because, in networking, connecting to a port to listen to is known as “binding
to a port.”
在这种情况下, bind
函数的工作方式与new
函数类似,它将返回一个新的TcpListener
实例。该函数称为bind
,因为在网络中,连接到要侦听的端口称为“绑定到端口”。
The bind
function returns a Result<T, E>
, which indicates that it’s
possible for binding to fail. For example, connecting to port 80 requires
administrator privileges (nonadministrators can listen only on ports higher
than 1023), so if we tried to connect to port 80 without being an
administrator, binding wouldn’t work. Binding also wouldn’t work, for example,
if we ran two instances of our program and so had two programs listening to the
same port. Because we’re writing a basic server just for learning purposes, we
won’t worry about handling these kinds of errors; instead, we use unwrap
to
stop the program if errors happen.bind
函数返回Result<T, E>
,这表明绑定可能会失败。例如,连接到端口 80 需要管理员权限(非管理员只能侦听高于 1023 的端口),因此如果我们尝试在没有管理员身份的情况下连接到端口 80,则绑定将不起作用。绑定也不起作用,例如,如果我们运行程序的两个实例,并且有两个程序侦听同一端口。因为我们编写一个基本服务器只是为了学习目的,所以我们不会担心处理这些类型的错误;相反,如果发生错误,我们使用unwrap
来停止程序。
The incoming
method on TcpListener
returns an iterator that gives us a
sequence of streams (more specifically, streams of type TcpStream
). A single
stream represents an open connection between the client and the server. A
connection is the name for the full request and response process in which a
client connects to the server, the server generates a response, and the server
closes the connection. As such, we will read from the TcpStream
to see what
the client sent and then write our response to the stream to send data back to
the client. Overall, this for
loop will process each connection in turn and
produce a series of streams for us to handle.TcpListener
上的incoming
方法返回一个迭代器,该迭代器为我们提供了一系列流(更具体地说,是TcpStream
类型的流)。单个流代表客户端和服务器之间的开放连接。连接是完整的请求和响应过程的名称,其中客户端连接到服务器,服务器生成响应,然后服务器关闭连接。因此,我们将从TcpStream
中读取以查看客户端发送的内容,然后将响应写入流以将数据发送回客户端。总的来说,这个for
循环将依次处理每个连接并产生一系列流供我们处理。
For now, our handling of the stream consists of calling unwrap
to terminate
our program if the stream has any errors; if there aren’t any errors, the
program prints a message. We’ll add more functionality for the success case in
the next listing. The reason we might receive errors from the incoming
method
when a client connects to the server is that we’re not actually iterating over
connections. Instead, we’re iterating over connection attempts. The
connection might not be successful for a number of reasons, many of them
operating system specific. For example, many operating systems have a limit to
the number of simultaneous open connections they can support; new connection
attempts beyond that number will produce an error until some of the open
connections are closed.
目前,我们对流的处理包括:如果流有任何错误,则调用unwrap
来终止我们的程序;如果没有任何错误,程序将打印一条消息。我们将在下一个清单中为成功案例添加更多功能。当客户端连接到服务器时,我们可能会从incoming
方法收到错误,原因是我们实际上并未迭代连接。相反,我们正在迭代连接尝试。连接可能会因多种原因而失败,其中许多原因是特定于操作系统的。例如,许多操作系统对其可以支持的同时打开连接的数量有限制;超过该数量的新连接尝试将产生错误,直到关闭某些打开的连接。
Let’s try running this code! Invoke cargo run
in the terminal and then load
127.0.0.1:7878 in a web browser. The browser should show an error message
like “Connection reset,” because the server isn’t currently sending back any
data. But when you look at your terminal, you should see several messages that
were printed when the browser connected to the server!
让我们尝试运行这段代码!在终端中调用cargo run
,然后在 Web 浏览器中加载127.0.0.1:7878 。浏览器应该显示一条错误消息,例如“连接重置”,因为服务器当前没有发回任何数据。但是当您查看终端时,您应该会看到浏览器连接到服务器时打印的几条消息!
Running `target/debug/hello`
Connection established!
Connection established!
Connection established!
Sometimes, you’ll see multiple messages printed for one browser request; the
reason might be that the browser is making a request for the page as well as a
request for other resources, like the favicon.ico icon that appears in the
browser tab.
有时,您会看到针对一个浏览器请求打印多条消息;原因可能是浏览器正在请求该页面以及其他资源,例如浏览器选项卡中显示的favicon.ico图标。
It could also be that the browser is trying to connect to the server multiple
times because the server isn’t responding with any data. When stream
goes out
of scope and is dropped at the end of the loop, the connection is closed as
part of the drop
implementation. Browsers sometimes deal with closed
connections by retrying, because the problem might be temporary. The important
factor is that we’ve successfully gotten a handle to a TCP connection!
也可能是浏览器多次尝试连接到服务器,因为服务器没有响应任何数据。当stream
超出范围并在循环结束时被删除时,连接将作为drop
实现的一部分关闭。浏览器有时会通过重试来处理关闭的连接,因为问题可能是暂时的。重要的是我们已经成功获得了 TCP 连接的句柄!
Remember to stop the program by pressing ctrl-c when
you’re done running a particular version of the code. Then restart the program
by invoking the cargo run
command after you’ve made each set of code changes
to make sure you’re running the newest code.
请记住按停止程序 ctrl - c 当您运行完特定版本的代码时。然后,在完成每组代码更改后,通过调用cargo run
命令来重新启动程序,以确保运行最新的代码。
Reading the Request 阅读请求
Let’s implement the functionality to read the request from the browser! To
separate the concerns of first getting a connection and then taking some action
with the connection, we’ll start a new function for processing connections. In
this new handle_connection
function, we’ll read data from the TCP stream and
print it so we can see the data being sent from the browser. Change the code to
look like Listing 20-2.
让我们实现从浏览器读取请求的功能!为了区分首先获取连接然后对连接执行某些操作的问题,我们将启动一个新函数来处理连接。在这个新的handle_connection
函数中,我们将从TCP流中读取数据并打印出来,这样我们就可以看到从浏览器发送的数据。将代码更改为如清单 20-2 所示。
Filename: src/main.rs 文件名:src/main.rs
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(&mut stream);
let http_request: Vec<_> = buf_reader
.lines()
.map(|result| result.unwrap())
.take_while(|line| !line.is_empty())
.collect();
println!("Request: {http_request:#?}");
}
We bring std::io::prelude
and std::io::BufReader
into scope to get access
to traits and types that let us read from and write to the stream. In the for
loop in the main
function, instead of printing a message that says we made a
connection, we now call the new handle_connection
function and pass the
stream
to it.
我们将std::io::prelude
和std::io::BufReader
引入作用域,以访问允许我们读取和写入流的特征和类型。在main
函数的for
循环中,我们现在调用新的handle_connection
函数并将stream
递给它,而不是打印一条表示我们已建立连接的消息。
In the handle_connection
function, we create a new BufReader
instance that
wraps a mutable reference to the stream
. BufReader
adds buffering by
managing calls to the std::io::Read
trait methods for us.
在handle_connection
函数中,我们创建一个新的BufReader
实例,它包装了stream
的可变引用。 BufReader
通过管理对std::io::Read
特征方法的调用来添加缓冲。
We create a variable named http_request
to collect the lines of the request
the browser sends to our server. We indicate that we want to collect these
lines in a vector by adding the Vec<_>
type annotation.
我们创建一个名为http_request
的变量来收集浏览器发送到服务器的请求行。我们通过添加Vec<_>
类型注释来表明我们想要将这些行收集到向量中。
BufReader
implements the std::io::BufRead
trait, which provides the lines
method. The lines
method returns an iterator of Result<String, std::io::Error>
by splitting the stream of data whenever it sees a newline
byte. To get each String
, we map and unwrap
each Result
. The Result
might be an error if the data isn’t valid UTF-8 or if there was a problem
reading from the stream. Again, a production program should handle these errors
more gracefully, but we’re choosing to stop the program in the error case for
simplicity.BufReader
实现了std::io::BufRead
特征,它提供了lines
方法。 lines
方法通过每当看到换行字节时分割数据流来返回Result<String, std::io::Error>
的迭代器。为了获取每个String
,我们映射并unwrap
每个Result
。如果数据不是有效的 UTF-8 或者从流读取时出现问题, Result
可能会出现错误。同样,生产程序应该更优雅地处理这些错误,但为了简单起见,我们选择在错误情况下停止程序。
The browser signals the end of an HTTP request by sending two newline
characters in a row, so to get one request from the stream, we take lines until
we get a line that is the empty string. Once we’ve collected the lines into the
vector, we’re printing them out using pretty debug formatting so we can take a
look at the instructions the web browser is sending to our server.
浏览器通过连续发送两个换行符来表示 HTTP 请求的结束,因此为了从流中获取一个请求,我们需要获取一行,直到得到一行空字符串。一旦我们将这些行收集到向量中,我们就会使用漂亮的调试格式将它们打印出来,这样我们就可以查看网络浏览器发送到我们服务器的指令。
Let’s try this code! Start the program and make a request in a web browser
again. Note that we’ll still get an error page in the browser, but our
program’s output in the terminal will now look similar to this:
让我们试试这段代码!启动程序并再次在网络浏览器中发出请求。请注意,我们仍然会在浏览器中看到错误页面,但我们的程序在终端中的输出现在看起来与此类似:
$ 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",
]
Depending on your browser, you might get slightly different output. Now that
we’re printing the request data, we can see why we get multiple connections
from one browser request by looking at the path after GET
in the first line
of the request. If the repeated connections are all requesting /, we know the
browser is trying to fetch / repeatedly because it’s not getting a response
from our program.
根据您的浏览器,您可能会得到略有不同的输出。现在我们正在打印请求数据,通过查看请求第一行中GET
之后的路径,我们可以了解为什么我们从一个浏览器请求获得多个连接。如果重复的连接都在请求/ ,我们就知道浏览器正在尝试重复获取/ ,因为它没有从我们的程序中得到响应。
Let’s break down this request data to understand what the browser is asking of
our program.
让我们分解这个请求数据,以了解浏览器向我们的程序询问什么。
A Closer Look at an HTTP Request
仔细观察 HTTP 请求
HTTP is a text-based protocol, and a request takes this format:
HTTP 是基于文本的协议,请求采用以下格式:
Method Request-URI HTTP-Version CRLF
headers CRLF
message-body
The first line is the request line that holds information about what the
client is requesting. The first part of the request line indicates the method
being used, such as GET
or POST
, which describes how the client is making
this request. Our client used a GET
request, which means it is asking for
information.
第一行是请求行,保存有关客户端请求的信息。请求行的第一部分指示正在使用的方法,例如GET
或POST
,它描述了客户端如何发出此请求。我们的客户使用了GET
请求,这意味着它正在询问信息。
The next part of the request line is /, which indicates the Uniform Resource
Identifier (URI) the client is requesting: a URI is almost, but not quite,
the same as a Uniform Resource Locator (URL). The difference between URIs
and URLs isn’t important for our purposes in this chapter, but the HTTP spec
uses the term URI, so we can just mentally substitute URL for URI here.
请求行的下一部分是/ ,它指示客户端正在请求的统一资源标识符(URI) :URI 与统一资源定位符(URL)几乎相同,但不完全相同。 URI 和 URL 之间的区别对于我们本章的目的来说并不重要,但 HTTP 规范使用术语 URI,因此我们可以在这里用 URL 代替 URI。
The last part is the HTTP version the client uses, and then the request line
ends in a CRLF sequence. (CRLF stands for carriage return and line feed,
which are terms from the typewriter days!) The CRLF sequence can also be
written as \r\n
, where \r
is a carriage return and \n
is a line feed. The
CRLF sequence separates the request line from the rest of the request data.
Note that when the CRLF is printed, we see a new line start rather than \r\n
.
最后一部分是客户端使用的HTTP版本,然后请求行以CRLF序列结束。 (CRLF 代表回车符和换行符,这是打字机时代的术语!)CRLF 序列也可以写为\r\n
,其中\r
是回车符, \n
是换行符。 CRLF 序列将请求行与请求数据的其余部分分开。请注意,当打印 CRLF 时,我们看到一个新行开始,而不是\r\n
。
Looking at the request line data we received from running our program so far,
we see that GET
is the method, / is the request URI, and HTTP/1.1
is the
version.
查看到目前为止运行程序收到的请求行数据,我们看到GET
是方法, /是请求 URI, HTTP/1.1
是版本。
After the request line, the remaining lines starting from Host:
onward are
headers. GET
requests have no body.
在请求行之后,从Host:
开始的其余行是标头。 GET
请求没有正文。
Try making a request from a different browser or asking for a different
address, such as 127.0.0.1:7878/test, to see how the request data changes.
尝试从不同的浏览器发出请求或请求不同的地址,例如127.0.0.1:7878/test ,以查看请求数据如何变化。
Now that we know what the browser is asking for, let’s send back some data!
现在我们知道浏览器要求什么,让我们发回一些数据!
Writing a Response 写回应
We’re going to implement sending data in response to a client request.
Responses have the following format:
我们将实现发送数据以响应客户端请求。响应具有以下格式:
HTTP-Version Status-Code Reason-Phrase CRLF
headers CRLF
message-body
The first line is a status line that contains the HTTP version used in the
response, a numeric status code that summarizes the result of the request, and
a reason phrase that provides a text description of the status code. After the
CRLF sequence are any headers, another CRLF sequence, and the body of the
response.
第一行是状态行,其中包含响应中使用的 HTTP 版本、总结请求结果的数字状态代码以及提供状态代码文本描述的原因短语。 CRLF 序列之后是任何标头、另一个 CRLF 序列和响应正文。
Here is an example response that uses HTTP version 1.1, has a status code of
200, an OK reason phrase, no headers, and no body:
以下是使用 HTTP 版本 1.1 的示例响应,状态代码为 200,OK 原因短语,没有标头,也没有正文:
HTTP/1.1 200 OK\r\n\r\n
The status code 200 is the standard success response. The text is a tiny
successful HTTP response. Let’s write this to the stream as our response to a
successful request! From the handle_connection
function, remove the
println!
that was printing the request data and replace it with the code in
Listing 20-3.
状态代码 200 是标准的成功响应。该文本是一个微小的成功 HTTP 响应。让我们将其写入流作为对成功请求的响应!从handle_connection
函数中,删除println!
打印请求数据并将其替换为清单 20-3 中的代码。
Filename: src/main.rs 文件名:src/main.rs
The first new line defines the response
variable that holds the success
message’s data. Then we call as_bytes
on our response
to convert the string
data to bytes. The write_all
method on stream
takes a &[u8]
and sends
those bytes directly down the connection. Because the write_all
operation
could fail, we use unwrap
on any error result as before. Again, in a real
application you would add error handling here.
第一个新行定义保存成功消息数据的response
变量。然后我们在response
中调用as_bytes
将字符串数据转换为字节。 stream
上的write_all
方法采用&[u8]
并直接通过连接发送这些字节。由于write_all
操作可能会失败,因此我们像以前一样对任何错误结果使用unwrap
。同样,在实际应用程序中,您将在此处添加错误处理。
With these changes, let’s run our code and make a request. We’re no longer
printing any data to the terminal, so we won’t see any output other than the
output from Cargo. When you load 127.0.0.1:7878 in a web browser, you should
get a blank page instead of an error. You’ve just hand-coded receiving an HTTP
request and sending a response!
完成这些更改后,让我们运行代码并发出请求。我们不再将任何数据打印到终端,因此除了 Cargo 的输出之外,我们不会看到任何输出。当您在 Web 浏览器中加载127.0.0.1:7878时,您应该看到一个空白页面而不是错误。您刚刚手动编写了接收 HTTP 请求并发送响应的代码!
Returning Real HTML 返回真实的 HTML
Let’s implement the functionality for returning more than a blank page. Create
the new file hello.html in the root of your project directory, not in the
src directory. You can input any HTML you want; Listing 20-4 shows one
possibility.
让我们实现返回多个空白页面的功能。在项目目录的根目录中创建新文件hello.html ,而不是在src目录中。您可以输入任何您想要的HTML;清单 20-4 显示了一种可能性。
Filename: hello.html 文件名: 你好.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello!</title>
</head>
<body>
<h1>Hello!</h1>
<p>Hi from Rust</p>
</body>
</html>
This is a minimal HTML5 document with a heading and some text. To return this
from the server when a request is received, we’ll modify handle_connection
as
shown in Listing 20-5 to read the HTML file, add it to the response as a body,
and send it.
这是一个最小的 HTML5 文档,带有标题和一些文本。为了在收到请求时从服务器返回此信息,我们将修改handle_connection
(如清单 20-5 所示)以读取 HTML 文件,将其作为正文添加到响应中,然后发送它。
Filename: src/main.rs 文件名:src/main.rs
We’ve added fs
to the use
statement to bring the standard library’s
filesystem module into scope. The code for reading the contents of a file to a
string should look familiar; we used it in Chapter 12 when we read the contents
of a file for our I/O project in Listing 12-4.
我们已将fs
添加到use
语句中,以将标准库的文件系统模块纳入范围。将文件内容读取为字符串的代码应该看起来很熟悉;我们在第 12 章中使用了它,当时我们读取清单 12-4 中 I/O 项目的文件内容。
Next, we use format!
to add the file’s contents as the body of the success
response. To ensure a valid HTTP response, we add the Content-Length
header
which is set to the size of our response body, in this case the size of
hello.html
.
接下来,我们使用format!
将文件的内容添加为成功响应的正文。为了确保有效的 HTTP 响应,我们添加Content-Length
标头,该标头设置为响应正文的大小,在本例中为hello.html
的大小。
Run this code with cargo run
and load 127.0.0.1:7878 in your browser; you
should see your HTML rendered!
使用cargo run
运行此代码并在浏览器中加载127.0.0.1:7878 ;你应该看到你的 HTML 被渲染了!
Currently, we’re ignoring the request data in http_request
and just sending
back the contents of the HTML file unconditionally. That means if you try
requesting 127.0.0.1:7878/something-else in your browser, you’ll still get
back this same HTML response. At the moment, our server is very limited and
does not do what most web servers do. We want to customize our responses
depending on the request and only send back the HTML file for a well-formed
request to /.
目前,我们忽略http_request
中的请求数据,只是无条件发回 HTML 文件的内容。这意味着如果您尝试在浏览器中请求127.0.0.1:7878/something-else ,您仍然会得到相同的 HTML 响应。目前,我们的服务器非常有限,无法完成大多数网络服务器的工作。我们希望根据请求自定义我们的响应,并且仅将格式正确的请求的 HTML 文件发送回/ 。
Validating the Request and Selectively Responding
验证请求并有选择地响应
Right now, our web server will return the HTML in the file no matter what the
client requested. Let’s add functionality to check that the browser is
requesting / before returning the HTML file and return an error if the
browser requests anything else. For this we need to modify handle_connection
,
as shown in Listing 20-6. This new code checks the content of the request
received against what we know a request for / looks like and adds if
and
else
blocks to treat requests differently.
现在,无论客户端请求什么,我们的 Web 服务器都会返回文件中的 HTML。让我们添加功能来检查浏览器是否正在请求/在返回 HTML 文件之前,如果浏览器请求其他任何内容,则返回错误。为此,我们需要修改handle_connection
,如清单20-6所示。这段新代码根据我们所知道的/请求检查收到的请求内容,并添加if
和else
以不同方式处理请求。
Filename: src/main.rs 文件名:src/main.rs
We’re only going to be looking at the first line of the HTTP request, so rather
than reading the entire request into a vector, we’re calling next
to get the
first item from the iterator. The first unwrap
takes care of the Option
and
stops the program if the iterator has no items. The second unwrap
handles the
Result
and has the same effect as the unwrap
that was in the map
added in
Listing 20-2.
我们只会查看 HTTP 请求的第一行,因此我们不会将整个请求读入向量,而是调用next
从迭代器中获取第一项。第一个unwrap
负责Option
,并在迭代器没有项目时停止程序。第二个unwrap
处理Result
,并且与清单 20-2 中添加的map
中的unwrap
具有相同的效果。
Next, we check the request_line
to see if it equals the request line of a GET
request to the / path. If it does, the if
block returns the contents of our
HTML file.
接下来,我们检查request_line
是否等于对/路径的 GET 请求的请求行。如果是, if
块将返回 HTML 文件的内容。
If the request_line
does not equal the GET request to the / path, it
means we’ve received some other request. We’ll add code to the else
block in
a moment to respond to all other requests.
如果request_line
不等于/路径的 GET 请求,则意味着我们收到了其他请求。我们稍后将向else
块添加代码以响应所有其他请求。
Run this code now and request 127.0.0.1:7878; you should get the HTML in
hello.html. If you make any other request, such as
127.0.0.1:7878/something-else, you’ll get a connection error like those you
saw when running the code in Listing 20-1 and Listing 20-2.
现在运行此代码并请求127.0.0.1:7878 ;您应该在hello.html中获取 HTML。如果您发出任何其他请求,例如127.0.0.1:7878/something-else ,您将收到连接错误,如运行清单 20-1 和清单 20-2 中的代码时看到的那样。
Now let’s add the code in Listing 20-7 to the else
block to return a response
with the status code 404, which signals that the content for the request was
not found. We’ll also return some HTML for a page to render in the browser
indicating the response to the end user.
现在,我们将清单 20-7 中的代码添加到else
块中,以返回状态代码为 404 的响应,这表示未找到请求的内容。我们还将返回一些 HTML 以便在浏览器中呈现页面,指示对最终用户的响应。
Filename: src/main.rs 文件名:src/main.rs
Here, our response has a status line with status code 404 and the reason phrase
NOT FOUND
. The body of the response will be the HTML in the file 404.html.
You’ll need to create a 404.html file next to hello.html for the error
page; again feel free to use any HTML you want or use the example HTML in
Listing 20-8.
在这里,我们的响应有一个状态行,状态代码为 404 和原因短语NOT FOUND
。响应的正文将是文件404.html中的 HTML。您需要在错误页面的hello.html旁边创建一个404.html文件;再次,您可以随意使用任何您想要的 HTML 或使用清单 20-8 中的示例 HTML。
Filename: 404.html 文件名:404.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello!</title>
</head>
<body>
<h1>Oops!</h1>
<p>Sorry, I don't know what you're asking for.</p>
</body>
</html>
With these changes, run your server again. Requesting 127.0.0.1:7878 should
return the contents of hello.html, and any other request, like
127.0.0.1:7878/foo, should return the error HTML from 404.html.
完成这些更改后,再次运行您的服务器。请求127.0.0.1:7878应返回hello.html的内容,而任何其他请求(例如127.0.0.1:7878/foo )应返回404.html中的错误 HTML。
A Touch of Refactoring 一点重构
At the moment the if
and else
blocks have a lot of repetition: they’re both
reading files and writing the contents of the files to the stream. The only
differences are the status line and the filename. Let’s make the code more
concise by pulling out those differences into separate if
and else
lines
that will assign the values of the status line and the filename to variables;
we can then use those variables unconditionally in the code to read the file
and write the response. Listing 20-9 shows the resulting code after replacing
the large if
and else
blocks.
目前, if
和else
块有很多重复:它们都在读取文件并将文件内容写入流。唯一的区别是状态行和文件名。让我们通过将这些差异提取到单独的if
和else
行中来使代码更加简洁,这些行将状态行和文件名的值分配给变量;然后我们可以在代码中无条件地使用这些变量来读取文件并写入响应。清单 20-9 显示了替换大的if
和else
块后的结果代码。
Filename: src/main.rs 文件名:src/main.rs
Now the if
and else
blocks only return the appropriate values for the
status line and filename in a tuple; we then use destructuring to assign these
two values to status_line
and filename
using a pattern in the let
statement, as discussed in Chapter 18.
现在, if
和else
块仅返回元组中状态行和文件名的适当值;然后,我们使用let
语句中的模式,使用解构将这两个值分配给status_line
和filename
,如第 18 章所述。
The previously duplicated code is now outside the if
and else
blocks and
uses the status_line
and filename
variables. This makes it easier to see
the difference between the two cases, and it means we have only one place to
update the code if we want to change how the file reading and response writing
work. The behavior of the code in Listing 20-9 will be the same as that in
Listing 20-7.
之前复制的代码现在位于if
和else
块之外,并使用status_line
和filename
变量。这使得更容易看出两种情况之间的差异,这意味着如果我们想要更改文件读取和响应写入的工作方式,我们只有一个地方可以更新代码。清单 20-9 中的代码行为与清单 20-7 中的代码相同。
Awesome! We now have a simple web server in approximately 40 lines of Rust code
that responds to one request with a page of content and responds to all other
requests with a 404 response.
惊人的!我们现在有一个简单的 Web 服务器,大约有 40 行 Rust 代码,它用一页内容响应一个请求,并用 404 响应响应所有其他请求。
Currently, our server runs in a single thread, meaning it can only serve one
request at a time. Let’s examine how that can be a problem by simulating some
slow requests. Then we’ll fix it so our server can handle multiple requests at
once.
目前,我们的服务器在单线程中运行,这意味着它一次只能服务一个请求。让我们通过模拟一些缓慢的请求来检查这可能是一个问题。然后我们将修复它,以便我们的服务器可以同时处理多个请求。
Turning Our Single-Threaded Server into a Multithreaded Server
将我们的单线程服务器变成多线程服务器
Right now, the server will process each request in turn, meaning it won’t
process a second connection until the first is finished processing. If the
server received more and more requests, this serial execution would be less and
less optimal. If the server receives a request that takes a long time to
process, subsequent requests will have to wait until the long request is
finished, even if the new requests can be processed quickly. We’ll need to fix
this, but first, we’ll look at the problem in action.
现在,服务器将依次处理每个请求,这意味着在第一个连接处理完成之前它不会处理第二个连接。如果服务器收到越来越多的请求,这种串行执行将越来越不理想。如果服务器收到一个需要很长时间处理的请求,即使新的请求可以很快处理,后续的请求也必须等到这个长请求完成。我们需要解决这个问题,但首先,我们将看看实际问题。
Simulating a Slow Request in the Current Server Implementation
在当前服务器实现中模拟慢速请求
We’ll look at how a slow-processing request can affect other requests made to
our current server implementation. Listing 20-10 implements handling a request
to /sleep with a simulated slow response that will cause the server to sleep
for 5 seconds before responding.
我们将了解处理缓慢的请求如何影响对当前服务器实现发出的其他请求。清单 20-10 实现了通过模拟慢速响应来处理对/sleep的请求,这将导致服务器在响应之前休眠 5 秒。
Filename: src/main.rs 文件名:src/main.rs
We switched from if
to match
now that we have three cases. We need to
explicitly match on a slice of request_line
to pattern match against the
string literal values; match
doesn’t do automatic referencing and
dereferencing like the equality method does.
现在我们有三种情况,我们从if
切换到match
。我们需要显式匹配request_line
的一部分,以针对字符串文字值进行模式匹配; match
不像 equals 方法那样进行自动引用和取消引用。
The first arm is the same as the if
block from Listing 20-9. The second arm
matches a request to /sleep. When that request is received, the server will
sleep for 5 seconds before rendering the successful HTML page. The third arm is
the same as the else
block from Listing 20-9.
第一个臂与清单 20-9 中的if
块相同。第二个分支匹配对/sleep 的请求。收到该请求后,服务器将休眠 5 秒,然后再渲染成功的 HTML 页面。第三个分支与清单 20-9 中的else
块相同。
You can see how primitive our server is: real libraries would handle the
recognition of multiple requests in a much less verbose way!
您可以看到我们的服务器是多么原始:真正的库将以更简洁的方式处理多个请求的识别!
Start the server using cargo run
. Then open two browser windows: one for
http://127.0.0.1:7878/ and the other for http://127.0.0.1:7878/sleep. If
you enter the / URI a few times, as before, you’ll see it respond quickly.
But if you enter /sleep and then load /, you’ll see that / waits until
sleep
has slept for its full 5 seconds before loading.
使用cargo run
启动服务器。然后打开两个浏览器窗口:一个用于http://127.0.0.1:7878/ ,另一个用于http://127.0.0.1:7878/sleep 。如果像以前一样输入/ URI 几次,您会看到它快速响应。但是如果你输入/sleep然后加载/ ,你会看到/会等到sleep
睡足 5 秒才加载。
There are multiple techniques we could use to avoid requests backing up behind
a slow request; the one we’ll implement is a thread pool.
我们可以使用多种技术来避免请求在缓慢的请求后面备份;我们要实现的是线程池。
Improving Throughput with a Thread Pool
使用线程池提高吞吐量
A thread pool is a group of spawned threads that are waiting and ready to
handle a task. When the program receives a new task, it assigns one of the
threads in the pool to the task, and that thread will process the task. The
remaining threads in the pool are available to handle any other tasks that come
in while the first thread is processing. When the first thread is done
processing its task, it’s returned to the pool of idle threads, ready to handle
a new task. A thread pool allows you to process connections concurrently,
increasing the throughput of your server.
线程池是一组正在等待并准备好处理任务的派生线程。当程序接收到一个新任务时,它会将池中的线程之一分配给该任务,并且该线程将处理该任务。池中的剩余线程可用于处理第一个线程正在处理时进入的任何其他任务。当第一个线程处理完其任务后,它会返回到空闲线程池,准备处理新任务。线程池允许您同时处理连接,从而提高服务器的吞吐量。
We’ll limit the number of threads in the pool to a small number to protect us
from Denial of Service (DoS) attacks; if we had our program create a new thread
for each request as it came in, someone making 10 million requests to our
server could create havoc by using up all our server’s resources and grinding
the processing of requests to a halt.
我们将池中的线程数量限制为少量,以保护我们免受拒绝服务 (DoS) 攻击;如果我们让程序为每个传入的请求创建一个新线程,那么有人向我们的服务器发出 1000 万个请求,可能会耗尽我们所有服务器的资源并使请求处理停止,从而造成严重破坏。
Rather than spawning unlimited threads, then, we’ll have a fixed number of
threads waiting in the pool. Requests that come in are sent to the pool for
processing. The pool will maintain a queue of incoming requests. Each of the
threads in the pool will pop off a request from this queue, handle the request,
and then ask the queue for another request. With this design, we can process up
to N
requests concurrently, where N
is the number of threads. If each
thread is responding to a long-running request, subsequent requests can still
back up in the queue, but we’ve increased the number of long-running requests
we can handle before reaching that point.
那么,我们将有固定数量的线程在池中等待,而不是产生无限的线程。传入的请求将发送到池中进行处理。该池将维护传入请求的队列。池中的每个线程都会从该队列中弹出一个请求,处理该请求,然后向队列询问另一个请求。通过这种设计,我们最多可以同时处理N
请求,其中N
是线程数。如果每个线程都响应长时间运行的请求,则后续请求仍然可以在队列中备份,但我们增加了在到达该点之前可以处理的长时间运行请求的数量。
This technique is just one of many ways to improve the throughput of a web
server. Other options you might explore are the fork/join model, the
single-threaded async I/O model, or the multi-threaded async I/O model. If
you’re interested in this topic, you can read more about other solutions and
try to implement them; with a low-level language like Rust, all of these
options are possible.
该技术只是提高 Web 服务器吞吐量的众多方法之一。您可能会探索的其他选项包括fork/join 模型、单线程异步 I/O 模型或多线程异步 I/O 模型。如果您对此主题感兴趣,可以阅读有关其他解决方案的更多信息并尝试实现它们;使用 Rust 这样的低级语言,所有这些选项都是可能的。
Before we begin implementing a thread pool, let’s talk about what using the
pool should look like. When you’re trying to design code, writing the client
interface first can help guide your design. Write the API of the code so it’s
structured in the way you want to call it; then implement the functionality
within that structure rather than implementing the functionality and then
designing the public API.
在开始实现线程池之前,我们先讨论一下线程池的使用方式。当您尝试设计代码时,首先编写客户端界面可以帮助指导您的设计。编写代码的 API,使其按照您想要的调用方式构建;然后在该结构中实现功能,而不是实现功能然后设计公共 API。
Similar to how we used test-driven development in the project in Chapter 12,
we’ll use compiler-driven development here. We’ll write the code that calls the
functions we want, and then we’ll look at errors from the compiler to determine
what we should change next to get the code to work. Before we do that, however,
we’ll explore the technique we’re not going to use as a starting point.
与我们在第 12 章的项目中使用测试驱动开发的方式类似,我们在这里将使用编译器驱动开发。我们将编写调用所需函数的代码,然后查看编译器中的错误,以确定下一步应该更改哪些内容以使代码正常工作。然而,在此之前,我们将探索我们不打算用作起点的技术。
Spawning a Thread for Each Request
为每个请求生成一个线程
First, let’s explore how our code might look if it did create a new thread for
every connection. As mentioned earlier, this isn’t our final plan due to the
problems with potentially spawning an unlimited number of threads, but it is a
starting point to get a working multithreaded server first. Then we’ll add the
thread pool as an improvement, and contrasting the two solutions will be
easier. Listing 20-11 shows the changes to make to main
to spawn a new thread
to handle each stream within the for
loop.
首先,让我们探讨一下如果我们的代码为每个连接创建一个新线程,它会是什么样子。如前所述,这不是我们的最终计划,因为可能会产生无限数量的线程,但它是首先获得工作多线程服务器的起点。然后我们将添加线程池作为改进,对比这两种解决方案会更容易。清单 20-11 显示了对main
进行的更改,以生成一个新线程来处理for
循环中的每个流。
Filename: src/main.rs 文件名:src/main.rs
As you learned in Chapter 16, thread::spawn
will create a new thread and then
run the code in the closure in the new thread. If you run this code and load
/sleep in your browser, then / in two more browser tabs, you’ll indeed see
that the requests to / don’t have to wait for /sleep to finish. However, as
we mentioned, this will eventually overwhelm the system because you’d be making
new threads without any limit.
正如您在第 16 章中了解到的, thread::spawn
将创建一个新线程,然后在新线程中运行闭包中的代码。如果您运行此代码并在浏览器中加载/sleep ,然后在另外两个浏览器选项卡中加载/ ,您确实会看到对/ 的请求不必等待/sleep完成。然而,正如我们所提到的,这最终将使系统不堪重负,因为您将无限制地创建新线程。
Creating a Finite Number of Threads
创建有限数量的线程
We want our thread pool to work in a similar, familiar way so switching from
threads to a thread pool doesn’t require large changes to the code that uses
our API. Listing 20-12 shows the hypothetical interface for a ThreadPool
struct we want to use instead of thread::spawn
.
我们希望线程池以类似、熟悉的方式工作,因此从线程切换到线程池不需要对使用 API 的代码进行大量更改。清单 20-12 显示了我们想要使用的ThreadPool
结构的假设接口,而不是thread::spawn
。
Filename: src/main.rs 文件名:src/main.rs
We use ThreadPool::new
to create a new thread pool with a configurable number
of threads, in this case four. Then, in the for
loop, pool.execute
has a
similar interface as thread::spawn
in that it takes a closure the pool should
run for each stream. We need to implement pool.execute
so it takes the
closure and gives it to a thread in the pool to run. This code won’t yet
compile, but we’ll try so the compiler can guide us in how to fix it.
我们使用ThreadPool::new
创建一个具有可配置线程数量的新线程池,在本例中为四个。然后,在for
循环中, pool.execute
具有与thread::spawn
类似的接口,因为它需要一个池应该为每个流运行的闭包。我们需要实现pool.execute
以便它获取闭包并将其交给池中的线程来运行。此代码尚未编译,但我们将尝试以便编译器可以指导我们如何修复它。
Building ThreadPool
Using Compiler Driven Development
使用编译器驱动开发构建ThreadPool
Make the changes in Listing 20-12 to src/main.rs, and then let’s use the
compiler errors from cargo check
to drive our development. Here is the first
error we get:
将清单 20-12 中的更改更改为src/main.rs ,然后让我们使用cargo check
中的编译器错误来驱动我们的开发。这是我们得到的第一个错误:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0433]: failed to resolve: use of undeclared type `ThreadPool`
--> 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
Great! This error tells us we need a ThreadPool
type or module, so we’ll
build one now. Our ThreadPool
implementation will be independent of the kind
of work our web server is doing. So, let’s switch the hello
crate from a
binary crate to a library crate to hold our ThreadPool
implementation. After
we change to a library crate, we could also use the separate thread pool
library for any work we want to do using a thread pool, not just for serving
web requests.
伟大的!这个错误告诉我们我们需要一个ThreadPool
类型或模块,所以我们现在就构建一个。我们的ThreadPool
实现将独立于我们的 Web 服务器正在执行的工作类型。因此,让我们将hello
crate 从二进制 crate 切换为库 crate 以保存我们的ThreadPool
实现。更改为库箱后,我们还可以使用单独的线程池库来完成我们想要使用线程池完成的任何工作,而不仅仅是用于服务 Web 请求。
Create a src/lib.rs that contains the following, which is the simplest
definition of a ThreadPool
struct that we can have for now:
创建一个包含以下内容的src/lib.rs ,这是我们目前可以拥有的ThreadPool
结构体的最简单定义:
Filename: src/lib.rs 文件名:src/lib.rs
pub struct ThreadPool;
Then edit main.rs file to bring ThreadPool
into scope from the library
crate by adding the following code to the top of src/main.rs:
然后编辑main.rs文件,通过将以下代码添加到src/main.rs的顶部,将ThreadPool
从库箱引入范围:
Filename: src/main.rs 文件名:src/main.rs
This code still won’t work, but let’s check it again to get the next error that
we need to address:
这段代码仍然无法工作,但让我们再次检查一下以获得我们需要解决的下一个错误:
$ 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
--> 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
This error indicates that next we need to create an associated function named
new
for ThreadPool
. We also know that new
needs to have one parameter
that can accept 4
as an argument and should return a ThreadPool
instance.
Let’s implement the simplest new
function that will have those
characteristics:
此错误表明接下来我们需要为ThreadPool
创建一个名为new
关联函数。我们还知道new
需要有一个参数,该参数可以接受4
作为参数,并且应该返回一个ThreadPool
实例。让我们实现具有这些特征的最简单的new
函数:
Filename: src/lib.rs 文件名:src/lib.rs
pub struct ThreadPool;
impl ThreadPool {
pub fn new(size: usize) -> ThreadPool {
ThreadPool
}
}
We chose usize
as the type of the size
parameter, because we know that a
negative number of threads doesn’t make any sense. We also know we’ll use this
4 as the number of elements in a collection of threads, which is what the
usize
type is for, as discussed in the “Integer Types” section of Chapter 3.
我们选择usize
作为size
参数的类型,因为我们知道负数的线程没有任何意义。我们还知道我们将使用这个 4 作为线程集合中的元素数量,这就是usize
类型的用途,如第 3 章的“整数类型”忽略部分中所述。
Let’s check the code again:
我们再检查一下代码:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no method named `execute` found for struct `ThreadPool` in the current scope
--> 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
Now the error occurs because we don’t have an execute
method on ThreadPool
.
Recall from the “Creating a Finite Number of
Threads” section that we
decided our thread pool should have an interface similar to thread::spawn
. In
addition, we’ll implement the execute
function so it takes the closure it’s
given and gives it to an idle thread in the pool to run.
现在发生错误是因为我们在ThreadPool
上没有execute
方法。回想一下“创建有限数量的线程”忽略部分,我们决定线程池应该有一个类似于thread::spawn
接口。此外,我们将实现execute
函数,以便它获取给定的闭包并将其提供给池中的空闲线程来运行。
We’ll define the execute
method on ThreadPool
to take a closure as a
parameter. Recall from the “Moving Captured Values Out of the Closure and the
Fn
Traits” section in Chapter 13 that we can take
closures as parameters with three different traits: Fn
, FnMut
, and
FnOnce
. We need to decide which kind of closure to use here. We know we’ll
end up doing something similar to the standard library thread::spawn
implementation, so we can look at what bounds the signature of thread::spawn
has on its parameter. The documentation shows us the following:
我们将在ThreadPool
上定义execute
方法以将闭包作为参数。回想一下第 13 章中的“将捕获的值移出闭包和Fn
特征”忽略部分,我们可以将闭包作为具有三个不同特征的参数: Fn
、 FnMut
和FnOnce
。我们需要决定在这里使用哪种闭包。我们知道我们最终会做一些类似于标准库thread::spawn
实现的事情,所以我们可以看看thread::spawn
签名对其参数的限制。该文档向我们展示了以下内容:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
The F
type parameter is the one we’re concerned with here; the T
type
parameter is related to the return value, and we’re not concerned with that. We
can see that spawn
uses FnOnce
as the trait bound on F
. This is probably
what we want as well, because we’ll eventually pass the argument we get in
execute
to spawn
. We can be further confident that FnOnce
is the trait we
want to use because the thread for running a request will only execute that
request’s closure one time, which matches the Once
in FnOnce
.F
类型参数是我们这里关心的; T
类型参数与返回值有关,我们不关心这个。我们可以看到, spawn
使用FnOnce
作为F
上的特征绑定。这可能也是我们想要的,因为我们最终会将在execute
中获得的参数传递给spawn
。我们可以进一步确信FnOnce
是我们想要使用的特征,因为运行请求的线程只会执行该请求的闭包一次,这与FnOnce
中的Once
匹配。
The F
type parameter also has the trait bound Send
and the lifetime bound
'static
, which are useful in our situation: we need Send
to transfer the
closure from one thread to another and 'static
because we don’t know how long
the thread will take to execute. Let’s create an execute
method on
ThreadPool
that will take a generic parameter of type F
with these bounds:F
类型参数还具有特征绑定Send
和生命周期绑定'static
,这在我们的情况下很有用:我们需要Send
将闭包从一个线程传输到另一个线程,并且'static
因为我们不知道线程将持续多长时间采取执行。让我们在ThreadPool
上创建一个execute
方法,该方法将采用具有以下边界的F
类型泛型参数:
Filename: src/lib.rs 文件名:src/lib.rs
We still use the ()
after FnOnce
because this FnOnce
represents a closure
that takes no parameters and returns the unit type ()
. Just like function
definitions, the return type can be omitted from the signature, but even if we
have no parameters, we still need the parentheses.
我们仍然在FnOnce
之后使用()
因为这个FnOnce
表示一个不带参数并返回单位类型()
的闭包。就像函数定义一样,签名中可以省略返回类型,但即使我们没有参数,我们仍然需要括号。
Again, this is the simplest implementation of the execute
method: it does
nothing, but we’re trying only to make our code compile. Let’s check it again:
同样,这是execute
方法最简单的实现:它什么也不做,但我们只是尝试让我们的代码编译。我们再检查一下:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.24s
It compiles! But note that if you try cargo run
and make a request in the
browser, you’ll see the errors in the browser that we saw at the beginning of
the chapter. Our library isn’t actually calling the closure passed to execute
yet!
它编译了!但请注意,如果您尝试cargo run
并在浏览器中发出请求,您将在浏览器中看到我们在本章开头看到的错误。我们的库实际上还没有调用传递来execute
闭包!
Note: A saying you might hear about languages with strict compilers, such as
Haskell and Rust, is “if the code compiles, it works.” But this saying is not
universally true. Our project compiles, but it does absolutely nothing! If we
were building a real, complete project, this would be a good time to start
writing unit tests to check that the code compiles and has the behavior we
want.
注意:您可能听说过关于具有严格编译器的语言(例如 Haskell 和 Rust)的一句话是“如果代码可以编译,它就可以工作”。但这句话并不普遍正确。我们的项目可以编译,但它什么也没做!如果我们正在构建一个真正的、完整的项目,那么这将是开始编写单元测试以检查代码是否编译并具有我们想要的行为的好时机。
Validating the Number of Threads in new
验证new
中的线程数
We aren’t doing anything with the parameters to new
and execute
. Let’s
implement the bodies of these functions with the behavior we want. To start,
let’s think about new
. Earlier we chose an unsigned type for the size
parameter, because a pool with a negative number of threads makes no sense.
However, a pool with zero threads also makes no sense, yet zero is a perfectly
valid usize
. We’ll add code to check that size
is greater than zero before
we return a ThreadPool
instance and have the program panic if it receives a
zero by using the assert!
macro, as shown in Listing 20-13.
我们没有对new
和execute
参数做任何事情。让我们用我们想要的行为来实现这些函数的主体。首先,让我们考虑一下new
.之前我们为size
参数选择了无符号类型,因为线程数为负数的池没有意义。然而,具有零线程的池也没有意义,但零是完全有效的usize
。在返回ThreadPool
实例之前,我们将添加代码来检查size
是否大于零,并且如果使用assert!
宏,如清单20-13所示。
Filename: src/lib.rs 文件名:src/lib.rs
We’ve also added some documentation for our ThreadPool
with doc comments.
Note that we followed good documentation practices by adding a section that
calls out the situations in which our function can panic, as discussed in
Chapter 14. Try running cargo doc --open
and clicking the ThreadPool
struct
to see what the generated docs for new
look like!
我们还为我们的ThreadPool
添加了一些带有文档注释的文档。请注意,我们遵循了良好的文档实践,添加了一个部分来指出我们的函数可能会出现恐慌的情况,如第 14 章中所讨论的。尝试运行cargo doc --open
并单击ThreadPool
结构以查看生成的文档的new
外观喜欢!
Instead of adding the assert!
macro as we’ve done here, we could change new
into build
and return a Result
like we did with Config::build
in the I/O
project in Listing 12-9. But we’ve decided in this case that trying to create a
thread pool without any threads should be an unrecoverable error. If you’re
feeling ambitious, try to write a function named build
with the following
signature to compare with the new
function:
而不是添加assert!
正如我们在这里所做的那样,我们可以将new
更改为build
并返回一个Result
,就像我们在清单 12-9 中的 I/O 项目中使用Config::build
所做的那样。但在这种情况下,我们决定尝试创建一个没有任何线程的线程池应该是一个不可恢复的错误。如果您雄心勃勃,请尝试编写一个名为build
函数,并使用以下签名来与new
函数进行比较:
pub fn build(size: usize) -> Result<ThreadPool, PoolCreationError> {
Creating Space to Store the Threads
创建空间来存储线程
Now that we have a way to know we have a valid number of threads to store in
the pool, we can create those threads and store them in the ThreadPool
struct
before returning the struct. But how do we “store” a thread? Let’s take another
look at the thread::spawn
signature:
现在我们有办法知道我们有有效数量的线程存储在池中,我们可以创建这些线程并将它们存储在ThreadPool
结构中,然后返回该结构。但是我们如何“存储”线程呢?让我们再看一下thread::spawn
签名:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
The spawn
function returns a JoinHandle<T>
, where T
is the type that the
closure returns. Let’s try using JoinHandle
too and see what happens. In our
case, the closures we’re passing to the thread pool will handle the connection
and not return anything, so T
will be the unit type ()
.spawn
函数返回JoinHandle<T>
,其中T
是闭包返回的类型。我们也尝试使用JoinHandle
看看会发生什么。在我们的例子中,我们传递给线程池的闭包将处理连接并且不返回任何内容,因此T
将是单元类型()
。
The code in Listing 20-14 will compile but doesn’t create any threads yet.
We’ve changed the definition of ThreadPool
to hold a vector of
thread::JoinHandle<()>
instances, initialized the vector with a capacity of
size
, set up a for
loop that will run some code to create the threads, and
returned a ThreadPool
instance containing them.
清单 20-14 中的代码将编译,但尚未创建任何线程。我们更改了ThreadPool
的定义以保存thread::JoinHandle<()>
实例的向量,用size
的容量初始化该向量,设置一个for
循环来运行一些代码来创建线程,并且返回包含它们的ThreadPool
实例。
Filename: src/lib.rs 文件名:src/lib.rs
We’ve brought std::thread
into scope in the library crate, because we’re
using thread::JoinHandle
as the type of the items in the vector in
ThreadPool
.
我们已将std::thread
纳入库箱的范围内,因为我们使用thread::JoinHandle
作为ThreadPool
中向量中项目的类型。
Once a valid size is received, our ThreadPool
creates a new vector that can
hold size
items. The with_capacity
function performs the same task as
Vec::new
but with an important difference: it preallocates space in the
vector. Because we know we need to store size
elements in the vector, doing
this allocation up front is slightly more efficient than using Vec::new
,
which resizes itself as elements are inserted.
一旦收到有效的大小,我们的ThreadPool
就会创建一个可以容纳size
项的新向量。 with_capacity
函数执行与Vec::new
相同的任务,但有一个重要的区别:它在向量中预先分配空间。因为我们知道需要在向量中存储size
元素,所以预先进行此分配比使用Vec::new
稍微更有效,后者会在插入元素时调整自身大小。
When you run cargo check
again, it should succeed.
当您再次运行cargo check
时,它应该会成功。
A Worker
Struct Responsible for Sending Code from the ThreadPool
to a Thread
负责将代码从ThreadPool
发送到线程的Worker
结构
We left a comment in the for
loop in Listing 20-14 regarding the creation of
threads. Here, we’ll look at how we actually create threads. The standard
library provides thread::spawn
as a way to create threads, and
thread::spawn
expects to get some code the thread should run as soon as the
thread is created. However, in our case, we want to create the threads and have
them wait for code that we’ll send later. The standard library’s
implementation of threads doesn’t include any way to do that; we have to
implement it manually.
我们在清单 20-14 的for
循环中留下了关于线程创建的注释。在这里,我们将看看如何实际创建线程。标准库提供了thread::spawn
作为创建线程的方式,并且thread::spawn
期望在创建线程后立即获取线程应该运行的一些代码。然而,在我们的例子中,我们想要创建线程并让它们等待我们稍后发送的代码。标准库的线程实现不包含任何方法来做到这一点;我们必须手动实现它。
We’ll implement this behavior by introducing a new data structure between the
ThreadPool
and the threads that will manage this new behavior. We’ll call
this data structure Worker, which is a common term in pooling
implementations. The Worker picks up code that needs to be run and runs the
code in the Worker’s thread. Think of people working in the kitchen at a
restaurant: the workers wait until orders come in from customers, and then
they’re responsible for taking those orders and fulfilling them.
我们将通过在ThreadPool
和管理此新行为的线程之间引入新的数据结构来实现此行为。我们将这种数据结构称为Worker ,这是池实现中的常用术语。 Worker拾取需要运行的代码并在Worker的线程中运行代码。想象一下在餐厅厨房工作的人:工人们等待顾客下单,然后负责接受并履行这些订单。
Instead of storing a vector of JoinHandle<()>
instances in the thread pool,
we’ll store instances of the Worker
struct. Each Worker
will store a single
JoinHandle<()>
instance. Then we’ll implement a method on Worker
that will
take a closure of code to run and send it to the already running thread for
execution. We’ll also give each worker an id
so we can distinguish between
the different workers in the pool when logging or debugging.
我们将存储Worker
结构的实例,而不是在线程池中存储JoinHandle<()>
实例的向量。每个Worker
将存储一个JoinHandle<()>
实例。然后我们将在Worker
上实现一个方法,该方法将获取要运行的代码闭包并将其发送到已经运行的线程来执行。我们还将为每个工作人员提供一个id
,以便我们在记录或调试时可以区分池中的不同工作人员。
Here is the new process that will happen when we create a ThreadPool
. We’ll
implement the code that sends the closure to the thread after we have Worker
set up in this way:
这是当我们创建ThreadPool
时将发生的新进程。在以这种方式设置Worker
后,我们将实现将闭包发送到线程的代码:
- Define a
Worker
struct that holds anid
and aJoinHandle<()>
.
定义一个Worker
结构体,其中包含id
和JoinHandle<()>
。 - Change
ThreadPool
to hold a vector ofWorker
instances.
更改ThreadPool
以保存Worker
实例的向量。 - Define a
Worker::new
function that takes anid
number and returns aWorker
instance that holds theid
and a thread spawned with an empty closure.
定义一个Worker::new
函数,它接受一个id
号并返回一个Worker
实例,该实例保存该id
和一个用空闭包生成的线程。 - In
ThreadPool::new
, use thefor
loop counter to generate anid
, create a newWorker
with thatid
, and store the worker in the vector.
在ThreadPool::new
中,使用for
循环计数器生成id
,使用该id
创建一个新的Worker
,并将该 Worker 存储在向量中。
If you’re up for a challenge, try implementing these changes on your own before
looking at the code in Listing 20-15.
如果您准备迎接挑战,请在查看清单 20-15 中的代码之前尝试自己实现这些更改。
Ready? Here is Listing 20-15 with one way to make the preceding modifications.
准备好?清单 20-15 提供了进行上述修改的一种方法。
Filename: src/lib.rs 文件名:src/lib.rs
We’ve changed the name of the field on ThreadPool
from threads
to workers
because it’s now holding Worker
instances instead of JoinHandle<()>
instances. We use the counter in the for
loop as an argument to
Worker::new
, and we store each new Worker
in the vector named workers
.
我们已将ThreadPool
上的字段名称从threads
更改为workers
,因为它现在保存的是Worker
实例,而不是JoinHandle<()>
实例。我们使用for
循环中的计数器作为Worker::new
参数,并将每个新Worker
存储在名为workers
向量中。
External code (like our server in src/main.rs) doesn’t need to know the
implementation details regarding using a Worker
struct within ThreadPool
,
so we make the Worker
struct and its new
function private. The
Worker::new
function uses the id
we give it and stores a JoinHandle<()>
instance that is created by spawning a new thread using an empty closure.
外部代码(如src/main.rs中的服务器)不需要知道有关在ThreadPool
中使用Worker
结构的实现细节,因此我们将Worker
结构及其new
函数设为私有。 Worker::new
函数使用我们给它的id
并存储一个JoinHandle<()>
实例,该实例是通过使用空闭包生成新线程而创建的。
Note: If the operating system can’t create a thread because there aren’t
enough system resources, thread::spawn
will panic. That will cause our
whole server to panic, even though the creation of some threads might
succeed. For simplicity’s sake, this behavior is fine, but in a production
thread pool implementation, you’d likely want to use
std::thread::Builder
and its
spawn
method that returns Result
instead.
注意:如果操作系统由于没有足够的系统资源而无法创建线程, thread::spawn
将会出现紧急情况。即使某些线程的创建可能成功,这也会导致整个服务器出现恐慌。为了简单起见,这种行为很好,但在生产线程池实现中,您可能希望使用std::thread::Builder
及其返回Result
的spawn
方法。
This code will compile and will store the number of Worker
instances we
specified as an argument to ThreadPool::new
. But we’re still not processing
the closure that we get in execute
. Let’s look at how to do that next.
该代码将编译并存储我们指定为ThreadPool::new
参数的Worker
实例数量。但我们仍然没有处理在execute
中得到的闭包。接下来让我们看看如何做到这一点。
Sending Requests to Threads via Channels
通过通道向线程发送请求
The next problem we’ll tackle is that the closures given to thread::spawn
do
absolutely nothing. Currently, we get the closure we want to execute in the
execute
method. But we need to give thread::spawn
a closure to run when we
create each Worker
during the creation of the ThreadPool
.
我们要解决的下一个问题是给thread::spawn
闭包绝对不做任何事情。目前,我们在execute
方法中得到了想要执行的闭包。但是,当我们在创建ThreadPool
期间创建每个Worker
时,我们需要为thread::spawn
一个要运行的闭包。
We want the Worker
structs that we just created to fetch the code to run from
a queue held in the ThreadPool
and send that code to its thread to run.
我们希望刚刚创建的Worker
结构从ThreadPool
中保存的队列中获取要运行的代码,并将该代码发送到其线程来运行。
The channels we learned about in Chapter 16—a simple way to communicate between
two threads—would be perfect for this use case. We’ll use a channel to function
as the queue of jobs, and execute
will send a job from the ThreadPool
to
the Worker
instances, which will send the job to its thread. Here is the plan:
我们在第 16 章中了解到的通道(一种在两个线程之间进行通信的简单方法)非常适合此用例。我们将使用通道作为作业队列,并execute
将作业从ThreadPool
发送到Worker
实例,Worker 实例将作业发送到其线程。这是计划:
- The
ThreadPool
will create a channel and hold on to the sender.ThreadPool
将创建一个通道并保留发送者。 - Each
Worker
will hold on to the receiver.
每个Worker
都会握住接收器。 - We’ll create a new
Job
struct that will hold the closures we want to send down the channel.
我们将创建一个新的Job
结构,它将保存我们想要沿着通道发送的闭包。 - The
execute
method will send the job it wants to execute through the sender.execute
方法将通过发送者发送它想要执行的作业。 - In its thread, the
Worker
will loop over its receiver and execute the closures of any jobs it receives.
在其线程中,Worker
将循环其接收器并执行其接收到的任何作业的关闭。
Let’s start by creating a channel in ThreadPool::new
and holding the sender
in the ThreadPool
instance, as shown in Listing 20-16. The Job
struct
doesn’t hold anything for now but will be the type of item we’re sending down
the channel.
首先,我们在ThreadPool::new
中创建一个通道,并将发送者保存在ThreadPool
实例中,如清单 20-16 所示。 Job
结构目前不包含任何内容,但将是我们沿着通道发送的项目类型。
Filename: src/lib.rs 文件名:src/lib.rs
In ThreadPool::new
, we create our new channel and have the pool hold the
sender. This will successfully compile.
在ThreadPool::new
中,我们创建新通道并让池保存发送者。这样就可以编译成功了。
Let’s try passing a receiver of the channel into each worker as the thread pool
creates the channel. We know we want to use the receiver in the thread that the
workers spawn, so we’ll reference the receiver
parameter in the closure. The
code in Listing 20-17 won’t quite compile yet.
让我们尝试在线程池创建通道时将通道的接收器传递给每个工作线程。我们知道我们想要在工作线程生成的线程中使用接收器,因此我们将在闭包中引用receiver
参数。清单 20-17 中的代码还不能完全编译。
Filename: src/lib.rs 文件名:src/lib.rs
We’ve made some small and straightforward changes: we pass the receiver into
Worker::new
, and then we use it inside the closure.
我们做了一些小而直接的更改:我们将接收器传递给Worker::new
,然后在闭包中使用它。
When we try to check this code, we get this error:
当我们尝试检查此代码时,我们收到此错误:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0382]: use of moved value: `receiver`
--> src/lib.rs:26:42
|
21 | let (sender, receiver) = mpsc::channel();
| -------- move occurs because `receiver` has type `std::sync::mpsc::Receiver<Job>`, 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
--> src/lib.rs:47:33
|
47 | fn new(id: usize, receiver: mpsc::Receiver<Job>) -> Worker {
| --- in this method ^^^^^^^^^^^^^^^^^^^ this parameter takes ownership of the value
For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` (lib) due to 1 previous error
The code is trying to pass receiver
to multiple Worker
instances. This
won’t work, as you’ll recall from Chapter 16: the channel implementation that
Rust provides is multiple producer, single consumer. This means we can’t
just clone the consuming end of the channel to fix this code. We also don’t
want to send a message multiple times to multiple consumers; we want one list
of messages with multiple workers such that each message gets processed once.
该代码尝试将receiver
传递给多个Worker
实例。这是行不通的,你会记得第 16 章:Rust 提供的通道实现是多个生产者、单个消费者。这意味着我们不能仅仅克隆通道的消费端来修复此代码。我们也不希望向多个消费者多次发送消息;我们想要一个包含多个工作人员的消息列表,以便每条消息都被处理一次。
Additionally, taking a job off the channel queue involves mutating the
receiver
, so the threads need a safe way to share and modify receiver
;
otherwise, we might get race conditions (as covered in Chapter 16).
此外,从通道队列中取出作业涉及改变receiver
,因此线程需要一种安全的方法来共享和修改receiver
;否则,我们可能会遇到竞争条件(如第 16 章所述)。
Recall the thread-safe smart pointers discussed in Chapter 16: to share
ownership across multiple threads and allow the threads to mutate the value, we
need to use Arc<Mutex<T>>
. The Arc
type will let multiple workers own the
receiver, and Mutex
will ensure that only one worker gets a job from the
receiver at a time. Listing 20-18 shows the changes we need to make.
回想一下第 16 章中讨论的线程安全智能指针:为了在多个线程之间共享所有权并允许线程改变值,我们需要使用Arc<Mutex<T>>
。 Arc
类型将让多个worker拥有接收器,而Mutex
将确保一次只有一个worker从接收器获得工作。清单 20-18 显示了我们需要进行的更改。
Filename: src/lib.rs 文件名:src/lib.rs
In ThreadPool::new
, we put the receiver in an Arc
and a Mutex
. For each
new worker, we clone the Arc
to bump the reference count so the workers can
share ownership of the receiver.
在ThreadPool::new
中,我们将接收器放入Arc
和Mutex
中。对于每个新的工作人员,我们克隆Arc
以增加引用计数,以便工作人员可以共享接收器的所有权。
With these changes, the code compiles! We’re getting there!
通过这些更改,代码可以编译了!我们快到了!
Implementing the execute
Method
实现execute
方法
Let’s finally implement the execute
method on ThreadPool
. We’ll also change
Job
from a struct to a type alias for a trait object that holds the type of
closure that execute
receives. As discussed in the “Creating Type Synonyms
with Type Aliases”
section of Chapter 19, type aliases allow us to make long types shorter for
ease of use. Look at Listing 20-19.
最后让我们在ThreadPool
上实现execute
方法。我们还将Job
从结构体更改为特征对象的类型别名,该特征对象保存execute
接收的闭包类型。正如第 19 章的“使用类型别名创建类型同义词”忽略部分中所讨论的,类型别名允许我们将长类型缩短以方便使用。请看清单 20-19。
Filename: src/lib.rs 文件名:src/lib.rs
After creating a new Job
instance using the closure we get in execute
, we
send that job down the sending end of the channel. We’re calling unwrap
on
send
for the case that sending fails. This might happen if, for example, we
stop all our threads from executing, meaning the receiving end has stopped
receiving new messages. At the moment, we can’t stop our threads from
executing: our threads continue executing as long as the pool exists. The
reason we use unwrap
is that we know the failure case won’t happen, but the
compiler doesn’t know that.
使用execute
中的闭包创建新的Job
实例后,我们将该作业发送到通道的发送端。对于发送失败的情况,我们在send
调用unwrap
。例如,如果我们停止所有线程的执行,这意味着接收端已停止接收新消息,则可能会发生这种情况。目前,我们无法阻止线程执行:只要池存在,我们的线程就会继续执行。我们使用unwrap
原因是我们知道失败情况不会发生,但编译器不知道。
But we’re not quite done yet! In the worker, our closure being passed to
thread::spawn
still only references the receiving end of the channel.
Instead, we need the closure to loop forever, asking the receiving end of the
channel for a job and running the job when it gets one. Let’s make the change
shown in Listing 20-20 to Worker::new
.
但我们还没有完成!在工作线程中,传递给thread::spawn
闭包仍然只引用通道的接收端。相反,我们需要闭包永远循环,向通道的接收端请求一项作业,并在收到作业时运行该作业。让我们对Worker::new
进行如清单 20-20 所示的更改。
Filename: src/lib.rs 文件名:src/lib.rs
Here, we first call lock
on the receiver
to acquire the mutex, and then we
call unwrap
to panic on any errors. Acquiring a lock might fail if the mutex
is in a poisoned state, which can happen if some other thread panicked while
holding the lock rather than releasing the lock. In this situation, calling
unwrap
to have this thread panic is the correct action to take. Feel free to
change this unwrap
to an expect
with an error message that is meaningful to
you.
在这里,我们首先调用receiver
上的lock
来获取互斥体,然后调用unwrap
来对任何错误进行恐慌。如果互斥体处于中毒状态,则获取锁可能会失败,如果其他线程在持有锁而不是释放锁时发生恐慌,则可能会发生这种情况。在这种情况下,调用unwrap
以使该线程发生恐慌是正确的操作。请随意将此unwrap
更改为带有对您有意义的错误消息的expect
。
If we get the lock on the mutex, we call recv
to receive a Job
from the
channel. A final unwrap
moves past any errors here as well, which might occur
if the thread holding the sender has shut down, similar to how the send
method returns Err
if the receiver shuts down.
如果我们获得了互斥体的锁,我们就调用recv
从通道接收Job
。最后的unwrap
也会消除此处的所有错误,如果保存发送方的线程已关闭,则可能会发生这种情况,类似于如果接收方关闭则send
方法返回Err
的方式。
The call to recv
blocks, so if there is no job yet, the current thread will
wait until a job becomes available. The Mutex<T>
ensures that only one
Worker
thread at a time is trying to request a job.
对recv
调用会阻塞,因此如果还没有作业,当前线程将等待,直到有作业可用。 Mutex<T>
确保一次只有一个Worker
线程尝试请求作业。
Our thread pool is now in a working state! Give it a cargo run
and make some
requests:
我们的线程池现在处于工作状态!让它cargo run
并提出一些要求:
$ cargo run
Compiling hello v0.1.0 (file:///projects/hello)
warning: field is never read: `workers`
--> src/lib.rs:7:5
|
7 | workers: Vec<Worker>,
| ^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: field is never read: `id`
--> src/lib.rs:48:5
|
48 | id: usize,
| ^^^^^^^^^
warning: field is never read: `thread`
--> src/lib.rs:49:5
|
49 | thread: thread::JoinHandle<()>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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.
Success! We now have a thread pool that executes connections asynchronously.
There are never more than four threads created, so our system won’t get
overloaded if the server receives a lot of requests. If we make a request to
/sleep, the server will be able to serve other requests by having another
thread run them.
成功!我们现在有一个异步执行连接的线程池。创建的线程永远不会超过四个,因此如果服务器收到大量请求,我们的系统不会过载。如果我们向/sleep发出请求,服务器将能够通过让另一个线程运行其他请求来服务它们。
Note: If you open /sleep in multiple browser windows simultaneously, they
might load one at a time in 5 second intervals. Some web browsers execute
multiple instances of the same request sequentially for caching reasons. This
limitation is not caused by our web server.
注意:如果您同时在多个浏览器窗口中打开/sleep ,它们可能会以 5 秒的间隔一次加载一个。出于缓存原因,某些 Web 浏览器会顺序执行同一请求的多个实例。此限制不是由我们的网络服务器造成的。
After learning about the while let
loop in Chapter 18, you might be wondering
why we didn’t write the worker thread code as shown in Listing 20-21.
在了解第 18 章中的while let
循环之后,您可能想知道为什么我们没有编写如清单 20-21 所示的工作线程代码。
Filename: src/lib.rs 文件名:src/lib.rs
This code compiles and runs but doesn’t result in the desired threading
behavior: a slow request will still cause other requests to wait to be
processed. The reason is somewhat subtle: the Mutex
struct has no public
unlock
method because the ownership of the lock is based on the lifetime of
the MutexGuard<T>
within the LockResult<MutexGuard<T>>
that the lock
method returns. At compile time, the borrow checker can then enforce the rule
that a resource guarded by a Mutex
cannot be accessed unless we hold the
lock. However, this implementation can also result in the lock being held
longer than intended if we aren’t mindful of the lifetime of the
MutexGuard<T>
.
此代码编译并运行,但不会产生所需的线程行为:缓慢的请求仍会导致其他请求等待处理。原因有些微妙: Mutex
结构没有公共unlock
方法,因为锁的所有权基于lock
方法返回的 LockResult<MutexGuard<T MutexGuard<T>
LockResult<MutexGuard<T>>
的生命周期。在编译时,借用检查器可以强制执行这样的规则:除非我们持有锁,否则无法访问由Mutex
保护的资源。但是,如果我们不注意MutexGuard<T>
的生命周期,此实现也可能导致锁定的持有时间比预期的时间长。
The code in Listing 20-20 that uses let job = receiver.lock().unwrap().recv().unwrap();
works because with let
, any
temporary values used in the expression on the right hand side of the equals
sign are immediately dropped when the let
statement ends. However, while let
(and if let
and match
) does not drop temporary values until the end of
the associated block. In Listing 20-21, the lock remains held for the duration
of the call to job()
, meaning other workers cannot receive jobs.
清单 20-20 中的代码使用了let job = receiver.lock().unwrap().recv().unwrap();
之所以有效,是因为使用let
时,等号右侧表达式中使用的任何临时值都会在let
语句结束时立即删除。但是, while let
(以及if let
和match
)在关联块结束之前不会删除临时值。在清单 20-21 中,锁在调用job()
期间保持保持状态,这意味着其他工作线程无法接收作业。
Graceful Shutdown and Cleanup
正常关闭和清理
The code in Listing 20-20 is responding to requests asynchronously through the
use of a thread pool, as we intended. We get some warnings about the workers
,
id
, and thread
fields that we’re not using in a direct way that reminds us
we’re not cleaning up anything. When we use the less elegant
ctrl-c method to halt the main thread, all other threads
are stopped immediately as well, even if they’re in the middle of serving a
request.
清单 20-20 中的代码按照我们的预期通过使用线程池异步响应请求。我们收到一些关于workers
、 id
和thread
字段的警告,我们没有直接使用这些字段,提醒我们没有清理任何东西。当我们使用不太优雅的 ctrl - c 方法来停止主线程,所有其他线程也会立即停止,即使它们正在处理请求。
Next, then, we’ll implement the Drop
trait to call join
on each of the
threads in the pool so they can finish the requests they’re working on before
closing. Then we’ll implement a way to tell the threads they should stop
accepting new requests and shut down. To see this code in action, we’ll modify
our server to accept only two requests before gracefully shutting down its
thread pool.
接下来,我们将实现Drop
特征来调用池中每个线程的join
,以便它们可以在关闭之前完成正在处理的请求。然后我们将实现一种方法来告诉线程它们应该停止接受新请求并关闭。为了查看此代码的实际效果,我们将修改服务器以在正常关闭其线程池之前仅接受两个请求。
Implementing the Drop
Trait on ThreadPool
在ThreadPool
上实现Drop
Trait
Let’s start with implementing Drop
on our thread pool. When the pool is
dropped, our threads should all join to make sure they finish their work.
Listing 20-22 shows a first attempt at a Drop
implementation; this code won’t
quite work yet.
让我们从在线程池上实现Drop
开始。当池被删除时,我们的线程应该全部加入以确保它们完成工作。清单 20-22 显示了Drop
实现的第一次尝试;这段代码还不能完全工作。
Filename: src/lib.rs 文件名:src/lib.rs
First, we loop through each of the thread pool workers
. We use &mut
for
this because self
is a mutable reference, and we also need to be able to
mutate worker
. For each worker, we print a message saying that this
particular worker is shutting down, and then we call join
on that worker’s
thread. If the call to join
fails, we use unwrap
to make Rust panic and go
into an ungraceful shutdown.
首先,我们循环遍历每个线程池workers
。我们为此使用&mut
因为self
是一个可变引用,并且我们还需要能够改变worker
。对于每个工作人员,我们打印一条消息,说明该特定工作人员正在关闭,然后我们在该工作人员的线程上调用join
。如果join
调用失败,我们使用unwrap
使 Rust 恐慌并进入不正常的关闭状态。
Here is the error we get when we compile this code:
这是我们编译这段代码时得到的错误:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference
--> 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<()>`, which does not implement the `Copy` trait
|
note: `JoinHandle::<T>::join` takes ownership of the receiver `self`, which moves `worker.thread`
--> /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/std/src/thread/mod.rs:1657:17
For more information about this error, try `rustc --explain E0507`.
error: could not compile `hello` (lib) due to 1 previous error
The error tells us we can’t call join
because we only have a mutable borrow
of each worker
and join
takes ownership of its argument. To solve this
issue, we need to move the thread out of the Worker
instance that owns
thread
so join
can consume the thread. We did this in Listing 17-15: if
Worker
holds an Option<thread::JoinHandle<()>>
instead, we can call the
take
method on the Option
to move the value out of the Some
variant and
leave a None
variant in its place. In other words, a Worker
that is running
will have a Some
variant in thread
, and when we want to clean up a
Worker
, we’ll replace Some
with None
so the Worker
doesn’t have a
thread to run.
该错误告诉我们无法调用join
因为我们只有每个worker
的可变借用,并且join
拥有其参数的所有权。为了解决这个问题,我们需要将线程移出拥有thread
的Worker
实例,以便join
可以消耗该线程。我们在清单 17-15 中做到了这一点:如果Worker
持有Option<thread::JoinHandle<()>>
,我们可以调用Option
上的take
方法,将值移出Some
变量并留下一个None
变体代替它。换句话说,正在运行的Worker
在thread
中会有Some
变体,当我们想要清理Worker
时,我们会将Some
替换为None
,这样Worker
就没有线程可以运行。
So we know we want to update the definition of Worker
like this:
所以我们知道我们要像这样更新Worker
的定义:
Filename: src/lib.rs 文件名:src/lib.rs
Now let’s lean on the compiler to find the other places that need to change.
Checking this code, we get two errors:
现在让我们依靠编译器来查找其他需要更改的地方。检查这段代码,我们得到两个错误:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no method named `join` found for enum `Option` in the current scope
--> src/lib.rs:52:27
|
52 | worker.thread.join().unwrap();
| ^^^^ method not found in `Option<JoinHandle<()>>`
|
note: the method `join` exists on the type `JoinHandle<()>`
--> /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/std/src/thread/mod.rs:1657:5
help: consider using `Option::expect` to unwrap the `JoinHandle<()>` value, panicking if the value is an `Option::None`
|
52 | worker.thread.expect("REASON").join().unwrap();
| +++++++++++++++++
error[E0308]: mismatched types
--> src/lib.rs:72:22
|
72 | Worker { id, thread }
| ^^^^^^ expected `Option<JoinHandle<()>>`, found `JoinHandle<_>`
|
= note: expected enum `Option<JoinHandle<()>>`
found struct `JoinHandle<_>`
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
Let’s address the second error, which points to the code at the end of
Worker::new
; we need to wrap the thread
value in Some
when we create a
new Worker
. Make the following changes to fix this error:
让我们解决第二个错误,它指向Worker::new
末尾的代码;当我们创建一个新的Worker
时,我们需要将thread
值包装在Some
中。进行以下更改以修复此错误:
Filename: src/lib.rs 文件名:src/lib.rs
The first error is in our Drop
implementation. We mentioned earlier that we
intended to call take
on the Option
value to move thread
out of worker
.
The following changes will do so:
第一个错误出现在我们的Drop
实现中。我们之前提到过,我们打算对Option
值调用take
来将thread
移出worker
。以下更改将实现此目的:
Filename: src/lib.rs 文件名:src/lib.rs
As discussed in Chapter 17, the take
method on Option
takes the Some
variant out and leaves None
in its place. We’re using if let
to destructure
the Some
and get the thread; then we call join
on the thread. If a worker’s
thread is already None
, we know that worker has already had its thread
cleaned up, so nothing happens in that case.
正如第 17 章中所讨论的, Option
上的take
方法取出Some
变体并保留None
。我们使用if let
来解构Some
并获取线程;然后我们在线程上调用join
。如果一个工作线程已经是None
,我们就知道该工作线程已经清理了它的线程,所以在这种情况下什么也不会发生。
Signaling to the Threads to Stop Listening for Jobs
向线程发出信号以停止侦听作业
With all the changes we’ve made, our code compiles without any warnings.
However, the bad news is this code doesn’t function the way we want it to yet.
The key is the logic in the closures run by the threads of the Worker
instances: at the moment, we call join
, but that won’t shut down the threads
because they loop
forever looking for jobs. If we try to drop our
ThreadPool
with our current implementation of drop
, the main thread will
block forever waiting for the first thread to finish.
经过我们所做的所有更改,我们的代码编译时不会出现任何警告。然而,坏消息是这段代码还没有按照我们想要的方式运行。关键是Worker
实例的线程运行的闭包中的逻辑:目前,我们调用join
,但这不会关闭线程,因为它们loop
永远循环寻找作业。如果我们尝试使用当前的drop
实现来删除ThreadPool
,主线程将永远阻塞,等待第一个线程完成。
To fix this problem, we’ll need a change in the ThreadPool
drop
implementation and then a change in the Worker
loop.
要解决此问题,我们需要更改ThreadPool
drop
实现,然后更改Worker
循环。
First, we’ll change the ThreadPool
drop
implementation to explicitly drop
the sender
before waiting for the threads to finish. Listing 20-23 shows the
changes to ThreadPool
to explicitly drop sender
. We use the same Option
and take
technique as we did with the thread to be able to move sender
out
of ThreadPool
:
首先,我们将更改ThreadPool
drop
实现,以在等待线程完成之前显式删除sender
。清单 20-23 显示了对ThreadPool
进行的更改,以显式删除sender
。我们使用与线程相同的Option
并take
技术,以便能够将sender
移出ThreadPool
:
Filename: src/lib.rs 文件名:src/lib.rs
Dropping sender
closes the channel, which indicates no more messages will be
sent. When that happens, all the calls to recv
that the workers do in the
infinite loop will return an error. In Listing 20-24, we change the Worker
loop to gracefully exit the loop in that case, which means the threads will
finish when the ThreadPool
drop
implementation calls join
on them.
删除sender
将关闭通道,这表明将不再发送消息。发生这种情况时,工作人员在无限循环中执行的所有对recv
的调用都将返回错误。在清单 20-24 中,我们更改了Worker
循环,以便在这种情况下优雅地退出循环,这意味着当ThreadPool
drop
实现对线程调用join
时,线程将完成。
Filename: src/lib.rs 文件名:src/lib.rs
To see this code in action, let’s modify main
to accept only two requests
before gracefully shutting down the server, as shown in Listing 20-25.
要查看此代码的实际效果,我们将main
修改为仅接受两个请求,然后再正常关闭服务器,如清单 20-25 所示。
Filename: src/main.rs 文件名:src/main.rs
You wouldn’t want a real-world web server to shut down after serving only two
requests. This code just demonstrates that the graceful shutdown and cleanup is
in working order.
您不希望现实世界的 Web 服务器在仅处理两个请求后关闭。此代码仅表明正常关闭和清理工作正常。
The take
method is defined in the Iterator
trait and limits the iteration
to the first two items at most. The ThreadPool
will go out of scope at the
end of main
, and the drop
implementation will run.take
方法在Iterator
特征中定义,并将迭代限制为最多前两项。 ThreadPool
将在main
末尾超出范围,并且drop
实现将运行。
Start the server with cargo run
, and make three requests. The third request
should error, and in your terminal you should see output similar to this:
使用cargo run
启动服务器,并发出三个请求。第三个请求应该出错,并且在您的终端中您应该看到类似于以下内容的输出:
$ 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
You might see a different ordering of workers and messages printed. We can see
how this code works from the messages: workers 0 and 3 got the first two
requests. The server stopped accepting connections after the second connection,
and the Drop
implementation on ThreadPool
starts executing before worker 3
even starts its job. Dropping the sender
disconnects all the workers and
tells them to shut down. The workers each print a message when they disconnect,
and then the thread pool calls join
to wait for each worker thread to finish.
您可能会看到打印的工作人员和消息的顺序不同。我们可以从消息中看到这段代码的工作原理:workers 0 和 3 收到了前两个请求。服务器在第二个连接后停止接受连接,并且ThreadPool
上的Drop
实现在工作线程 3 开始其作业之前就开始执行。删除sender
会断开所有工作人员的连接并告诉他们关闭。每个工作线程在断开连接时都会打印一条消息,然后线程池调用join
等待每个工作线程完成。
Notice one interesting aspect of this particular execution: the ThreadPool
dropped the sender
, and before any worker received an error, we tried to join
worker 0. Worker 0 had not yet gotten an error from recv
, so the main thread
blocked waiting for worker 0 to finish. In the meantime, worker 3 received a
job and then all threads received an error. When worker 0 finished, the main
thread waited for the rest of the workers to finish. At that point, they had
all exited their loops and stopped.
请注意此特定执行的一个有趣的方面: ThreadPool
删除了sender
,并且在任何工作程序收到错误之前,我们尝试加入工作程序 0。工作程序 0 尚未从recv
收到错误,因此主线程阻塞等待工作程序 0完成。与此同时,worker 3 收到了一个作业,然后所有线程都收到了一个错误。当worker 0完成后,主线程等待其余worker完成。那时,他们都退出了循环并停止了。
Congrats! We’ve now completed our project; we have a basic web server that uses
a thread pool to respond asynchronously. We’re able to perform a graceful
shutdown of the server, which cleans up all the threads in the pool.
恭喜!我们现在已经完成了我们的项目;我们有一个基本的 Web 服务器,它使用线程池来异步响应。我们能够正常关闭服务器,从而清理池中的所有线程。
Here’s the full code for reference:
以下是完整代码供参考:
Filename: src/main.rs 文件名:src/main.rs
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(&mut stream);
let request_line = buf_reader.lines().next().unwrap().unwrap();
let (status_line, filename) = match &request_line[..] {
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
_ => ("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();
}
Filename: src/lib.rs 文件名:src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: Option<mpsc::Sender<Job>>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
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) -> ThreadPool {
assert!(size > 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(&receiver)));
}
ThreadPool {
workers,
sender: Some(sender),
}
}
pub fn execute<F>(&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(&mut self) {
drop(self.sender.take());
for worker in &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<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv();
match message {
Ok(job) => {
println!("Worker {id} got a job; executing.");
job();
}
Err(_) => {
println!("Worker {id} disconnected; shutting down.");
break;
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}
We could do more here! If you want to continue enhancing this project, here are
some ideas:
我们可以在这里做得更多!如果您想继续增强这个项目,这里有一些想法:
- Add more documentation to
ThreadPool
and its public methods.
为ThreadPool
及其公共方法添加更多文档。 - Add tests of the library’s functionality.
添加库功能的测试。 - Change calls to
unwrap
to more robust error handling.
更改对unwrap
调用以实现更强大的错误处理。 - Use
ThreadPool
to perform some task other than serving web requests.
使用ThreadPool
执行除处理 Web 请求之外的某些任务。 - Find a thread pool crate on crates.io and implement a
similar web server using the crate instead. Then compare its API and
robustness to the thread pool we implemented.
在crates.io上找到一个线程池 crate,并使用该 crate 实现一个类似的 Web 服务器。然后将它的API和健壮性与我们实现的线程池进行比较。
Summary 概括
Well done! You’ve made it to the end of the book! We want to thank you for
joining us on this tour of Rust. You’re now ready to implement your own Rust
projects and help with other peoples’ projects. Keep in mind that there is a
welcoming community of other Rustaceans who would love to help you with any
challenges you encounter on your Rust journey.
干得好!您已经读到了本书的结尾!我们要感谢您加入我们的 Rust 之旅。您现在已准备好实现自己的 Rust 项目并帮助其他人的项目。请记住,有一个由其他 Rustaceans 组成的热情社区,他们很乐意帮助您解决 Rust 之旅中遇到的任何挑战。
Appendix 附录
The following sections contain reference material you may find useful in your
Rust journey.
以下部分包含您可能会发现对 Rust 之旅有用的参考材料。
Appendix A: Keywords 附录 A:关键词
The following list contains keywords that are reserved for current or future
use by the Rust language. As such, they cannot be used as identifiers (except
as raw identifiers as we’ll discuss in the “Raw
Identifiers” section). Identifiers are names
of functions, variables, parameters, struct fields, modules, crates, constants,
macros, static values, attributes, types, traits, or lifetimes.
以下列表包含 Rust 语言保留供当前或将来使用的关键字。因此,它们不能用作标识符(除非作为原始标识符,我们将在“原始标识符忽略”部分中讨论)。标识符是函数、变量、参数、结构字段、模块、包、常量、宏、静态值、属性、类型、特征或生命周期的名称。
Keywords Currently in Use
当前使用的关键字
The following is a list of keywords currently in use, with their functionality
described.
以下是当前使用的关键字列表及其功能描述。
as
- perform primitive casting, disambiguate the specific trait containing an item, or rename items inuse
statementsas
- 执行原始转换,消除包含项目的特定特征的歧义,或重命名use
语句中的项目async
- return aFuture
instead of blocking the current threadasync
- 返回一个Future
而不是阻塞当前线程await
- suspend execution until the result of aFuture
is readyawait
- 暂停执行,直到Future
的结果准备就绪break
- exit a loop immediatelybreak
- 立即退出循环const
- define constant items or constant raw pointersconst
- 定义常量项或常量原始指针continue
- continue to the next loop iterationcontinue
- 继续下一个循环迭代crate
- in a module path, refers to the crate rootcrate
- 在模块路径中,指 crate 根dyn
- dynamic dispatch to a trait objectdyn
- 动态分派到特征对象else
- fallback forif
andif let
control flow constructselse
-if
和if let
控制流构造的后备enum
- define an enumerationenum
- 定义一个枚举extern
- link an external function or variableextern
- 链接外部函数或变量false
- Boolean false literalfalse
- 布尔假文字fn
- define a function or the function pointer typefn
- 定义函数或函数指针类型for
- loop over items from an iterator, implement a trait, or specify a higher-ranked lifetimefor
- 循环迭代器中的项目、实现特征或指定更高排名的生命周期if
- branch based on the result of a conditional expressionif
- 基于条件表达式的结果进行分支impl
- implement inherent or trait functionalityimpl
- 实现固有或特征功能in
- part offor
loop syntaxin
-for
循环语法的一部分let
- bind a variablelet
- 绑定一个变量loop
- loop unconditionallyloop
- 无条件循环match
- match a value to patternsmatch
- 将值与模式匹配mod
- define a modulemod
定义一个模块move
- make a closure take ownership of all its capturesmove
- 使闭包拥有其所有捕获的所有权mut
- denote mutability in references, raw pointers, or pattern bindingsmut
- 表示引用、原始指针或模式绑定中的可变性pub
- denote public visibility in struct fields,impl
blocks, or modulespub
- 表示结构字段、impl
块或模块中的公共可见性ref
- bind by referenceref
- 通过引用绑定return
- return from functionreturn
- 从函数返回Self
- a type alias for the type we are defining or implementingSelf
- 我们正在定义或实现的类型的类型别名self
- method subject or current moduleself
方法主题或当前模块static
- global variable or lifetime lasting the entire program executionstatic
- 全局变量或持续整个程序执行的生命周期struct
- define a structurestruct
定义一个结构体super
- parent module of the current module
当前模块的super
父模块trait
- define a traittrait
- 定义特质true
- Boolean true literaltrue
- 布尔 true 文字type
- define a type alias or associated typetype
- 定义类型别名或关联类型union
- define a union; is only a keyword when used in a union declarationunion
- 定义一个联合忽略;仅在联合声明中使用时是一个关键字unsafe
- denote unsafe code, functions, traits, or implementationsunsafe
- 表示不安全的代码、函数、特征或实现use
- bring symbols into scopeuse
- 将符号带入范围where
- denote clauses that constrain a typewhere
- 表示约束类型的子句while
- loop conditionally based on the result of an expressionwhile
- 根据表达式的结果有条件地循环
Keywords Reserved for Future Use
保留供将来使用的关键字
The following keywords do not yet have any functionality but are reserved by
Rust for potential future use.
以下关键字尚不具有任何功能,但 Rust 保留以供将来使用。
abstract
become
box
do
final
macro
override
priv
try
typeof
unsized
virtual
yield
Raw Identifiers 原始标识符
Raw identifiers are the syntax that lets you use keywords where they wouldn’t
normally be allowed. You use a raw identifier by prefixing a keyword with r#
.
原始标识符是允许您在通常不允许的地方使用关键字的语法。您可以通过在关键字前加上r#
来使用原始标识符。
For example, match
is a keyword. If you try to compile the following function
that uses match
as its name:
例如, match
是一个关键字。如果您尝试编译以下使用match
作为名称的函数:
Filename: src/main.rs 文件名:src/main.rs
fn match(needle: &str, haystack: &str) -> bool {
haystack.contains(needle)
}
you’ll get this error: 你会得到这个错误:
error: expected identifier, found keyword `match`
--> src/main.rs:4:4
|
4 | fn match(needle: &str, haystack: &str) -> bool {
| ^^^^^ expected identifier, found keyword
The error shows that you can’t use the keyword match
as the function
identifier. To use match
as a function name, you need to use the raw
identifier syntax, like this:
该错误表明您不能使用关键字match
作为函数标识符。要将match
用作函数名称,您需要使用原始标识符语法,如下所示:
Filename: src/main.rs 文件名:src/main.rs
fn r#match(needle: &str, haystack: &str) -> bool {
haystack.contains(needle)
}
fn main() {
assert!(r#match("foo", "foobar"));
}
This code will compile without any errors. Note the r#
prefix on the function
name in its definition as well as where the function is called in main
.
这段代码将编译,没有任何错误。请注意函数定义中函数名称的r#
前缀以及main
中调用该函数的位置。
Raw identifiers allow you to use any word you choose as an identifier, even if
that word happens to be a reserved keyword. This gives us more freedom to
choose identifier names, as well as lets us integrate with programs written in
a language where these words aren’t keywords. In addition, raw identifiers
allow you to use libraries written in a different Rust edition than your crate
uses. For example, try
isn’t a keyword in the 2015 edition but is in the 2018
edition. If you depend on a library that’s written using the 2015 edition and
has a try
function, you’ll need to use the raw identifier syntax, r#try
in
this case, to call that function from your 2018 edition code. See Appendix
E for more information on editions.
原始标识符允许您使用您选择的任何单词作为标识符,即使该单词恰好是保留关键字。这使我们能够更自由地选择标识符名称,并且使我们能够与用这些单词不是关键字的语言编写的程序集成。此外,原始标识符允许您使用与您的 crate 使用的 Rust 版本不同的库。例如, try
在 2015 版中不是关键字,但在 2018 版中却是关键字。如果您依赖使用 2015 版编写的库并具有try
函数,则需要使用原始标识符语法(本例中为r#try
从 2018 版代码中调用该函数。有关版本的更多信息,请参阅附录 E忽略。
Appendix B: Operators and Symbols
附录 B:运算符和符号
This appendix contains a glossary of Rust’s syntax, including operators and
other symbols that appear by themselves or in the context of paths, generics,
trait bounds, macros, attributes, comments, tuples, and brackets.
本附录包含 Rust 语法的术语表,包括单独出现或出现在路径、泛型、特征边界、宏、属性、注释、元组和括号上下文中的运算符和其他符号。
Operators 运营商
Table B-1 contains the operators in Rust, an example of how the operator would
appear in context, a short explanation, and whether that operator is
overloadable. If an operator is overloadable, the relevant trait to use to
overload that operator is listed.
表 B-1 包含 Rust 中的运算符、运算符在上下文中如何出现的示例、简短说明以及该运算符是否可重载。如果运算符可重载,则会列出用于重载该运算符的相关特征。
Operator 操作员 | Example 例子 | Explanation 解释 | Overloadable? 可超载吗? |
---|---|---|---|
! | ident!(...) , ident!{...} , ident![...] ident!(...) , ident!{...} , ident![...] | Macro expansion 宏观扩张 | |
! | !expr | Bitwise or logical complement 按位或逻辑求补 | Not |
!= | expr != expr | Nonequality comparison 非等式比较 | PartialEq |
% | expr % expr | Arithmetic remainder 算术余数 | Rem |
%= | var %= expr | Arithmetic remainder and assignment 算术余数和赋值 | RemAssign |
& | &expr , &mut expr &expr , &mut expr | Borrow 借 | |
& | &type , &mut type , &'a type , &'a mut type &type , &mut type , &'a type , &'a mut type | Borrowed pointer type 借用指针类型 | |
& | expr & expr | Bitwise AND 按位与 | BitAnd |
&= | var &= expr | Bitwise AND and assignment 按位与和赋值 | BitAndAssign |
&& | expr && expr | Short-circuiting logical AND 短路逻辑与 | |
* | expr * expr | Arithmetic multiplication 算术乘法 | Mul |
*= | var *= expr | Arithmetic multiplication and assignment 算术乘法和赋值 | MulAssign |
* | *expr | Dereference 解引用 | Deref |
* | *const type , *mut type *const type , *mut type | Raw pointer 原始指针 | |
+ | trait + trait , 'a + trait trait + trait , 'a + trait | Compound type constraint 复合类型约束 | |
+ | expr + expr | Arithmetic addition 算术加法 | Add |
+= | var += expr | Arithmetic addition and assignment 算术加法和赋值 | AddAssign |
, | expr, expr | Argument and element separator 参数和元素分隔符 | |
- | - expr | Arithmetic negation 算术求反 | Neg |
- | expr - expr | Arithmetic subtraction 算术减法 | Sub |
-= | var -= expr | Arithmetic subtraction and assignment 算术减法和赋值 | SubAssign |
-> | fn(...) -> type , |…| -> type fn(...) -> type , |…| -> type | Function and closure return type 函数和闭包返回类型 | |
. | expr.ident | Member access 会员访问 | |
.. | .. , expr.. , ..expr , expr..expr .. , expr.. , ..expr , expr..expr | Right-exclusive range literal 右独占范围文字 | PartialOrd |
..= | ..=expr , expr..=expr ..=expr , expr..=expr | Right-inclusive range literal 右包含范围文字 | PartialOrd |
.. | ..expr | Struct literal update syntax 结构体字面量更新语法 | |
.. | variant(x, ..) , struct_type { x, .. } variant(x, ..) , struct_type { x, .. } | “And the rest” pattern binding “其余”模式绑定 | |
... | expr...expr | (Deprecated, use ..= instead) In a pattern: inclusive range pattern(已弃用,请使用 ..= 代替)在模式中:包含范围模式 | |
/ | expr / expr | Arithmetic division 算术除法 | Div |
/= | var /= expr | Arithmetic division and assignment 算术除法和赋值 | DivAssign |
: | pat: type , ident: type pat: type , ident: type | Constraints 约束条件 | |
: | ident: expr | Struct field initializer 结构体字段初始值设定项 | |
: | 'a: loop {...} | Loop label 循环标签 | |
; | expr; | Statement and item terminator 语句和项目终止符 | |
; | [...; len] | Part of fixed-size array syntax 固定大小数组语法的一部分 | |
<< | expr << expr | Left-shift 左移 | Shl |
<<= | var <<= expr | Left-shift and assignment 左移和赋值 | ShlAssign |
< | expr < expr | Less than comparison 小于比较 | PartialOrd |
<= | expr <= expr | Less than or equal to comparison 小于或等于比较 | PartialOrd |
= | var = expr , ident = type var = expr , ident = type | Assignment/equivalence 赋值/等价 | |
== | expr == expr | Equality comparison 平等比较 | PartialEq |
=> | pat => expr | Part of match arm syntax 匹配臂语法的一部分 | |
> | expr > expr | Greater than comparison 大于比较 | PartialOrd |
>= | expr >= expr | Greater than or equal to comparison 大于或等于比较 | PartialOrd |
>> | expr >> expr | Right-shift 右移 | Shr |
>>= | var >>= expr | Right-shift and assignment 右移和赋值 | ShrAssign |
@ | ident @ pat | Pattern binding 图案装订 | |
^ | expr ^ expr | Bitwise exclusive OR 按位异或 | BitXor |
^= | var ^= expr | Bitwise exclusive OR and assignment 按位异或和赋值 | BitXorAssign |
| | pat | pat | Pattern alternatives 模式替代方案 | |
| | expr | expr | Bitwise OR 按位或 | BitOr |
|= | var |= expr | Bitwise OR and assignment 按位或和赋值 | BitOrAssign |
|| | expr || expr | Short-circuiting logical OR 短路逻辑或 | |
? | expr? | Error propagation 误差传播 |
Non-operator Symbols 非运算符符号
The following list contains all symbols that don’t function as operators; that
is, they don’t behave like a function or method call.
以下列表包含所有不用作运算符的符号;也就是说,它们的行为不像函数或方法调用。
Table B-2 shows symbols that appear on their own and are valid in a variety of
locations.
表 B-2 显示了单独出现且在各种位置有效的符号。
Symbol 象征 | Explanation 解释 |
---|---|
'ident | Named lifetime or loop label 命名生命周期或循环标签 |
...u8 , ...i32 , ...f64 , ...usize , etc....u8 、 ...i32 、 ...f64 、 ...usize 等。 | Numeric literal of specific type 特定类型的数字文字 |
"..." | String literal 字符串文字 |
r"..." , r#"..."# , r##"..."## , etc.r"..." 、 r#"..."# 、 r##"..."## 等。 | Raw string literal, escape characters not processed 原始字符串文字,未处理转义字符 |
b"..." | Byte string literal; constructs an array of bytes instead of a string 字节字符串文字;构造一个字节数组而不是字符串 |
br"..." , br#"..."# , br##"..."## , etc.br"..." 、 br#"..."# 、 br##"..."## 等。 | Raw byte string literal, combination of raw and byte string literal 原始字节字符串文字、原始字符串文字和字节字符串文字的组合 |
'...' | Character literal 字符字面量 |
b'...' | ASCII byte literal ASCII 字节文字 |
|…| expr | Closure 关闭 |
! | Always empty bottom type for diverging functions 始终为空底类型,用于发散功能 |
_ | “Ignored” pattern binding; also used to make integer literals readable “忽略”模式绑定;也用于使整数文字可读 |
Table B-3 shows symbols that appear in the context of a path through the module
hierarchy to an item.
表 B-3 显示了出现在从模块层次结构到项目的路径上下文中的符号。
Symbol 象征 | Explanation 解释 |
---|---|
ident::ident | Namespace path 命名空间路径 |
::path | Path relative to the crate root (i.e., an explicitly absolute path) 相对于 crate 根的路径(即明确的绝对路径) |
self::path | Path relative to the current module (i.e., an explicitly relative path). 相对于当前模块的路径(即显式相对路径)。 |
super::path | Path relative to the parent of the current module 相对于当前模块父模块的路径 |
type::ident , <type as trait>::ident type::ident , <type as trait>::ident | Associated constants, functions, and types 关联的常量、函数和类型 |
<type>::... | Associated item for a type that cannot be directly named (e.g., <&T>::... , <[T]>::... , etc.)无法直接命名的类型的关联项(例如, <&T>::... 、 <[T]>::... 等) |
trait::method(...) | Disambiguating a method call by naming the trait that defines it 通过命名定义方法调用的特征来消除方法调用的歧义 |
type::method(...) | Disambiguating a method call by naming the type for which it’s defined 通过命名定义方法的类型来消除方法调用的歧义 |
<type as trait>::method(...) | Disambiguating a method call by naming the trait and type 通过命名特征和类型来消除方法调用的歧义 |
Table B-4 shows symbols that appear in the context of using generic type
parameters.
表 B-4 显示了在使用泛型类型参数的上下文中出现的符号。
Symbol 象征 | Explanation 解释 |
---|---|
path<...> | Specifies parameters to generic type in a type (e.g., Vec<u8> )将参数指定为类型中的泛型类型(例如, Vec<u8> ) |
path::<...> , method::<...> path::<...> , method::<...> | Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., "42".parse::<i32>() )指定表达式中泛型类型、函数或方法的参数;通常称为涡轮鱼(例如, "42".parse::<i32>() ) |
fn ident<...> ... | Define generic function 定义通用函数 |
struct ident<...> ... | Define generic structure 定义通用结构 |
enum ident<...> ... | Define generic enumeration 定义泛型枚举 |
impl<...> ... | Define generic implementation 定义通用实现 |
for<...> type | Higher-ranked lifetime bounds 更高级别的生命周期 |
type<ident=type> | A generic type where one or more associated types have specific assignments (e.g., Iterator<Item=T> )一种泛型类型,其中一个或多个关联类型具有特定的赋值(例如, Iterator<Item=T> ) |
Table B-5 shows symbols that appear in the context of constraining generic type
parameters with trait bounds.
表 B-5 显示了在使用特征边界约束泛型类型参数的上下文中出现的符号。
Symbol 象征 | Explanation 解释 |
---|---|
T: U | Generic parameter T constrained to types that implement U 通用参数 T 约束为实现U 类型 |
T: 'a | Generic type T must outlive lifetime 'a (meaning the type cannot transitively contain any references with lifetimes shorter than 'a )泛型类型 T 生命周期必须比'a 长(意味着该类型不能传递包含任何生命周期短于'a 引用) |
T: 'static | Generic type T contains no borrowed references other than 'static ones通用类型 T 不包含除'static 引用”之外的借用引用 |
'b: 'a | Generic lifetime 'b must outlive lifetime 'a 通用生命周期 'b 必须比生命周期'a 长 |
T: ?Sized | Allow generic type parameter to be a dynamically sized type 允许泛型类型参数是动态调整大小的类型 |
'a + trait , trait + trait 'a + trait , trait + trait | Compound type constraint 复合类型约束 |
Table B-6 shows symbols that appear in the context of calling or defining
macros and specifying attributes on an item.
表 B-6 显示了在调用或定义宏以及指定项目属性的上下文中出现的符号。
Symbol 象征 | Explanation 解释 |
---|---|
#[meta] | Outer attribute 外层属性 |
#![meta] | Inner attribute 内在属性 |
$ident | Macro substitution 宏替换 |
$ident:kind | Macro capture 微距捕捉 |
$(…)… | Macro repetition 宏重复 |
ident!(...) , ident!{...} , ident![...] ident!(...) , ident!{...} , ident![...] | Macro invocation 宏调用 |
Table B-7 shows symbols that create comments.
表 B-7 显示了创建注释的符号。
Symbol 象征 | Explanation 解释 |
---|---|
// | Line comment 行评论 |
//! | Inner line doc comment 内行文档注释 |
/// | Outer line doc comment 外线文档注释 |
/*...*/ | Block comment 阻止评论 |
/*!...*/ | Inner block doc comment 内部块文档注释 |
/**...*/ | Outer block doc comment 外部块文档注释 |
Table B-8 shows symbols that appear in the context of using tuples.
表 B-8 显示了在使用元组的上下文中出现的符号。
Symbol 象征 | Explanation 解释 |
---|---|
() | Empty tuple (aka unit), both literal and type 空元组(又名单元),包括文字和类型 |
(expr) | Parenthesized expression 带括号的表达式 |
(expr,) | Single-element tuple expression 单元素元组表达式 |
(type,) | Single-element tuple type 单元素元组类型 |
(expr, ...) | Tuple expression 元组表达式 |
(type, ...) | Tuple type 元组类型 |
expr(expr, ...) | Function call expression; also used to initialize tuple struct s and tuple enum variants函数调用表达式;还用于初始化元组 struct 和元enum 变体 |
expr.0 , expr.1 , etc.expr.0 、 expr.1 等 | Tuple indexing 元组索引 |
Table B-9 shows the contexts in which curly braces are used.
表 B-9 显示了使用花括号的上下文。
Context 语境 | Explanation 解释 |
---|---|
{...} | Block expression 块表达式 |
Type {...} | struct literalstruct 字面量 |
Table B-10 shows the contexts in which square brackets are used.
表 B-10 显示了使用方括号的上下文。
Context 语境 | Explanation 解释 |
---|---|
[...] | Array literal 数组字面量 |
[expr; len] | Array literal containing len copies of expr 包含 expr 的len 个副本的数组文字 |
[type; len] | Array type containing len instances of type 包含 len type 实例的数组类型 |
expr[expr] | Collection indexing. Overloadable (Index , IndexMut )集合索引。可重载( Index 、 IndexMut ) |
expr[..] , expr[a..] , expr[..b] , expr[a..b] expr[..] 、 expr[a..] 、 expr[..b] 、 expr[a..b] | Collection indexing pretending to be collection slicing, using Range , RangeFrom , RangeTo , or RangeFull as the “index”集合索引伪装成集合切片,使用 Range 、 RangeFrom 、 RangeTo 或RangeFull 作为“索引” |
Appendix C: Derivable Traits
附录 C:可衍生特征
In various places in the book, we’ve discussed the derive
attribute, which
you can apply to a struct or enum definition. The derive
attribute generates
code that will implement a trait with its own default implementation on the
type you’ve annotated with the derive
syntax.
在本书的不同地方,我们讨论了derive
属性,您可以将其应用于结构或枚举定义。 derive
属性生成的代码将在您使用derive
语法注释的类型上使用其自己的默认实现来实现特征。
In this appendix, we provide a reference of all the traits in the standard
library that you can use with derive
. Each section covers:
在本附录中,我们提供了标准库中可与derive
一起使用的所有特征的参考。每个部分涵盖:
- What operators and methods deriving this trait will enable
派生此特征的运算符和方法将启用什么 - What the implementation of the trait provided by
derive
doesderive
提供的特征的实现做了什么 - What implementing the trait signifies about the type
实现该特征对类型意味着什么 - The conditions in which you’re allowed or not allowed to implement the trait
允许或不允许您实施该特征的条件 - Examples of operations that require the trait
需要该特征的操作示例
If you want different behavior from that provided by the derive
attribute,
consult the standard library documentation
for each trait for details of how to manually implement them.
如果您想要与derive
属性提供的行为不同的行为,请参阅每个特征的标准库文档ignore,了解如何手动实现它们的详细信息。
These traits listed here are the only ones defined by the standard library that
can be implemented on your types using derive
. Other traits defined in the
standard library don’t have sensible default behavior, so it’s up to you to
implement them in the way that makes sense for what you’re trying to accomplish.
此处列出的这些特征是标准库定义的唯一可以使用derive
在您的类型上实现的特征。标准库中定义的其他特征没有合理的默认行为,因此您需要以对您想要完成的任务有意义的方式来实现它们。
An example of a trait that can’t be derived is Display
, which handles
formatting for end users. You should always consider the appropriate way to
display a type to an end user. What parts of the type should an end user be
allowed to see? What parts would they find relevant? What format of the data
would be most relevant to them? The Rust compiler doesn’t have this insight, so
it can’t provide appropriate default behavior for you.
无法派生的特征的一个示例是Display
,它为最终用户处理格式。您应该始终考虑向最终用户显示类型的适当方式。应允许最终用户查看类型的哪些部分?他们会发现哪些部分相关?什么格式的数据与他们最相关? Rust 编译器没有这种洞察力,因此它无法为您提供适当的默认行为。
The list of derivable traits provided in this appendix is not comprehensive:
libraries can implement derive
for their own traits, making the list of
traits you can use derive
with truly open-ended. Implementing derive
involves using a procedural macro, which is covered in the
“Macros” section of Chapter 19.
本附录中提供的可派生特征列表并不全面:库可以为自己的特征实现derive
,从而使您可以使用derive
的特征列表真正开放。实现derive
涉及使用过程宏,这在第 19 章的“宏”忽略部分中进行了介绍。
Debug
for Programmer Output
Debug
程序员输出
The Debug
trait enables debug formatting in format strings, which you
indicate by adding :?
within {}
placeholders.Debug
特征启用格式字符串中的调试格式,您可以通过添加:?
来指示。在{}
占位符内。
The Debug
trait allows you to print instances of a type for debugging
purposes, so you and other programmers using your type can inspect an instance
at a particular point in a program’s execution.Debug
特征允许您出于调试目的打印类型的实例,因此您和使用您的类型的其他程序员可以在程序执行的特定点检查实例。
The Debug
trait is required, for example, in using the assert_eq!
macro.
This macro prints the values of instances given as arguments if the equality
assertion fails so programmers can see why the two instances weren’t equal.Debug
特征是必需的,例如,在使用assert_eq!
宏。如果相等断言失败,此宏将打印作为参数给出的实例的值,以便程序员可以了解为什么两个实例不相等。
PartialEq
and Eq
for Equality Comparisons
用于相等比较的PartialEq
和Eq
The PartialEq
trait allows you to compare instances of a type to check for
equality and enables use of the ==
and !=
operators.PartialEq
特征允许您比较类型的实例以检查是否相等,并允许使用==
和!=
运算符。
Deriving PartialEq
implements the eq
method. When PartialEq
is derived on
structs, two instances are equal only if all fields are equal, and the
instances are not equal if any fields are not equal. When derived on enums,
each variant is equal to itself and not equal to the other variants.
派生PartialEq
实现eq
方法。当在结构上派生PartialEq
时,仅当所有字段都相等时,两个实例才相等,如果任何字段不相等,则实例不相等。当对枚举进行派生时,每个变体都等于其自身,并且不等于其他变体。
The PartialEq
trait is required, for example, with the use of the
assert_eq!
macro, which needs to be able to compare two instances of a type
for equality.PartialEq
特征是必需的,例如,使用assert_eq!
宏,它需要能够比较类型的两个实例是否相等。
The Eq
trait has no methods. Its purpose is to signal that for every value of
the annotated type, the value is equal to itself. The Eq
trait can only be
applied to types that also implement PartialEq
, although not all types that
implement PartialEq
can implement Eq
. One example of this is floating point
number types: the implementation of floating point numbers states that two
instances of the not-a-number (NaN
) value are not equal to each other.Eq
特征没有方法。其目的是表明对于带注释类型的每个值,该值都等于其自身。 Eq
特征只能应用于也实现PartialEq
的类型,尽管并非所有实现PartialEq
的类型都可以实现Eq
。其中一个示例是浮点数类型:浮点数的实现表明非数字 ( NaN
) 值的两个实例彼此不相等。
An example of when Eq
is required is for keys in a HashMap<K, V>
so the
HashMap<K, V>
can tell whether two keys are the same.
需要Eq
的一个示例是HashMap<K, V>
中的键,因此HashMap<K, V>
可以判断两个键是否相同。
PartialOrd
and Ord
for Ordering Comparisons
用于排序比较的PartialOrd
和Ord
The PartialOrd
trait allows you to compare instances of a type for sorting
purposes. A type that implements PartialOrd
can be used with the <
, >
,
<=
, and >=
operators. You can only apply the PartialOrd
trait to types
that also implement PartialEq
.PartialOrd
特征允许您比较类型的实例以进行排序。实现PartialOrd
的类型可以与<
、 >
、 <=
和>=
运算符一起使用。您只能将PartialOrd
特征应用于也实现PartialEq
的类型。
Deriving PartialOrd
implements the partial_cmp
method, which returns an
Option<Ordering>
that will be None
when the values given don’t produce an
ordering. An example of a value that doesn’t produce an ordering, even though
most values of that type can be compared, is the not-a-number (NaN
) floating
point value. Calling partial_cmp
with any floating point number and the NaN
floating point value will return None
.
派生PartialOrd
实现partial_cmp
方法,该方法返回Option<Ordering>
,当给定的值不产生排序时,该选项将为None
。即使可以比较该类型的大多数值,也不产生排序的值的一个示例是非数字 ( NaN
) 浮点值。使用任何浮点数和NaN
浮点值调用partial_cmp
将返回None
。
When derived on structs, PartialOrd
compares two instances by comparing the
value in each field in the order in which the fields appear in the struct
definition. When derived on enums, variants of the enum declared earlier in the
enum definition are considered less than the variants listed later.
当在结构上派生时, PartialOrd
通过按照字段在结构定义中出现的顺序比较每个字段中的值来比较两个实例。当在枚举上派生时,枚举定义中前面声明的枚举的变体被认为小于后面列出的变体。
The PartialOrd
trait is required, for example, for the gen_range
method
from the rand
crate that generates a random value in the range specified by a
range expression.
例如, rand
箱中的gen_range
方法需要PartialOrd
特征,该方法在范围表达式指定的范围内生成随机值。
The Ord
trait allows you to know that for any two values of the annotated
type, a valid ordering will exist. The Ord
trait implements the cmp
method,
which returns an Ordering
rather than an Option<Ordering>
because a valid
ordering will always be possible. You can only apply the Ord
trait to types
that also implement PartialOrd
and Eq
(and Eq
requires PartialEq
). When
derived on structs and enums, cmp
behaves the same way as the derived
implementation for partial_cmp
does with PartialOrd
.Ord
特征让您知道对于带注释类型的任意两个值,都将存在有效的排序。 Ord
特征实现cmp
方法,该方法返回Ordering
而不是Option<Ordering>
因为有效的排序始终是可能的。您只能将Ord
特征应用于同时实现PartialOrd
和Eq
的类型(并且Eq
需要PartialEq
)。当在结构体和枚举上派生时, cmp
行为与使用PartialOrd
的partial_cmp
的派生实现相同。
An example of when Ord
is required is when storing values in a BTreeSet<T>
,
a data structure that stores data based on the sort order of the values.
需要Ord
的一个示例是将值存储在BTreeSet<T>
中,这是一种根据值的排序顺序存储数据的数据结构。
Clone
and Copy
for Duplicating Values
Clone
和Copy
重复值
The Clone
trait allows you to explicitly create a deep copy of a value, and
the duplication process might involve running arbitrary code and copying heap
data. See the “Ways Variables and Data Interact:
Clone” section in
Chapter 4 for more information on Clone
.Clone
特征允许您显式创建值的深层副本,并且复制过程可能涉及运行任意代码和复制堆数据。有关Clone
更多信息,请参阅第 4 章中的“变量和数据交互方式:克隆”忽略部分。
Deriving Clone
implements the clone
method, which when implemented for the
whole type, calls clone
on each of the parts of the type. This means all the
fields or values in the type must also implement Clone
to derive Clone
.
派生Clone
实现了clone
方法,当为整个类型实现该方法时,会对该类型的每个部分调用clone
。这意味着类型中的所有字段或值也必须实现Clone
才能派生Clone
。
An example of when Clone
is required is when calling the to_vec
method on a
slice. The slice doesn’t own the type instances it contains, but the vector
returned from to_vec
will need to own its instances, so to_vec
calls
clone
on each item. Thus, the type stored in the slice must implement Clone
.
需要Clone
的一个例子是在切片上调用to_vec
方法时。切片不拥有它包含的类型实例,但从to_vec
返回的向量需要拥有它的实例,因此to_vec
对每个项目调用clone
。因此,存储在切片中的类型必须实现Clone
。
The Copy
trait allows you to duplicate a value by only copying bits stored on
the stack; no arbitrary code is necessary. See the “Stack-Only Data:
Copy” section in Chapter 4 for more
information on Copy
.Copy
特性允许您通过仅复制存储在堆栈上的位来复制值;不需要任意代码。有关Copy
更多信息,请参阅第 4 章中的“仅堆栈数据:复制”忽略部分。
The Copy
trait doesn’t define any methods to prevent programmers from
overloading those methods and violating the assumption that no arbitrary code
is being run. That way, all programmers can assume that copying a value will be
very fast.Copy
特征没有定义任何方法来防止程序员重载这些方法并违反没有运行任意代码的假设。这样,所有程序员都可以假设复制值会非常快。
You can derive Copy
on any type whose parts all implement Copy
. A type that
implements Copy
must also implement Clone
, because a type that implements
Copy
has a trivial implementation of Clone
that performs the same task as
Copy
.
您可以在其部分全部实现Copy
的任何类型上派生Copy
。实现Copy
的类型也必须实现Clone
,因为实现Copy
的类型有一个简单的Clone
实现,它执行与Copy
相同的任务。
The Copy
trait is rarely required; types that implement Copy
have
optimizations available, meaning you don’t have to call clone
, which makes
the code more concise.
很少需要Copy
特征;实现Copy
的类型具有可用的优化,这意味着您不必调用clone
,这使得代码更加简洁。
Everything possible with Copy
you can also accomplish with Clone
, but the
code might be slower or have to use clone
in places.
使用Copy
可以实现的一切,您也可以使用Clone
来完成,但代码可能会更慢或者必须在某些地方使用clone
。
Hash
for Mapping a Value to a Value of Fixed Size
用于将值映射到固定大小的值的Hash
The Hash
trait allows you to take an instance of a type of arbitrary size and
map that instance to a value of fixed size using a hash function. Deriving
Hash
implements the hash
method. The derived implementation of the hash
method combines the result of calling hash
on each of the parts of the type,
meaning all fields or values must also implement Hash
to derive Hash
.Hash
特征允许您获取任意大小的类型的实例,并使用哈希函数将该实例映射到固定大小的值。 Deriving Hash
实现了hash
方法。 hash
方法的派生实现结合了对类型的每个部分调用hash
的结果,这意味着所有字段或值也必须实现Hash
才能派生Hash
。
An example of when Hash
is required is in storing keys in a HashMap<K, V>
to store data efficiently.
需要Hash
的一个例子是将键存储在HashMap<K, V>
中以有效地存储数据。
Default
for Default Values
默认值的默认Default
The Default
trait allows you to create a default value for a type. Deriving
Default
implements the default
function. The derived implementation of the
default
function calls the default
function on each part of the type,
meaning all fields or values in the type must also implement Default
to
derive Default
.Default
特征允许您为类型创建默认值。 Deriving Default
实现default
功能。 default
函数的派生实现在类型的每个部分上调用default
函数,这意味着类型中的所有字段或值也必须实现Default
才能派生Default
。
The Default::default
function is commonly used in combination with the struct
update syntax discussed in the “Creating Instances From Other Instances With
Struct Update
Syntax”
section in Chapter 5. You can customize a few fields of a struct and then
set and use a default value for the rest of the fields by using
..Default::default()
.Default::default
函数通常与第 5 章“使用结构体更新语法从其他实例创建实例”忽略部分中讨论的结构体更新语法结合使用。您可以自定义结构体的一些字段,然后设置和使用使用..Default::default()
为其余字段设置默认值。
The Default
trait is required when you use the method unwrap_or_default
on
Option<T>
instances, for example. If the Option<T>
is None
, the method
unwrap_or_default
will return the result of Default::default
for the type
T
stored in the Option<T>
.
例如,当您在Option<T>
实例上使用unwrap_or_default
方法时,需要Default
特征。如果Option<T>
为None
,则方法unwrap_or_default
将为存储在Option<T>
中的类型T
返回Default::default
结果。
Appendix D - Useful Development Tools
附录 D - 有用的开发工具
In this appendix, we talk about some useful development tools that the Rust
project provides. We’ll look at automatic formatting, quick ways to apply
warning fixes, a linter, and integrating with IDEs.
在本附录中,我们讨论 Rust 项目提供的一些有用的开发工具。我们将研究自动格式化、应用警告修复的快速方法、linter 以及与 IDE 的集成。
Automatic Formatting with rustfmt
使用rustfmt
自动格式化
The rustfmt
tool reformats your code according to the community code style.
Many collaborative projects use rustfmt
to prevent arguments about which
style to use when writing Rust: everyone formats their code using the tool.rustfmt
工具根据社区代码风格重新格式化您的代码。许多协作项目使用rustfmt
来防止在编写 Rust 时关于使用哪种风格的争论:每个人都使用该工具格式化他们的代码。
To install rustfmt
, enter the following:
要安装rustfmt
,请输入以下内容:
$ rustup component add rustfmt
This command gives you rustfmt
and cargo-fmt
, similar to how Rust gives you
both rustc
and cargo
. To format any Cargo project, enter the following:
此命令为您提供rustfmt
和cargo-fmt
,类似于 Rust 为您提供rustc
和cargo
的方式。要格式化任何 Cargo 项目,请输入以下内容:
$ cargo fmt
Running this command reformats all the Rust code in the current crate. This
should only change the code style, not the code semantics. For more information
on rustfmt
, see its documentation.
运行此命令会重新格式化当前包中的所有 Rust 代码。这只应该改变代码风格,而不是代码语义。有关rustfmt
的更多信息,请参阅其文档。
Fix Your Code with rustfix
使用rustfix
修复你的代码
The rustfix tool is included with Rust installations and can automatically fix
compiler warnings that have a clear way to correct the problem that’s likely
what you want. It’s likely you’ve seen compiler warnings before. For example,
consider this code:
rustfix 工具包含在 Rust 安装中,可以自动修复编译器警告,这些警告有一个明确的方法来纠正可能是您想要的问题。您以前可能见过编译器警告。例如,考虑以下代码:
Filename: src/main.rs 文件名:src/main.rs
fn do_something() {}
fn main() {
for i in 0..100 {
do_something();
}
}
Here, we’re calling the do_something
function 100 times, but we never use the
variable i
in the body of the for
loop. Rust warns us about that:
在这里,我们调用了do_something
函数 100 次,但我们从未在for
循环体中使用变量i
。 Rust 警告我们:
$ cargo build
Compiling myprogram v0.1.0 (file:///projects/myprogram)
warning: unused variable: `i`
--> 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
The warning suggests that we use _i
as a name instead: the underscore
indicates that we intend for this variable to be unused. We can automatically
apply that suggestion using the rustfix
tool by running the command cargo fix
:
该警告建议我们使用_i
作为名称:下划线表示我们打算不使用该变量。我们可以使用rustfix
工具自动应用该建议,方法是运行命令cargo fix
:
$ 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
When we look at src/main.rs again, we’ll see that cargo fix
has changed the
code:
当我们再次查看src/main.rs时,我们会看到cargo fix
更改了代码:
Filename: src/main.rs 文件名:src/main.rs
fn do_something() {}
fn main() {
for _i in 0..100 {
do_something();
}
}
The for
loop variable is now named _i
, and the warning no longer appears.for
循环变量现在命名为_i
,并且警告不再出现。
You can also use the cargo fix
command to transition your code between
different Rust editions. Editions are covered in Appendix E.
您还可以使用cargo fix
命令在不同的 Rust 版本之间转换代码。版本包含在附录 E中。
More Lints with Clippy 使用 Clippy 获得更多 lints
The Clippy tool is a collection of lints to analyze your code so you can catch
common mistakes and improve your Rust code.
Clippy 工具是用于分析代码的 lint 集合,以便您可以捕获常见错误并改进 Rust 代码。
To install Clippy, enter the following:
要安装 Clippy,请输入以下内容:
$ rustup component add clippy
To run Clippy’s lints on any Cargo project, enter the following:
要在任何 Cargo 项目上运行 Clippy 的 lint,请输入以下内容:
$ cargo clippy
For example, say you write a program that uses an approximation of a
mathematical constant, such as pi, as this program does:
例如,假设您编写了一个使用数学常数(例如 pi)的近似值的程序,如下程序所示:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = 3.1415;
let r = 8.0;
println!("the area of the circle is {}", x * r * r);
}
Running cargo clippy
on this project results in this error:
在此项目上运行cargo clippy
会导致以下错误:
error: approximate value of `f{32, 64}::consts::PI` found
--> 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
This error lets you know that Rust already has a more precise PI
constant
defined, and that your program would be more correct if you used the constant
instead. You would then change your code to use the PI
constant. The
following code doesn’t result in any errors or warnings from Clippy:
此错误让您知道 Rust 已经定义了更精确的PI
常量,并且如果您使用该常量,您的程序将会更正确。然后,您可以更改代码以使用PI
常量。以下代码不会导致 Clippy 发出任何错误或警告:
Filename: src/main.rs 文件名:src/main.rs
fn main() {
let x = std::f64::consts::PI;
let r = 8.0;
println!("the area of the circle is {}", x * r * r);
}
For more information on Clippy, see its documentation.
有关 Clippy 的更多信息,请参阅其文档。
IDE Integration Using rust-analyzer
使用rust-analyzer
进行 IDE 集成
To help IDE integration, the Rust community recommends using
rust-analyzer
. This tool is a set of
compiler-centric utilities that speaks the Language Server Protocol, which is a specification for IDEs and programming languages to
communicate with each other. Different clients can use rust-analyzer
, such as
the Rust analyzer plug-in for Visual Studio Code.
为了帮助 IDE 集成,Rust 社区建议使用rust-analyzer
。该工具是一组以编译器为中心的实用程序,使用Language Server Protocolignore ,这是 IDE 和编程语言相互通信的规范。不同的客户端可以使用rust-analyzer
,例如Visual Studio Code 的 Rust 分析器插件。
Visit the rust-analyzer
project’s home page
for installation instructions, then install the language server support in your
particular IDE. Your IDE will gain abilities such as autocompletion, jump to
definition, and inline errors.
访问rust-analyzer
项目的主页忽略安装说明,然后在您的特定 IDE 中安装语言服务器支持。您的 IDE 将获得自动完成、跳转到定义和内联错误等功能。
Appendix E - Editions 附录 E - 版本
In Chapter 1, you saw that cargo new
adds a bit of metadata to your
Cargo.toml file about an edition. This appendix talks about what that means!
在第 1 章中,您看到cargo new
向您的Cargo.toml文件添加了一些有关版本的元数据。本附录讲述了这意味着什么!
The Rust language and compiler have a six-week release cycle, meaning users get
a constant stream of new features. Other programming languages release larger
changes less often; Rust releases smaller updates more frequently. After a
while, all of these tiny changes add up. But from release to release, it can be
difficult to look back and say, “Wow, between Rust 1.10 and Rust 1.31, Rust has
changed a lot!”
Rust 语言和编译器有六周的发布周期,这意味着用户可以获得源源不断的新功能。其他编程语言发布较大更改的频率较低; Rust 更频繁地发布较小的更新。一段时间后,所有这些微小的变化都会加起来。但从一个版本到另一个版本,很难回顾并说:“哇,在 Rust 1.10 和 Rust 1.31 之间,Rust 发生了很大变化!”
Every two or three years, the Rust team produces a new Rust edition. Each
edition brings together the features that have landed into a clear package with
fully updated documentation and tooling. New editions ship as part of the usual
six-week release process.
每两三年,Rust 团队就会生产一个新的 Rust版本。每个版本都将已包含在一个清晰的包中的功能与完全更新的文档和工具结合在一起。新版本作为通常的六周发布过程的一部分发布。
Editions serve different purposes for different people:
版本对不同的人有不同的用途:
- For active Rust users, a new edition brings together incremental changes into
an easy-to-understand package.
对于活跃的 Rust 用户来说,新版本将增量更改整合到一个易于理解的包中。 - For non-users, a new edition signals that some major advancements have
landed, which might make Rust worth another look.
对于非用户来说,新版本标志着一些重大进步已经落地,这可能会让 Rust 值得再次关注。 - For those developing Rust, a new edition provides a rallying point for the
project as a whole.
对于那些开发 Rust 的人来说,新版本为整个项目提供了一个集结点。
At the time of this writing, three Rust editions are available: Rust 2015, Rust
2018, and Rust 2021. This book is written using Rust 2021 edition idioms.
在撰写本文时,Rust 已有三个版本:Rust 2015、Rust 2018 和 Rust 2021。本书是使用 Rust 2021 版本习惯用法编写的。
The edition
key in Cargo.toml indicates which edition the compiler should
use for your code. If the key doesn’t exist, Rust uses 2015
as the edition
value for backward compatibility reasons.
Cargo.toml中的edition
键指示编译器应为您的代码使用哪个版本。如果该密钥不存在,出于向后兼容性的原因,Rust 将使用2015
作为版本值。
Each project can opt in to an edition other than the default 2015 edition.
Editions can contain incompatible changes, such as including a new keyword that
conflicts with identifiers in code. However, unless you opt in to those
changes, your code will continue to compile even as you upgrade the Rust
compiler version you use.
每个项目都可以选择默认 2015 版本以外的版本。版本可能包含不兼容的更改,例如包含与代码中的标识符冲突的新关键字。但是,除非您选择接受这些更改,否则即使升级您使用的 Rust 编译器版本,您的代码也将继续编译。
All Rust compiler versions support any edition that existed prior to that
compiler’s release, and they can link crates of any supported editions
together. Edition changes only affect the way the compiler initially parses
code. Therefore, if you’re using Rust 2015 and one of your dependencies uses
Rust 2018, your project will compile and be able to use that dependency. The
opposite situation, where your project uses Rust 2018 and a dependency uses
Rust 2015, works as well.
所有 Rust 编译器版本都支持该编译器发布之前存在的任何版本,并且它们可以将任何受支持版本的包链接在一起。版本更改仅影响编译器最初解析代码的方式。因此,如果您使用 Rust 2015 并且您的依赖项之一使用 Rust 2018,您的项目将编译并能够使用该依赖项。相反的情况,即您的项目使用 Rust 2018 并且依赖项使用 Rust 2015,也适用。
To be clear: most features will be available on all editions. Developers using
any Rust edition will continue to see improvements as new stable releases are
made. However, in some cases, mainly when new keywords are added, some new
features might only be available in later editions. You will need to switch
editions if you want to take advantage of such features.
需要明确的是:大多数功能将在所有版本上提供。随着新的稳定版本的发布,使用任何 Rust 版本的开发人员都将继续看到改进。然而,在某些情况下,主要是当添加新关键字时,某些新功能可能只能在以后的版本中使用。如果您想利用这些功能,则需要切换版本。
For more details, the Edition
Guide is a complete book
about editions that enumerates the differences between editions and explains
how to automatically upgrade your code to a new edition via cargo fix
.
想要了解更多详细信息,版本指南是一本关于版本的完整书籍,它列举了版本之间的差异,并解释了如何通过cargo fix
自动将代码升级到新版本。
Appendix F: Translations of the Book
附录 F:本书的翻译
For resources in languages other than English. Most are still in progress; see
the Translations label to help or let us know about a new translation!
用于英语以外语言的资源。大多数仍在进行中;请参阅翻译标签以帮助或让我们了解新翻译!
- Português (BR)
葡萄牙语(BR) - Português (PT)
葡萄牙语(PT) - 简体中文
- 正體中文 正体中文
- Українська
- Español, alternate
西班牙语,备用 - Italiano 意大利人
- Русский 俄罗斯
- 한국어 韩国人
- 日本語 日本语
- Français 法国人
- Polski 波尔斯基
- Cebuano 宿务语
- Tagalog 他加禄语
- Esperanto 世界语
- ελληνική
- Svenska 斯文斯卡
- Farsi 波斯语
- Deutsch 德语
- हिंदी
- ไทย
- Danske 丹麦语
Appendix G - How Rust is Made and “Nightly Rust”
附录 G - Rust 是如何制造的以及“夜间 Rust”
This appendix is about how Rust is made and how that affects you as a Rust
developer.
本附录介绍 Rust 的制作方式以及它对 Rust 开发人员的影响。
Stability Without Stagnation
稳定不停滞
As a language, Rust cares a lot about the stability of your code. We want
Rust to be a rock-solid foundation you can build on, and if things were
constantly changing, that would be impossible. At the same time, if we can’t
experiment with new features, we may not find out important flaws until after
their release, when we can no longer change things.
作为一种语言,Rust非常关心代码的稳定性。我们希望 Rust 成为您可以构建的坚如磐石的基础,如果事情不断变化,那是不可能的。与此同时,如果我们不能尝试新功能,我们可能直到它们发布后才发现重要的缺陷,那时我们就无法再改变事情了。
Our solution to this problem is what we call “stability without stagnation”,
and our guiding principle is this: you should never have to fear upgrading to a
new version of stable Rust. Each upgrade should be painless, but should also
bring you new features, fewer bugs, and faster compile times.
我们对这个问题的解决方案就是所谓的“稳定而不停滞”,我们的指导原则是:你永远不必担心升级到新版本的稳定 Rust。每次升级都应该是轻松的,但也应该为您带来新功能、更少的错误和更快的编译时间。
Choo, Choo! Release Channels and Riding the Trains
楚楚,楚楚!发布渠道和乘坐列车
Rust development operates on a train schedule. That is, all development is
done on the master
branch of the Rust repository. Releases follow a software
release train model, which has been used by Cisco IOS and other software
projects. There are three release channels for Rust:
Rust 开发按照火车时间表进行。也就是说,所有开发都是在 Rust 存储库的master
分支上完成的。版本遵循软件版本序列模型,该模型已被 Cisco IOS 和其他软件项目使用。 Rust 共有三个发布渠道:
- Nightly 每晚
- Beta 贝塔
- Stable 稳定的
Most Rust developers primarily use the stable channel, but those who want to
try out experimental new features may use nightly or beta.
大多数 Rust 开发人员主要使用稳定通道,但那些想要尝试实验性新功能的人可能会使用 nightly 或 beta。
Here’s an example of how the development and release process works: let’s
assume that the Rust team is working on the release of Rust 1.5. That release
happened in December of 2015, but it will provide us with realistic version
numbers. A new feature is added to Rust: a new commit lands on the master
branch. Each night, a new nightly version of Rust is produced. Every day is a
release day, and these releases are created by our release infrastructure
automatically. So as time passes, our releases look like this, once a night:
以下是开发和发布过程如何工作的示例:假设 Rust 团队正在开发 Rust 1.5。该版本发布于 2015 年 12 月,但它将为我们提供实际的版本号。 Rust 添加了一个新功能:新的提交落在master
分支上。每天晚上,都会生成一个新的 Rust 夜间版本。每天都是发布日,这些发布是由我们的发布基础设施自动创建的。随着时间的推移,我们的发布看起来像这样,每晚一次:
nightly: * - - * - - *
Every six weeks, it’s time to prepare a new release! The beta
branch of the
Rust repository branches off from the master
branch used by nightly. Now,
there are two releases:
每六周,就该准备一个新版本了! Rust 存储库的beta
分支从 nightly 使用的master
分支分支出来。现在,有两个版本:
nightly: * - - * - - *
|
beta: *
Most Rust users do not use beta releases actively, but test against beta in
their CI system to help Rust discover possible regressions. In the meantime,
there’s still a nightly release every night:
大多数 Rust 用户不会主动使用 beta 版本,而是在 CI 系统中测试 beta 版本,以帮助 Rust 发现可能的回归。与此同时,每晚仍有夜间版本:
nightly: * - - * - - * - - * - - *
|
beta: *
Let’s say a regression is found. Good thing we had some time to test the beta
release before the regression snuck into a stable release! The fix is applied
to master
, so that nightly is fixed, and then the fix is backported to the
beta
branch, and a new release of beta is produced:
假设发现了回归。幸运的是,在回归进入稳定版本之前,我们有一些时间来测试测试版!该修复应用于master
,以便 nightly 得到修复,然后该修复被反向移植到beta
分支,并生成一个新的 beta 版本:
nightly: * - - * - - * - - * - - * - - *
|
beta: * - - - - - - - - *
Six weeks after the first beta was created, it’s time for a stable release! The
stable
branch is produced from the beta
branch:
第一个测试版创建六周后,是时候发布稳定版本了! stable
分支是从beta
分支产生的:
nightly: * - - * - - * - - * - - * - - * - * - *
|
beta: * - - - - - - - - *
|
stable: *
Hooray! Rust 1.5 is done! However, we’ve forgotten one thing: because the six
weeks have gone by, we also need a new beta of the next version of Rust, 1.6.
So after stable
branches off of beta
, the next version of beta
branches
off of nightly
again:
万岁! Rust 1.5 完成了!然而,我们忘记了一件事:因为六周已经过去了,我们还需要 Rust 的下一版本 1.6 的新测试版。因此,在stable
从beta
分支出来之后,下一个版本的beta
版本又从nightly
分支出来:
nightly: * - - * - - * - - * - - * - - * - * - *
| |
beta: * - - - - - - - - * *
|
stable: *
This is called the “train model” because every six weeks, a release “leaves the
station”, but still has to take a journey through the beta channel before it
arrives as a stable release.
这被称为“火车模型”,因为每六周就会有一个版本“出站”,但在稳定版本到达之前仍然必须经过测试版通道。
Rust releases every six weeks, like clockwork. If you know the date of one Rust
release, you can know the date of the next one: it’s six weeks later. A nice
aspect of having releases scheduled every six weeks is that the next train is
coming soon. If a feature happens to miss a particular release, there’s no need
to worry: another one is happening in a short time! This helps reduce pressure
to sneak possibly unpolished features in close to the release deadline.
Rust 每六周发布一次,就像发条一样。如果您知道一个 Rust 版本的日期,您就可以知道下一个版本的日期:六周后。每六周安排一次发布的一个好处是下一趟列车即将到来。如果某个功能碰巧错过了某个特定版本,则无需担心:另一个功能很快就会出现!这有助于减少在接近发布截止日期时偷偷推出可能未完善的功能的压力。
Thanks to this process, you can always check out the next build of Rust and
verify for yourself that it’s easy to upgrade to: if a beta release doesn’t
work as expected, you can report it to the team and get it fixed before the
next stable release happens! Breakage in a beta release is relatively rare, but
rustc
is still a piece of software, and bugs do exist.
通过这个过程,您可以随时查看 Rust 的下一个版本,并亲自验证它是否很容易升级:如果 beta 版本不能按预期工作,您可以向团队报告并在发布之前修复它。下一个稳定版本即将发布! Beta 版本中的损坏相对较少,但rustc
仍然是一个软件,错误确实存在。
Maintenance time 维护时间
The Rust project supports the most recent stable version. When a new stable
version is released, the old version reaches its end of life (EOL). This means
each version is supported for six weeks.
Rust 项目支持最新的稳定版本。当新的稳定版本发布时,旧版本就达到了其生命周期(EOL)。这意味着每个版本的支持时间为六周。
Unstable Features 不稳定的功能
There’s one more catch with this release model: unstable features. Rust uses a
technique called “feature flags” to determine what features are enabled in a
given release. If a new feature is under active development, it lands on
master
, and therefore, in nightly, but behind a feature flag. If you, as a
user, wish to try out the work-in-progress feature, you can, but you must be
using a nightly release of Rust and annotate your source code with the
appropriate flag to opt in.
这个发布模型还有一个问题:不稳定的功能。 Rust 使用一种称为“功能标志”的技术来确定给定版本中启用了哪些功能。如果一个新功能正在积极开发中,它会落在master
上,因此也会在 nightly 上,但位于功能标志后面。如果您作为用户希望尝试正在进行中的功能,您可以,但您必须使用 Rust 的夜间版本,并使用适当的标志注释您的源代码以选择加入。
If you’re using a beta or stable release of Rust, you can’t use any feature
flags. This is the key that allows us to get practical use with new features
before we declare them stable forever. Those who wish to opt into the bleeding
edge can do so, and those who want a rock-solid experience can stick with
stable and know that their code won’t break. Stability without stagnation.
如果您使用的是 Rust 的测试版或稳定版,则无法使用任何功能标志。这是让我们在宣布新功能永久稳定之前能够实际使用它们的关键。那些希望选择前沿技术的人可以这样做,而那些想要坚如磐石的体验的人可以坚持使用稳定版,并且知道他们的代码不会崩溃。稳定无停滞。
This book only contains information about stable features, as in-progress
features are still changing, and surely they’ll be different between when this
book was written and when they get enabled in stable builds. You can find
documentation for nightly-only features online.
本书仅包含有关稳定功能的信息,因为正在进行的功能仍在变化,并且在编写本书时和在稳定版本中启用它们时它们肯定会有所不同。您可以在线找到仅夜间功能的文档。
Rustup and the Role of Rust Nightly
Rustup 和 Rust Nightly 的作用
Rustup makes it easy to change between different release channels of Rust, on a
global or per-project basis. By default, you’ll have stable Rust installed. To
install nightly, for example:
Rustup 可以轻松地在全局或每个项目的基础上在 Rust 的不同发布渠道之间进行更改。默认情况下,您将安装稳定的 Rust。要每晚安装,例如:
$ rustup toolchain install nightly
You can see all of the toolchains (releases of Rust and associated
components) you have installed with rustup
as well. Here’s an example on one
of your authors’ Windows computer:
您还可以查看使用rustup
安装的所有工具链(Rust 和相关组件的版本)。以下是您的一位作者的 Windows 计算机上的示例:
> rustup toolchain list
stable-x86_64-pc-windows-msvc (default)
beta-x86_64-pc-windows-msvc
nightly-x86_64-pc-windows-msvc
As you can see, the stable toolchain is the default. Most Rust users use stable
most of the time. You might want to use stable most of the time, but use
nightly on a specific project, because you care about a cutting-edge feature.
To do so, you can use rustup override
in that project’s directory to set the
nightly toolchain as the one rustup
should use when you’re in that directory:
如您所见,稳定的工具链是默认的。大多数 Rust 用户大部分时间都使用 stable。您可能大部分时间都想使用 stable,但在特定项目上使用 nightly,因为您关心尖端功能。为此,您可以在该项目的目录中使用rustup override
将每晚工具链设置为您在该目录中时应使用的rustup
:
$ cd ~/projects/needs-nightly
$ rustup override set nightly
Now, every time you call rustc
or cargo
inside of
~/projects/needs-nightly, rustup
will make sure that you are using nightly
Rust, rather than your default of stable Rust. This comes in handy when you
have a lot of Rust projects!
现在,每次你在~/projects/needs-nightly中调用rustc
或cargo
时, rustup
都会确保你使用的是 nightly Rust,而不是默认的稳定 Rust。当您有很多 Rust 项目时,这会派上用场!
The RFC Process and Teams
RFC 流程和团队
So how do you learn about these new features? Rust’s development model follows
a Request For Comments (RFC) process. If you’d like an improvement in Rust,
you can write up a proposal, called an RFC.
那么如何了解这些新功能呢? Rust 的开发模型遵循征求意见(RFC)流程。如果您想改进 Rust,您可以编写一个提案,称为 RFC。
Anyone can write RFCs to improve Rust, and the proposals are reviewed and
discussed by the Rust team, which is comprised of many topic subteams. There’s
a full list of the teams on Rust’s
website, which includes teams for
each area of the project: language design, compiler implementation,
infrastructure, documentation, and more. The appropriate team reads the
proposal and the comments, writes some comments of their own, and eventually,
there’s consensus to accept or reject the feature.
任何人都可以编写 RFC 来改进 Rust,并且由许多主题子团队组成的 Rust 团队会审查和讨论这些提案。 Rust 网站上有完整的团队列表,其中包括项目各个领域的团队:语言设计、编译器实现、基础设施、文档等等。适当的团队阅读提案和评论,编写自己的一些评论,最终达成接受或拒绝该功能的共识。
If the feature is accepted, an issue is opened on the Rust repository, and
someone can implement it. The person who implements it very well may not be the
person who proposed the feature in the first place! When the implementation is
ready, it lands on the master
branch behind a feature gate, as we discussed
in the “Unstable Features” section.
如果该功能被接受,则会在 Rust 存储库上打开一个问题,并且有人可以实现它。实现得很好的人可能不是最初提出该功能的人!当实现准备就绪时,它会落在功能门后面的master
分支上,正如我们在“不稳定功能”忽略部分中讨论的那样。
After some time, once Rust developers who use nightly releases have been able
to try out the new feature, team members will discuss the feature, how it’s
worked out on nightly, and decide if it should make it into stable Rust or not.
If the decision is to move forward, the feature gate is removed, and the
feature is now considered stable! It rides the trains into a new stable release
of Rust.
一段时间后,一旦使用 nightly 版本的 Rust 开发人员能够尝试新功能,团队成员将讨论该功能、它在 nightly 上的运行情况,并决定是否应该将其纳入稳定的 Rust。如果决定继续前进,则删除功能门,并且该功能现在被认为是稳定的!它伴随着 Rust 进入新的稳定版本。