Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust 程序设计语言 (The Rust Programming Language)


x-i18n: generated_at: “2026-03-01T15:09:14Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: d7966031794dd1473247c82eeaba3fc9b5a32fa32ec4817686e9d9a6bebbbf48 source_path: title-page.md workflow: 16

Rust 编程语言 (The Rust Programming Language)

The Rust Programming Language

作者:Steve Klabnik、Carol Nichols 和 Chris Krycho,以及来自 Rust 社区的贡献者

by Steve Klabnik, Carol Nichols, and Chris Krycho, with contributions from the Rust Community

本书版本假设你使用的是 Rust 1.90.0(2025-09-18 发布)或更高版本,并在所有项目的 Cargo.toml 文件中设置了 edition = "2024" ,以配置它们使用 Rust 2024 版本 (Edition) 的惯用法。关于安装或更新 Rust 的说明,请参阅第 1 章的“安装”部分,关于版本的详细信息,请参阅附录 E

This version of the text assumes you’re using Rust 1.90.0 (released 2025-09-18) or later with edition = "2024" in the Cargo.toml file of all projects to configure them to use Rust 2024 Edition idioms. See the “Installation” section of Chapter 1 for instructions on installing or updating Rust, and see Appendix E for information on editions.

HTML 格式可以在线访问 https://doc.rust-lang.org/stable/book/,也可以在通过 rustup 安装的 Rust 中离线访问;运行 rustup doc --book 即可打开。

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.

同时也提供了一些社区翻译版本

Several community translations are also available.

本书由 No Starch Press 出版了纸质版和电子书格式

This text is available in paperback and ebook format from No Starch Press.

🚨 想要更具互动性的学习体验吗?试试另一个版本的 Rust 教程,它具有以下特色:测验、高亮显示、可视化效果等https://rust-book.cs.brown.edu

🚨 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

前言 (Foreword)


x-i18n: generated_at: “2026-03-01T15:07:33Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: d4e3371ec06389a6125a11b34bf14db8f12ec608dd93e49b4ae92c5e8293978a source_path: foreword.md workflow: 16

前言 (Foreword)

Foreword

Rust 编程语言在短短几年内走过了漫长的道路,从一小群初生的爱好者社区的创建和孵化,发展成为世界上最受喜爱和最受追捧的编程语言之一。回首往事,Rust 的力量和前景必然会引起关注并在系统编程领域站稳脚跟。而不可预见的是全球范围内兴趣和创新的增长,它们渗透到开源社区,并催化了跨行业的广泛采用。

The Rust programming language has come a long way in a few short years, from its creation and incubation by a small and nascent community of enthusiasts, to becoming one of the most loved and in-demand programming languages in the world. Looking back, it was inevitable that the power and promise of Rust would turn heads and gain a foothold in systems programming. What was not inevitable was the global growth in interest and innovation that permeated through open source communities and catalyzed wide-scale adoption across industries.

此时此刻,我们可以轻而易举地指出 Rust 所提供的精彩特性来解释这种兴趣和采用的爆发。在众多优秀的特性中,谁不想要内存安全,“以及”快速的性能,“以及”友好的编译器,“以及”出色的工具呢?你今天看到的 Rust 语言结合了系统编程领域多年的研究成果与一个充满活力和激情的社区的实践智慧。这门语言的设计初衷明确,制作精良,为开发者提供了一个更易于编写安全、快速且可靠代码的工具。

At this point in time, it is easy to point to the wonderful features that Rust has to offer to explain this explosion in interest and adoption. Who doesn’t want memory safety, and fast performance, and a friendly compiler, and great tooling, among a host of other wonderful features? The Rust language you see today combines years of research in systems programming with the practical wisdom of a vibrant and passionate community. This language was designed with purpose and crafted with care, offering developers a tool that makes it easier to write safe, fast, and reliable code.

但让 Rust 真正与众不同的是它的根基,即赋予你(用户)实现目标的能力。这是一门希望你成功的语言,赋权原则贯穿于构建、维护和倡导这门语言的社区核心。自本权威著作的上一个版本以来,Rust 进一步发展成为一门真正的全球性且值得信赖的语言。Rust 项目现在得到了 Rust 基金会的有力支持,该基金会还投资于关键计划,以确保 Rust 的安全、稳定和可持续发展。

But what makes Rust truly special is its roots in empowering you, the user, to achieve your goals. This is a language that wants you to succeed, and the principle of empowerment runs through the core of the community that builds, maintains, and advocates for this language. Since the previous edition of this definitive text, Rust has further developed into a truly global and trusted language. The Rust Project is now robustly supported by the Rust Foundation, which also invests in key initiatives to ensure that Rust is secure, stable, and sustainable.

本版《Rust 权威指南》是一次全面的更新,反映了该语言多年来的演进并提供了宝贵的新信息。但这不仅仅是一本语法和库的指南——它还是一份邀请,邀请你加入一个重视质量、性能和周密设计的社区。无论你是打算初次探索 Rust 的资深开发者,还是想要精进技能的资深 Rustacean,本版都为每个人提供了参考。

This edition of The Rust Programming Language is a comprehensive update, reflecting the language’s evolution over the years and providing valuable new information. But it is not just a guide to syntax and libraries—it’s an invitation to join a community that values quality, performance, and thoughtful design. Whether you’re a seasoned developer looking to explore Rust for the first time or an experienced Rustacean looking to refine your skills, this edition offers something for everyone.

Rust 的旅程是一段协作、学习和迭代的过程。该语言及其生态系统的成长是其背后充满活力且多元化的社区的直接体现。从核心语言设计者到业余贡献者,成千上万开发者的贡献共同造就了 Rust 这一独特且强大的工具。拿起这本书,你不仅是在学习一门新的编程语言,你还在加入一场让软件变得更好、更安全、开发过程更愉快的运动。

The Rust journey has been one of collaboration, learning, and iteration. The growth of the language and its ecosystem is a direct reflection of the vibrant, diverse community behind it. The contributions of thousands of developers, from core language designers to casual contributors, are what make Rust such a unique and powerful tool. By picking up this book, you’re not just learning a new programming language—you’re joining a movement to make software better, safer, and more enjoyable to work with.

欢迎加入 Rust 社区!

Welcome to the Rust community!

— Bec Rumbul,Rust 基金会执行董事

  • Bec Rumbul, Executive Director of the Rust Foundation

导言 (Introduction)


x-i18n: generated_at: “2026-03-01T09:17:47Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 2eba711175d633b5c6bf2585bcb6382fef4eec2b39f18689a1a2b9134dd9d273 source_path: ch00-00-introduction.md workflow: 16

导言 (Introduction)

Introduction

注意:本书的版本与 No Starch Press 出版的纸质书和电子书 《Rust 程序设计语言》(The Rust Programming Language) 相同。

Note: This edition of the book is the same as The Rust Programming Language available in print and ebook format from No Starch Press.

欢迎阅读《Rust 程序设计语言》(The Rust Programming Language),这是一本关于 Rust 的入门书籍。Rust 程序设计语言可以帮助你编写更快、更可靠的软件。在编程语言设计中,高级的人机工程学 (ergonomics) 和底层的控制力往往是相互矛盾的;Rust 挑战了这种冲突。通过平衡强大的技术能力和卓越的开发者体验,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 (Who Rust Is For)

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.

开发团队 (Teams of Developers)

Teams of Developers

事实证明,Rust 是一个高效的工具,可用于具有不同系统编程知识水平的大型开发团队之间的协作。底层代码容易出现各种微妙的 Bug,在大多数其他语言中,这些 Bug 只能通过大量的测试和经验丰富的开发者进行仔细的代码审查才能发现。在 Rust 中,编译器扮演了“守门员”的角色,它会拒绝编译包含这些难以捉摸的 Bug(包括并发 Bug)的代码。通过与编译器配合工作,团队可以将时间集中在程序的逻辑上,而不是去追踪 Bug。

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 only be caught 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 its time focusing on the program’s logic rather than chasing down bugs.

Rust 还为系统编程领域带来了现代化的开发者工具:

Rust also brings contemporary developer tools to the systems programming world:

  • Cargo 是内置的依赖管理器和构建工具,它使得在 Rust 生态系统中添加、编译和管理依赖项变得轻松且一致。
  • Cargo, the included dependency manager and build tool, makes adding, compiling, and managing dependencies painless and consistent across the Rust ecosystem.
  • rustfmt 格式化工具确保了开发者之间统一的代码风格。
  • The rustfmt formatting tool ensures a consistent coding style across developers.
  • Rust 语言服务器 (Rust Language Server) 为集成开发环境 (IDE) 集成提供支持,实现代码补全和内联错误消息。
  • The Rust Language Server powers integrated development environment (IDE) integration for code completion and inline error messages.

通过使用 Rust 生态系统中的这些以及其他工具,开发者在编写系统级代码时可以保持高效。

By using these and other tools in the Rust ecosystem, developers can be productive while writing systems-level code.

学生 (Students)

Students

Rust 适用于学生和那些对学习系统概念感兴趣的人。通过使用 Rust,许多人学习了诸如操作系统开发之类的课题。社区非常友好,乐于回答学生的问题。通过像本书这样的努力,Rust 团队希望让更多人(特别是编程新手)能够更容易地理解系统概念。

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 students’ 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.

公司 (Companies)

Companies

成百上千家大小公司在生产环境中使用 Rust 完成各种任务,包括命令行工具、Web 服务、DevOps 工具、嵌入式设备、音视频分析和转码、加密货币、生物信息学、搜索引擎、物联网应用、机器学习,甚至 Firefox 浏览器的主要部分。

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.

开源开发者 (Open Source Developers)

Open Source Developers

Rust 适用于那些想要构建 Rust 编程语言、社区、开发工具和库的人。我们非常欢迎你为 Rust 语言做出贡献。

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.

重视速度与稳定性的开发者 (People Who Value Speed and Stability)

People Who Value Speed and Stability

Rust 适用于那些渴望语言具有速度和稳定性的开发者。所谓速度,我们既指 Rust 代码运行的速度,也指 Rust 让你编写程序的效率。Rust 编译器的检查确保了在添加特性和进行重构时的稳定性。这与那些没有这些检查的语言中脆弱的遗留代码形成鲜明对比,开发者往往不敢修改它们。通过追求零成本抽象 (zero-cost abstractions)——即编译成与手动编写的代码一样快的底层代码的高级特性——Rust 致力于让安全的代码同样也是快速的代码。

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,看看它的选择是否适合你。

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.

本书读者对象 (Who This Book Is For)

Who This Book Is For

本书假设你已经用另一种编程语言写过代码,但并不对具体是哪种语言做任何假设。我们努力使这些内容能够被具有各种编程背景的人广泛接受。我们不会花很多时间讨论什么是编程,或者如何思考编程。如果你完全是编程新手,阅读专门提供编程入门的书籍会对你更有帮助。

This book assumes that you’ve written code in another programming language, but it 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)

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.

你会在本书中发现两种章节:概念章节和项目章节。在概念章节中,你将学习 Rust 的某个方面。在项目章节中,我们将一起构建小程序,应用你目前学到的知识。第 2 章、第 12 章和第 21 章是项目章节;其余的是概念章节。

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. Chapter 2, Chapter 12, and Chapter 21 are project chapters; the rest are concept chapters.

第 1 章 解释了如何安装 Rust,如何编写“Hello, world!”程序,以及如何使用 Cargo(Rust 的包管理器和构建工具)。第 2 章 是编写 Rust 程序的动手实践入门,让你构建一个猜数字游戏。在这里,我们从宏观层面介绍概念,后面的章节将提供额外的细节。如果你想马上动手尝试,第 2 章就是为你准备的。如果你是一个特别严谨的学习者,更喜欢在进入下一步之前学习每一个细节,你可能想跳过第 2 章,直接阅读 第 3 章,该章涵盖了与其他编程语言相似的 Rust 特性;然后,当你想要开展一个应用所学细节的项目时,可以再回到第 2 章。

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. 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, which covers Rust features that are similar to those of other programming languages; then, you can return to Chapter 2 when you’d like to work on a project applying the details you’ve learned.

第 4 章 中,你将学习 Rust 的所有权系统。第 5 章 讨论结构体 (structs) 和方法 (methods)。第 6 章 涵盖枚举 (enums)、match 表达式,以及 if letlet...else 控制流结构。你将使用结构体和枚举来创建自定义类型。

In Chapter 4, you’ll learn about Rust’s ownership system. Chapter 5 discusses structs and methods. Chapter 6 covers enums, match expressions, and the if let and let...else control flow constructs. You’ll use structs and enums to make custom types.

第 7 章 中,你将学习 Rust 的模块系统,以及用于组织代码及其公共应用编程接口 (API) 的私有性规则。第 8 章 讨论标准库提供的一些常见集合数据结构:Vector、String 和哈希映射 (hash maps)。第 9 章 探索 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: vectors, strings, and hash maps. Chapter 9 explores Rust’s error-handling philosophy and techniques.

第 10 章 深入研究泛型 (generics)、Traits 和生命周期 (lifetimes),它们赋予你定义适用于多种类型的代码的能力。第 11 章 全面介绍测试,即使有 Rust 的安全保证,测试对于确保程序逻辑正确也是必要的。在 第 12 章 中,我们将实现 grep 命令行工具的功能子集,用于在文件中搜索文本。为此,我们将使用前面章节中讨论的许多概念。

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 that 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.

第 13 章 探索闭包 (closures) 和迭代器 (iterators):这些 Rust 特性源自函数式编程语言。在 第 14 章 中,我们将更深入地研究 Cargo,并讨论与他人分享你的库的最佳实践。第 15 章 讨论标准库提供的智能指针以及实现其功能的 Traits。

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.

第 16 章 中,我们将介绍并发编程的不同模型,并讨论 Rust 如何帮助你无畏地进行多线程编程。在 第 17 章 中,我们在此基础上探索 Rust 的 async 和 await 语法,以及任务 (tasks)、Futures 和 Streams,以及它们所实现的轻量级并发模型。

In Chapter 16, we’ll walk through different models of concurrent programming and talk about how Rust helps you program in multiple threads fearlessly. In Chapter 17, we build on that by exploring Rust’s async and await syntax, along with tasks, futures, and streams, and the lightweight concurrency model they enable.

第 18 章 探讨 Rust 惯用法如何与你可能熟悉的面向对象编程原则进行对比。第 19 章 是关于模式和模式匹配的参考,它们是在整个 Rust 程序中表达想法的强大方式。第 20 章 包含了一系列感兴趣的高级主题,包括不安全 Rust (unsafe Rust)、宏 (macros),以及更多关于生命周期、Traits、类型、函数和闭包的内容。

Chapter 18 looks at how Rust idioms compare to object-oriented programming principles you might be familiar with. Chapter 19 is a reference on patterns and pattern matching, which are powerful ways of expressing ideas throughout Rust programs. Chapter 20 contains a smorgasbord of advanced topics of interest, including unsafe Rust, macros, and more about lifetimes, traits, types, functions, and closures.

第 21 章 中,我们将完成一个项目,在其中我们将实现一个底层的多线程 Web 服务器!

In Chapter 21, we’ll complete a project in which we’ll implement a low-level multithreaded web server!

最后,一些附录以更类似参考资料的格式包含了关于该语言的有用信息。附录 A 涵盖 Rust 的关键字,附录 B 涵盖 Rust 的运算符和符号,附录 C 涵盖标准库提供的可派生 Traits,附录 D 涵盖一些实用的开发工具,附录 E 解释 Rust 版本。在 附录 F 中,你可以找到本书的翻译版,在 附录 G 中,我们将介绍 Rust 是如何开发的以及什么是每夜版 (nightly) Rust。

Finally, some appendixes 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.

阅读本书没有错误的方式:如果你想跳着看,那就去吧!如果你感到任何困惑,可能需要跳回前面的章节。但请采取任何适合你的方式。

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.

学习 Rust 过程中一个重要的部分是学习如何阅读编译器显示的错误消息:这些将引导你编写出可工作的代码。因此,我们将提供许多无法编译的示例,以及编译器在每种情况下会显示给你的错误消息。请记住,如果你输入并运行一个随机示例,它可能无法编译!请确保阅读上下文文字,以查看你尝试运行的示例是否旨在报错。在大多数情况下,我们会引导你获得任何无法编译的代码的正确版本。费里斯 (Ferris) 也会帮助你区分那些不打算运行的代码:

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. In most situations, we’ll lead you to the correct version of any code that doesn’t compile. Ferris will also help you distinguish code that isn’t meant to work:

费里斯 (Ferris)含义 (Meaning)
Ferris with a question mark这段代码无法编译! (This code does not compile!)
Ferris throwing up their hands这段代码会发生 Panic! (This code panics!)
Ferris with one claw up, shrugging这段代码不会产生预期的行为。 (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)

Source Code

生成本书的源文件可以在 GitHub 上找到。

The source files from which this book is generated can be found on GitHub.

入门指南 (Getting Started)


x-i18n: generated_at: “2026-03-01T09:18:06Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 152b24e7ca44a75c8b092d0c4eabce84ee82224978bf666ef627799e97f922db source_path: ch01-00-getting-started.md workflow: 16

入门指南 (Getting Started)

Getting Started

让我们开始你的 Rust 旅程吧!虽然有很多知识需要学习,但每一次旅程都有一个起点。在本章中,我们将讨论:

Let’s start your Rust journey! There’s a lot to learn, but every journey starts somewhere. In this chapter, we’ll discuss:

  • 在 Linux、macOS 和 Windows 上安装 Rust
  • Installing Rust on Linux, macOS, and Windows
  • 编写一个打印 Hello, world! 的程序
  • Writing a program that prints Hello, world!
  • 使用 Rust 的包管理器和构建系统 cargo
  • Using cargo, Rust’s package manager and build system

安装 (Installation)


x-i18n: generated_at: “2026-03-01T09:19:55Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 9a6739066ce1229128e99f343fc7e1e7648107dc89456a46683612c50247f118 source_path: ch01-01-installation.md workflow: 16

安装 (Installation)

Installation

第一步是安装 Rust。我们将通过 rustup 下载 Rust,这是一个用于管理 Rust 版本和相关工具的命令行工具。下载过程需要互联网连接。

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.

注意:如果由于某种原因你不想使用 rustup,请查看其他 Rust 安装方法页面以获取更多选项。

Note: If you prefer not to use rustup for some reason, please see the Other Rust Installation Methods page for more options.

以下步骤将安装最新稳定版本的 Rust 编译器。Rust 的稳定性保证确保了书中所有能编译的示例在更新的 Rust 版本中也能继续编译。不同版本之间的输出可能会略有不同,因为 Rust 经常改进错误消息和警告。换句话说,你使用这些步骤安装的任何更新的稳定版 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.

命令行表示法 (Command Line Notation)

Command Line Notation

在本章和全书中,我们将展示一些在终端中使用的命令。你应该在终端中输入的行都以 $ 开头。你不需要输入 $ 字符;它是显示的命令行提示符,用于指示每个命令的开始。不以 $ 开头的行通常显示前一个命令的输出。此外,针对 PowerShell 的示例将使用 > 而不是 $

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 $.

在 Linux 或 macOS 上安装 rustup (Installing rustup on Linux or macOS)

Installing rustup on Linux or macOS

如果你使用的是 Linux 或 macOS,请打开终端并输入以下命令:

If you’re using Linux or macOS, open a terminal and enter the following command:

$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

该命令下载一个脚本并开始安装 rustup 工具,它会安装最新稳定版本的 Rust。可能会提示你输入密码。如果安装成功,将出现以下行:

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:

Rust is installed now. Great!

你还需要一个链接器 (linker),它是 Rust 用于将其编译输出连接成一个文件的程序。你很可能已经有一个了。如果你遇到链接器错误,你应该安装一个 C 编译器 (C compiler),它通常会包含一个链接器。C 编译器也很有用,因为一些常用的 Rust 包依赖于 C 代码,因此需要 C 编译器。

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.

在 macOS 上,你可以通过运行以下命令获取 C 编译器:

On macOS, you can get a C compiler by running:

$ xcode-select --install

Linux 用户通常应根据其发行版的文档安装 GCC 或 Clang。例如,如果你使用 Ubuntu,可以安装 build-essential 包。

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.

在 Windows 上安装 rustup (Installing rustup on Windows)

Installing rustup on Windows

在 Windows 上,请访问 https://www.rust-lang.org/tools/install 并按照安装 Rust 的说明进行操作。在安装过程中的某个时刻,系统会提示你安装 Visual Studio。这提供了链接器和编译程序所需的原生库。如果你在这一步需要更多帮助,请参阅 https://rust-lang.github.io/rustup/installation/windows-msvc.html

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.

本书的其余部分使用的命令在 cmd.exe 和 PowerShell 中均适用。如果有特定的差异,我们会解释使用哪一个。

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.

故障排除 (Troubleshooting)

Troubleshooting

要检查你是否正确安装了 Rust,请打开一个 Shell 并输入这一行:

To check whether you have Rust installed correctly, open a shell and enter this line:

$ 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)

如果你看到了这些信息,说明你已经成功安装了 Rust!如果你没有看到这些信息,请按照以下步骤检查 Rust 是否在你的 %PATH% 系统变量中。

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.

在 Windows CMD 中,使用:

In Windows CMD, use:

> echo %PATH%

在 PowerShell 中,使用:

In PowerShell, use:

> echo $env:Path

在 Linux 和 macOS 中,使用:

In Linux and macOS, use:

$ echo $PATH

如果一切都正确但 Rust 仍然无法工作,有很多地方可以寻求帮助。在 社区页面 上查找如何与其他 Rustaceans(我们自称的一个有趣的昵称)取得联系。

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.

更新与卸载 (Updating and Uninstalling)

Updating and Uninstalling

一旦通过 rustup 安装了 Rust,更新到新发布的版本就很简单。在 Shell 中运行以下更新脚本:

Once Rust is installed via rustup, updating to a newly released version is easy. From your shell, run the following update script:

$ rustup update

要卸载 Rust 和 rustup,请在 Shell 中运行以下卸载脚本:

To uninstall Rust and rustup, run the following uninstall script from your shell:

$ rustup self uninstall

阅读本地文档 (Reading the Local Documentation)

Reading the Local Documentation

Rust 的安装还包括一份文档的本地副本,以便你可以离线阅读。运行 rustup doc 即可在浏览器中打开本地文档。

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.

每当标准库提供一个类型或函数,而你不确定它的作用或如何使用它时,请查阅应用编程接口 (API) 文档来查找答案!

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!

使用文本编辑器和 IDE (Using Text Editors and IDEs)

Using Text Editors and IDEs

本书不假设你使用什么工具来编写 Rust 代码。几乎任何文本编辑器都可以胜任!但是,许多文本编辑器和集成开发环境 (IDE) 都有对 Rust 的内置支持。你始终可以在 Rust 网站的 工具页面 上找到许多编辑器和 IDE 的相当新的列表。

This book makes no assumptions about what tools you use to author Rust code. Just about any text editor will get the job done! However, many text editors and integrated development environments (IDEs) have built-in support for Rust. You can always find a fairly current list of many editors and IDEs on the tools page on the Rust website.

离线使用本书 (Working Offline with This Book)

Working Offline with This Book

在几个示例中,我们将使用标准库之外的 Rust 包。要完成这些示例,你既需要互联网连接,也需要提前下载这些依赖项。要提前下载这些依赖项,可以运行以下命令。(我们稍后会详细解释 cargo 是什么以及每个命令的作用。)

In several examples, we will use Rust packages beyond the standard library. To work through those examples, you will either need to have an internet connection or to have downloaded those dependencies ahead of time. To download the dependencies ahead of time, you can run the following commands. (We’ll explain what cargo is and what each of these commands does in detail later.)

$ cargo new get-dependencies
$ cd get-dependencies
$ cargo add rand@0.8.5 trpl@0.2.0

这将缓存这些包的下载内容,因此你稍后无需下载它们。一旦运行了此命令,就不需要保留 get-dependencies 文件夹了。如果你运行了此命令,则可以在本书其余部分的所有 cargo 命令中使用 --offline 标志,以使用这些缓存版本而不是尝试使用网络。

This will cache the downloads for these packages so you will not need to download them later. Once you have run this command, you do not need to keep the get-dependencies folder. If you have run this command, you can use the --offline flag with all cargo commands in the rest of the book to use these cached versions instead of attempting to use the network.

你好,世界! (Hello, World!)


x-i18n: generated_at: “2026-03-01T09:20:21Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 645189892417cf5431fafb29c4e9b413db2c8cb07fb99e993efaf3c3e9d7a143 source_path: ch01-02-hello-world.md workflow: 16

你好,世界! (Hello, World!)

Hello, World!

现在你已经安装了 Rust,是时候编写你的第一个 Rust 程序了。学习一门新语言时,编写一个在屏幕上打印 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 对你的编辑器、工具或代码存放位置没有特殊要求,所以如果你更喜欢使用 IDE 而不是命令行,请随意使用你喜欢的 IDE。现在许多 IDE 都有一定程度的 Rust 支持;详情请查看 IDE 的文档。Rust 团队一直致力于通过 rust-analyzer 提供出色的 IDE 支持。更多详情请参见附录 D

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 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.

项目目录设置 (Project Directory Setup)

Project Directory Setup

首先,你要创建一个目录来存储你的 Rust 代码。Rust 并不关心你的代码存放在哪里,但对于本书中的练习和项目,我们建议在你的主目录中创建一个 projects 目录,并将所有项目都存放在那里。

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.

打开终端并输入以下命令,在 projects 目录中创建一个 projects 目录和一个用于“Hello, world!”项目的目录。

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.

对于 Linux、macOS 和 Windows 上的 PowerShell,请输入:

For Linux, macOS, and PowerShell on Windows, enter this:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world

对于 Windows CMD,请输入:

For Windows CMD, enter this:

> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir hello_world
> cd hello_world

Rust 程序基础 (Rust Program Basics)

Rust Program Basics

接下来,创建一个新的源文件并将其命名为 main.rs。Rust 文件总是以 .rs 扩展名结尾。如果你的文件名中使用了多个单词,惯例是使用下划线来分隔它们。例如,使用 hello_world.rs 而不是 helloworld.rs

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 文件,并输入示例 1-1 中的代码。

Now open the main.rs file you just created and enter the code in Listing 1-1.

fn main() {
    println!("Hello, world!");
}

保存文件并回到 ~/projects/hello_world 目录下的终端窗口。在 Linux 或 macOS 上,输入以下命令来编译并运行该文件:

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:

$ rustc main.rs
$ ./main
Hello, world!

在 Windows 上,输入命令 .\main 而不是 ./main

On Windows, enter the command .\main instead of ./main:

> rustc main.rs
> .\main
Hello, world!

无论你使用的是什么操作系统,字符串 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! 确实打印出来了,恭喜你!你正式编写了一个 Rust 程序。这让你成为了一名 Rust 程序员——欢迎加入!

If Hello, world! did print, congratulations! You’ve officially written a Rust program. That makes you a Rust programmer—welcome!

Rust 程序的解剖 (The Anatomy of a Rust Program)

The Anatomy of a Rust Program

让我们详细回顾一下这个 “Hello, world!” 程序。这是拼图的第一块:

Let’s review this “Hello, world!” program in detail. Here’s the first piece of the puzzle:

fn main() {

}

这些行定义了一个名为 main 的函数。main 函数是特殊的:它是每个可执行 Rust 程序中首先运行的代码。在这里,第一行声明了一个名为 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 (()).

函数体包裹在 {} 中。Rust 要求所有函数体都要用花括号括起来。良好的风格是将左花括号与函数声明放在同一行,并在两者之间添加一个空格。

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 项目中坚持统一的标准风格,可以使用名为 rustfmt 的自动格式化工具将代码格式化为特定的风格(有关 rustfmt 的更多信息请参见附录 D)。Rust 团队已将此工具与标准 Rust 发行版(如 rustc)一并提供,因此它应该已经安装在你的电脑上了!

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!

main 函数的函数体包含以下代码:

The body of the main function holds the following code:

#![allow(unused)]
fn main() {
println!("Hello, world!");
}

这一行完成了这个小程序中的所有工作:它将文本打印到屏幕上。这里有三个重要的细节需要注意。

This line does all the work in this little program: It prints text to the screen. There are three important details to notice here.

首先,println! 调用了一个 Rust 宏 (macro)。如果它调用的是一个函数,它将被输入为 println(没有 !)。Rust 宏是一种编写代码的方法,它通过生成代码来扩展 Rust 语法,我们将在 第 20 章 中更详细地讨论它们。现在,你只需要知道使用 ! 意味着你正在调用一个宏而不是一个普通的函数,并且宏并不总是遵循与函数相同的规则。

First, println! calls a Rust macro. If it had called a function instead, it would be entered as println (without the !). Rust macros are a way to write code that generates code to extend Rust syntax, and we’ll discuss them in more detail in Chapter 20. 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.

其次,你看到了 "Hello, world!" 字符串。我们将这个字符串作为参数传递给 println!,然后该字符串被打印到屏幕上。

Second, you see the "Hello, world!" string. We pass this string as an argument to println!, and the string is printed to the screen.

第三,我们以分号 (;) 结尾,这表示该表达式已经结束,下一个表达式准备开始。大多数 Rust 代码行都以分号结尾。

Third, 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.

编译与运行是分开的步骤 (Compilation and Execution)

Compilation and Execution

你刚刚运行了一个新创建的程序,所以让我们检查一下这个过程中的每个步骤。

You’ve just run a newly created program, so let’s examine each step in the process.

在运行 Rust 程序之前,必须使用 Rust 编译器对其进行编译,方法是输入 rustc 命令并传递源文件的名称,如下所示:

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:

$ rustc main.rs

如果你有 C 或 C++ 背景,你会注意到这与 gccclang 类似。成功编译后,Rust 会输出一个二进制可执行文件。

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.

在 Linux、macOS 和 Windows 上的 PowerShell 上,你可以通过在 Shell 中输入 ls 命令来查看该可执行文件:

On Linux, macOS, and PowerShell on Windows, you can see the executable by entering the ls command in your shell:

$ ls
main  main.rs

在 Linux 和 macOS 上,你会看到两个文件。在 Windows 的 PowerShell 上,你会看到与使用 CMD 相同的三个文件。在 Windows 的 CMD 上,你会输入以下内容:

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:

> dir /B %= the /B option says to only show the file names =%
main.exe
main.pdb
main.rs

这显示了带有 .rs 扩展名的源代码文件、可执行文件(在 Windows 上是 main.exe,但在所有其他平台上是 main),以及在使用 Windows 时,包含调试信息且扩展名为 .pdb 的文件。从这里,你可以像这样运行 mainmain.exe 文件:

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:

$ ./main # or .\main on Windows

如果你的 main.rs 是你的 “Hello, world!” 程序,这一行将在你的终端上打印 Hello, world!

If your main.rs is your “Hello, world!” program, this line prints Hello, world! to your terminal.

如果你更熟悉 Ruby、Python 或 JavaScript 等动态语言,你可能不习惯将编译和运行程序作为分开的步骤。Rust 是一种预先编译 (ahead-of-time compiled) 的语言,这意味着你可以编译一个程序并将可执行文件交给其他人,即使他们没有安装 Rust 也可以运行它。如果你给别人一个 .rb.py.js 文件,他们需要分别安装 Ruby、Python 或 JavaScript 的实现。但在那些语言中,你只需要一个命令即可编译并运行你的程序。在语言设计中,一切都是一种权衡。

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.

对于简单的程序,仅使用 rustc 编译就可以了,但随着项目的增长,你会希望管理所有选项并让共享代码变得容易。接下来,我们将向你介绍 Cargo 工具,它将帮助你编写现实世界的 Rust 程序。

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.

你好,Cargo! (Hello, Cargo!)


x-i18n: generated_at: “2026-03-01T09:26:46Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 61369f359b84b646fc3773eb569a26bc18ba6edb4cf2be06a84472c7054c0e39 source_path: ch01-03-hello-cargo.md workflow: 16

你好,Cargo! (Hello, Cargo!)

Hello, Cargo!

Cargo 是 Rust 的构建系统和包管理器。大多数 Rust 开发人员 (Rustaceans) 使用这个工具来管理他们的 Rust 项目,因为 Cargo 会为你处理很多任务,例如构建代码、下载代码依赖的库以及构建这些库。(我们将代码需要的库称为依赖项 (dependencies)。)

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.)

最简单的 Rust 程序,比如我们到目前为止编写的程序,没有任何依赖项。如果我们用 Cargo 构建 “Hello, world!” 项目,它只会使用 Cargo 中处理构建代码的部分。随着你编写更复杂的 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。如果你使用了 “安装” 章节中讨论的官方安装程序,那么 Cargo 会随 Rust 一起安装。如果你通过其他方式安装了 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:

$ cargo --version
$ cargo --version

如果你看到版本号,说明你已经安装了!如果你看到错误,例如 command not found,请查看你的安装方法的文档,以确定如何单独安装 Cargo。

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.

使用 Cargo 创建项目 (Creating a Project with Cargo)

Creating a Project with Cargo

让我们使用 Cargo 创建一个新项目,看看它与我们最初的 “Hello, world!” 项目有何不同。导航回到你的 projects 目录(或者你决定存储代码的任何地方)。然后,在任何操作系统上运行以下命令:

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 new hello_cargo
$ cd hello_cargo
$ cargo new hello_cargo
$ cd hello_cargo

第一个命令创建了一个名为 hello_cargo 的新目录和项目。我们将项目命名为 hello_cargo,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 目录并列出文件。你会看到 Cargo 为我们生成了两个文件和一个目录:一个 Cargo.toml 文件和一个包含 main.rs 文件的 src 目录。

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.

它还初始化了一个新的 Git 仓库以及一个 .gitignore 文件。如果你在现有的 Git 仓库中运行 cargo new,则不会生成 Git 文件;你可以使用 cargo new --vcs=git 来覆盖此行为。

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 是一种常见的版本控制系统。你可以通过使用 --vcs 标志将 cargo new 更改为使用不同的版本控制系统或不使用版本控制系统。运行 cargo new --help 查看可用选项。

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.

在你选择的文本编辑器中打开 Cargo.toml。它应该看起来类似于列表 1-2 中的代码。

Open Cargo.toml in your text editor of choice. It should look similar to the code in Listing 1-2.

[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2024"

[dependencies]
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2024"

[dependencies]

此文件采用 TOML (Tom’s Obvious, Minimal Language) 格式,这是 Cargo 的配置格式。

This file is in the TOML (Tom’s Obvious, Minimal Language) format, which is Cargo’s configuration format.

第一行 [package] 是一个部分标题,表明接下来的语句正在配置一个包。随着我们向该文件添加更多信息,我们将添加其他部分。

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.

接下来的三行设置了 Cargo 编译程序所需的配置信息:名称、版本和要使用的 Rust 版本。我们将在 附录 E 中讨论 edition 键。

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.

最后一行 [dependencies] 是供你列出项目任何依赖项的部分的开始。在 Rust 中,代码包被称为 crates。这个项目不需要任何其他 crates,但在第 2 章的第一个项目中我们会需要,所以届时我们将使用这个依赖项部分。

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.

现在打开 src/main.rs 看看:

Now open src/main.rs and take a look:

文件名: src/main.rs (Filename: src/main.rs)

Filename: src/main.rs

fn main() {
    println!("Hello, world!");
}
fn main() {
    println!("Hello, world!");
}

Cargo 为你生成了一个 “Hello, world!” 程序,就像我们在列表 1-1 中编写的那个一样!到目前为止,我们的项目与 Cargo 生成的项目之间的区别在于,Cargo 将代码放在了 src 目录中,并且我们在顶级目录中有一个 Cargo.toml 配置文件。

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 期望你的源文件位于 src 目录中。顶级项目目录仅用于 README 文件、许可证信息、配置文件以及与你的代码无关的其他任何内容。使用 Cargo 可以帮助你组织项目。一切都有它的位置,一切都在它的位置上。

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 的项目,就像我们对 “Hello, world!” 项目所做的那样,你可以将其转换为使用 Cargo 的项目。将项目代码移至 src 目录并创建一个适当的 Cargo.toml 文件。获取该 Cargo.toml 文件的一个简单方法是运行 cargo init,它将自动为你创建。

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. One easy way to get that Cargo.toml file is to run cargo init, which will create it for you automatically.

构建和运行 Cargo 项目 (Building and Running a Cargo Project)

Building and Running a Cargo Project

现在让我们看看使用 Cargo 构建和运行 “Hello, world!” 程序时有什么不同!在你的 hello_cargo 目录下,通过输入以下命令构建你的项目:

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:

$ cargo build
   Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
$ cargo build
   Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs

此命令在 target/debug/hello_cargo(在 Windows 上为 target\debug\hello_cargo.exe)中创建一个可执行文件,而不是在当前目录中。因为默认构建是调试构建,所以 Cargo 将二进制文件放在名为 debug 的目录中。你可以使用此命令运行可执行文件:

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
Hello, world!
$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
Hello, world!

如果一切顺利,Hello, world! 应该会打印到终端。第一次运行 cargo build 还会导致 Cargo 在顶层创建一个新文件:Cargo.lock。此文件跟踪项目中依赖项的确切版本。由于该项目没有依赖项,因此该文件有点稀疏。你永远不需要手动更改此文件;Cargo 会为你管理它的内容。

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.

我们刚刚使用 cargo build 构建了一个项目并使用 ./target/debug/hello_cargo 运行了它,但我们也可以使用 cargo run 来编译代码,然后通过一个命令运行生成的可执行文件:

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 run
    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/hello_cargo`
Hello, world!
$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/hello_cargo`
Hello, world!

使用 cargo run 比记住运行 cargo build 然后使用二进制文件的完整路径更方便,因此大多数开发人员使用 cargo run

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 正在编译 hello_cargo 的输出。Cargo 发现文件没有改变,所以它没有重新构建而是直接运行了二进制文件。如果你修改了源代码,Cargo 会在运行项目之前重新构建项目,你将会看到如下输出:

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 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 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 还提供了一个名为 cargo check 的命令。此命令会快速检查你的代码以确保其可以编译,但不会生成可执行文件:

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 check
   Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
$ cargo check
   Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs

为什么你不需要可执行文件呢?通常,cargo checkcargo build 快得多,因为它跳过了生成可执行文件的步骤。如果你在编写代码时不断检查你的工作,使用 cargo check 将加快让你知道项目是否仍在编译的过程!因此,许多 Rust 开发人员 (Rustaceans) 在编写程序时会定期运行 cargo check 以确保其可以编译。然后,在准备好使用可执行文件时运行 cargo build

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 的知识:

Let’s recap what we’ve learned so far about Cargo:

  • 我们可以使用 cargo new 创建项目。

  • 我们可以使用 cargo build 构建项目。

  • 我们可以在一个步骤中使用 cargo run 构建和运行项目。

  • 我们可以在不生成二进制文件的情况下构建项目以使用 cargo check 检查错误。

  • Cargo 不是将构建结果保存在与代码相同的目录中,而是将其存储在 target/debug 目录中。

  • We can create a project using cargo new.

  • We can build a project using cargo build.

  • We can build and run a project in one step using cargo run.

  • We can build a project without producing a binary to check for errors using 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 的另一个优点是,无论你在哪个操作系统上工作,命令都是相同的。因此,在这一点上,我们将不再为 Linux 和 macOS 与 Windows 提供特定的说明。

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.

发布版本构建 (Building for Release)

Building for Release

当你的项目终于准备好发布时,你可以使用 cargo build --release 来通过优化进行编译。此命令将在 target/release 而不是 target/debug 中创建一个可执行文件。优化使你的 Rust 代码运行得更快,但开启优化会延长程序编译所需的时间。这就是为什么有两种不同的配置文件:一种用于开发,当你想要快速且频繁地重新构建时;另一种用于构建最终提供给用户的程序,该程序不会被重复重新构建且运行速度尽可能快。如果你正在对代码的运行时间进行基准测试,请务必运行 cargo build --release 并使用 target/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 的惯例 (Leveraging Cargo’s Conventions)

Leveraging Cargo’s Conventions

对于简单的项目,Cargo 相比于直接使用 rustc 并没有提供太多的价值,但随着你的程序变得更加复杂,它将证明其价值。一旦程序增长到多个文件或需要依赖项,让 Cargo 协调构建就会容易得多。

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.

尽管 hello_cargo 项目很简单,但它现在使用了你在 Rust 生涯的其余部分将使用的许多真实工具。事实上,要在任何现有项目上工作,你可以使用以下命令通过 Git 检出代码,切换到该项目目录,然后构建:

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:

$ git clone example.org/someproject
$ cd someproject
$ cargo build
$ git clone example.org/someproject
$ cd someproject
$ cargo build

有关 Cargo 的更多信息,请查看 其文档

For more information about Cargo, check out its documentation.

总结 (Summary)

Summary

你的 Rust 之旅已经有了一个很好的开始!在本章中,你学会了如何:

You’re already off to a great start on your Rust journey! In this chapter, you learned how to:

  • 使用 rustup 安装最新的稳定版 Rust。

  • 更新到较新的 Rust 版本。

  • 打开本地安装的文档。

  • 直接使用 rustc 编写并运行 “Hello, world!” 程序。

  • 使用 Cargo 的惯例创建并运行一个新项目。

  • Install the latest stable version of Rust using rustup.

  • Update to a newer Rust version.

  • Open locally installed documentation.

  • Write and run a “Hello, world!” program using rustc directly.

  • Create and run a new project using the conventions of Cargo.

现在是构建一个更充实的程序以习惯阅读和编写 Rust 代码的好时机。因此,在第 2 章中,我们将构建一个猜谜游戏程序。如果你宁愿先学习通用编程概念在 Rust 中是如何工作的,请参阅第 3 章,然后再返回第 2 章。

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.

编写猜数字游戏 (Programming a Guessing Game)


x-i18n: generated_at: “2026-03-01T13:12:43Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 353f08f5f9306cec3bdcac6a9efd3e5c7968264a6fc3f489e1c5abea3b3fbdda source_path: ch02-00-guessing-game-tutorial.md workflow: 16

编写猜数字游戏 (Programming a Guessing Game)

Programming a Guessing Game

让我们通过共同完成一个动手项目来跳入 Rust 的世界!本章将向你展示如何在一个真实程序中使用一些常见的 Rust 概念。你将学习 letmatch、方法 (methods)、关联函数 (associated functions)、外部 crate 等内容!在接下来的章节中,我们将更详细地探讨这些想法。在本章中,你只需要练习基础知识。

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.

我们将实现一个经典的初学者编程问题:猜数字游戏。它的工作原理是:程序将生成一个 1 到 100 之间的随机整数。然后它会提示玩家输入一个猜测。在输入猜测后,程序将指示该猜测是太低还是太高。如果猜测正确,游戏将打印一条恭喜消息并退出。

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.

创建一个新项目 (Setting Up a New Project)

Setting Up a New Project

要创建一个新项目,请进入你在第 1 章中创建的 projects 目录,并使用 Cargo 创建一个新项目,如下所示:

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:

$ cargo new guessing_game
$ cd guessing_game

第一个命令 cargo new 将项目名称 (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.toml 文件:

Look at the generated Cargo.toml file:

文件名:Cargo.toml (Filename: Cargo.toml)

{{#include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml}}

正如你在第 1 章中所看到的,cargo new 为你生成了一个 “Hello, world!” 程序。查看 src/main.rs 文件:

As you saw in Chapter 1, cargo new generates a “Hello, world!” program for you. Check out the src/main.rs file:

文件名:src/main.rs (Filename: src/main.rs)

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs}}
}

现在让我们使用 cargo run 命令在同一步骤中编译并运行这个 “Hello, world!” 程序:

Now let’s compile this “Hello, world!” program and run it in the same step using the cargo run command:

{{#include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt}}

当你需要快速迭代一个项目时,run 命令非常方便,就像我们在这个游戏中要做的那样,在进入下一步之前快速测试每一次迭代。

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.

重新打开 src/main.rs 文件。你将在这个文件中编写所有的代码。

Reopen the src/main.rs file. You’ll be writing all the code in this file.

处理猜测 (Processing a Guess)

Processing a Guess

猜数字游戏程序的第一部分将询问用户输入,处理该输入,并检查输入是否符合预期形式。首先,我们将允许玩家输入一个猜测。将示例 2-1 中的代码输入到 src/main.rs 中。

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.

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:all}}

这段代码包含很多信息,让我们逐行过一遍。为了获取用户输入并将结果作为输出打印出来,我们需要将 io 输入/输出库引入作用域。io 库来自标准库,即 std

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:

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:io}}

默认情况下,Rust 会在标准库中定义一组项,并将其引入每个程序的作用域。这组项被称为 prelude (预导入模块),你可以在 标准库文档 中查看其中的所有内容。

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.

如果你想使用的类型不在 prelude 中,你必须使用 use 语句显式地将该类型引入作用域。使用 std::io 库可以为你提供许多有用的功能,包括接受用户输入的能力。

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.

正如你在第 1 章中所看到的,main 函数是程序的入口点:

As you saw in Chapter 1, the main function is the entry point into the program:

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:main}}

fn 语法声明了一个新函数;圆括号 () 表示没有参数;而花括号 { 开始了函数体。

The fn syntax declares a new function; the parentheses, (), indicate there are no parameters; and the curly bracket, {, starts the body of the function.

正如你还在第 1 章中学到的,println! 是一个将字符串打印到屏幕上的宏:

As you also learned in Chapter 1, println! is a macro that prints a string to the screen:

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:print}}

这段代码正在打印一个提示,说明游戏内容并请求用户输入。

This code is printing a prompt stating what the game is and requesting input from the user.

使用变量存储值 (Storing Values with Variables)

Storing Values with Variables

接下来,我们将创建一个 变量 (variable) 来存储用户输入,如下所示:

Next, we’ll create a variable to store the user input, like this:

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:string}}

现在程序变得有趣了!在这一小行中发生了很多事情。我们使用 let 语句来创建变量。这里有另一个例子:

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 apples = 5;

这一行创建了一个名为 apples 的新变量,并将它绑定到值 5。在 Rust 中,变量默认是不可变的 (immutable),这意味着一旦我们给变量一个值,这个值就不会改变。我们将在第 3 章的 “变量与可变性” 部分详细讨论这个概念。要使变量可变 (mutable),我们在变量名之前添加 mut

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:

let apples = 5; // 不可变 (immutable)
let mut bananas = 5; // 可变 (mutable)

注意:// 语法开始一个注释,该注释一直持续到行尾。Rust 会忽略注释中的所有内容。我们将在 第 3 章 中更详细地讨论注释。

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.

回到猜数字游戏程序,你现在知道 let mut guess 将引入一个名为 guess 的可变变量。等号 (=) 告诉 Rust 我们现在想要将某些东西绑定到该变量。等号右边是 guess 所绑定的值,它是调用 String::new 的结果,该函数返回 String 的一个新实例。String 是标准库提供的一种字符串类型,它是一种可增长的、UTF-8 编码的文本片段。

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.

::new 行中的 :: 语法表示 newString 类型的一个关联函数 (associated function)。关联函数 是在某种类型上实现的函数,在本例中是 String。这个 new 函数创建了一个新的空字符串。你会在许多类型上发现 new 函数,因为它是创建某种新值的函数的常用名称。

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.

总而言之,let mut guess = String::new(); 这一行创建了一个可变变量,该变量目前绑定到一个新的空 String 实例。呼!

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!

接收用户输入 (Receiving User Input)

Receiving User Input

回想一下,我们在程序的第一行使用 use std::io; 引入了标准库的输入/输出功能。现在我们将调用 io 模块中的 stdin 函数,这将允许我们处理用户输入:

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:

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:read}}

如果我们没有在程序开头使用 use std::io; 导入 io 模块,我们仍然可以通过将此函数调用写为 std::io::stdin 来使用该函数。stdin 函数返回 std::io::Stdin 的一个实例,该类型代表终端标准输入的句柄 (handle)。

If we hadn’t imported the io module 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.

接下来,.read_line(&mut guess) 行在标准输入句柄上调用 read_line 方法,以获取用户的输入。我们还将 &mut guess 作为参数传递给 read_line,以告诉它将用户输入存储在哪个字符串中。read_line 的全部工作是获取用户在标准输入中输入的任何内容,并将其追加到字符串中(不覆盖其内容),因此我们将该字符串作为参数传递。字符串参数需要是可变的,以便该方法可以更改字符串的内容。

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 that the method can change the string’s content.

& 表示该参数是一个 引用 (reference),它为你提供了一种方法,让代码的多个部分访问同一块数据,而无需多次将该数据复制到内存中。引用是一个复杂的功能,而 Rust 的主要优势之一就是使用引用的安全性和简便性。你不需要了解这些细节就可以完成这个程序。目前,你只需要知道,像变量一样,引用默认也是不可变的。因此,你需要编写 &mut guess 而不是 &guess 来使其可变。(第 4 章将更深入地解释引用。)

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.)

使用 Result 处理潜在的失败 (Handling Potential Failure with Result)

Handling Potential Failure with 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:

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:expect}}

我们可以将这段代码写成:

We could have written this code as:

io::stdin().read_line(&mut guess).expect("Failed to read line");

然而,过长的行难以阅读,因此最好将其拆分。当你使用 .method_name() 语法调用方法时,引入换行符和其他空白符来帮助分解长行通常是明智之举。现在让我们讨论这一行的作用。

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.

如前所述,read_line 将用户输入的任何内容放入我们传递给它的字符串中,但它也会返回一个 Result 值。Result 是一个 枚举 (enumeration)(通常简称为 enum),它是一种可以处于多种可能状态之一的类型。我们称每个可能的状态为 变体 (variant)

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.

第 6 章 将更详细地讨论枚举。这些 Result 类型的目的是编码错误处理信息。

Chapter 6 will cover enums in more detail. The purpose of these Result types is to encode error-handling information.

Result 的变体是 OkErrOk 变体表示操作成功,并包含成功生成的值。Err 变体表示操作失败,并包含有关操作如何失败或为何失败的信息。

Result’s variants are Ok and Err. The Ok variant indicates the operation was successful, and it contains the successfully generated value. The Err variant means the operation failed, and it contains information about how or why the operation failed.

Result 类型的值,就像任何类型的值一样,在其上定义了方法。Result 的实例有一个你可以调用的 expect 方法。如果这个 Result 实例是一个 Err 值,expect 将导致程序崩溃,并显示你作为参数传递给 expect 的消息。如果 read_line 方法返回 Err,这很可能是底层操作系统产生的错误结果。如果这个 Result 实例是一个 Ok 值,expect 将获取 Ok 持有的返回值,并仅将该值返回给你,以便你可以使用它。在本例中,该值是用户输入中的字节数。

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 that you can use it. In this case, that value is the number of bytes in the user’s input.

如果你不调用 expect,程序可以编译,但你会得到一个警告:

If you don’t call expect, the program will compile, but you’ll get a warning:

{{#include ../listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt}}

Rust 警告你没有使用 read_line 返回的 Result 值,这表明程序尚未处理可能出现的错误。

Rust warns that you haven’t used the Result value returned from read_line, indicating that the program hasn’t handled a possible error.

消除警告的正确方法是实际编写错误处理代码,但在我们的案例中,我们只想在出现问题时让程序崩溃,因此我们可以使用 expect。你将在 第 9 章 中学习如何从错误中恢复。

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.

使用 println! 占位符打印值 (Printing Values with println! Placeholders)

Printing Values with println! Placeholders

除了结尾的花括号外,到目前为止的代码中只有一行需要讨论:

Aside from the closing curly bracket, there’s only one more line to discuss in the code so far:

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:print_guess}}

这一行打印现在包含用户输入的字符串。{} 这对花括号是一个占位符:把 {} 想象成固定值的小螃蟹钳。在打印变量的值时,变量名可以放在花括号内。在打印评估表达式的结果时,在格式字符串中放置空花括号,然后在格式字符串后跟一个逗号分隔的表达式列表,以按相同顺序打印在每个空花括号占位符中。在一次调用 println! 中同时打印变量和表达式的结果看起来像这样:

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:

#![allow(unused)]
fn main() {
let x = 5;
let y = 10;

println!("x = {x} and y + 2 = {}", y + 2);
}

这段代码将打印 x = 5 and y + 2 = 12

This code would print x = 5 and y + 2 = 12.

测试第一部分 (Testing the First Part)

Testing the First Part

让我们测试猜数字游戏的第一部分。使用 cargo run 运行它:

Let’s test the first part of the guessing game. Run it using cargo run:

$ cargo run
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished `dev` profile [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)

Generating a Secret Number

接下来,我们需要生成一个秘密数字供用户尝试猜测。秘密数字每次都应该不同,这样游戏玩起来才会有趣。我们将使用 1 到 100 之间的随机数,这样游戏就不会太难。Rust 尚未在其标准库中包含随机数功能。但是,Rust 团队确实提供了一个具有该功能的 rand crate

Next, we need to generate a secret number that the user will try to guess. The secret number should be different every time so that the game is fun to play more than once. We’ll use a random number between 1 and 100 so that 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.

通过 crate 增加功能 (Increasing Functionality with a Crate)

Increasing Functionality with a Crate

请记住,crate 是 Rust 源代码文件的集合。我们一直在构建的项目是一个二进制 crate (binary crate),它是一个可执行文件。rand crate 是一个库 crate (library 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.

Cargo 对外部 crate 的协调是 Cargo 真正大放异彩的地方。在我们编写使用 rand 的代码之前,我们需要修改 Cargo.toml 文件,将 rand crate 作为依赖项包含在内。现在打开该文件,并在 Cargo 为你创建的 [dependencies] 节标题下方添加以下行。请务必严格按照我们这里的格式指定 rand,并使用此版本号,否则本教程中的代码示例可能无法运行:

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.toml (Filename: Cargo.toml)

{{#include ../listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml:8:}}

Cargo.toml 文件中,标题后面的所有内容都是该节的一部分,该节一直持续到另一个节开始。在 [dependencies] 中,你告诉 Cargo 你的项目依赖于哪些外部 crate 以及你需要的这些 crate 的版本。在这种情况下,我们使用语义化版本说明符 0.8.5 指定 rand crate。Cargo 理解 语义化版本 (Semantic Versioning)(有时称为 SemVer),这是一种编写版本号的标准。说明符 0.8.5 实际上是 ^0.8.5 的简写,这意味着任何至少为 0.8.5 但低于 0.9.0 的版本。

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 认为这些版本的公共 API 与版本 0.8.5 兼容,此规范可确保你将获得最新的修订版,且该版本仍能与本章中的代码一起编译。任何 0.9.0 或更高版本都不保证具有与以下示例相同的 API。

Cargo considers these versions to have public APIs compatible with version 0.8.5, and this specification ensures that 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.

现在,在不更改任何代码的情况下,让我们构建项目,如示例 2-2 所示。

Now, without changing any of the code, let’s build the project, as shown in Listing 2-2.

$ cargo build
  Updating crates.io index
   Locking 15 packages to latest Rust 1.85.0 compatible versions
    Adding rand v0.8.5 (available: v0.9.0)
 Compiling proc-macro2 v1.0.93
 Compiling unicode-ident v1.0.17
 Compiling libc v0.2.170
 Compiling cfg-if v1.0.0
 Compiling byteorder v1.5.0
 Compiling getrandom v0.2.15
 Compiling rand_core v0.6.4
 Compiling quote v1.0.38
 Compiling syn v2.0.98
 Compiling zerocopy-derive v0.7.35
 Compiling zerocopy v0.7.35
 Compiling ppv-lite86 v0.2.20
 Compiling rand_chacha v0.3.1
 Compiling rand v0.8.5
 Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
  Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.48s

你可能会看到不同的版本号(但由于 SemVer,它们都会与代码兼容!)和不同的行(取决于操作系统),并且这些行的顺序可能不同。

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.

当我们包含外部依赖项时,Cargo 会从 注册表 (registry) 中获取该依赖项所需的所有最新版本,注册表是来自 Crates.io 的数据副本。Crates.io 是 Rust 生态系统中的人们发布其开源 Rust 项目供他人使用的地方。

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 会检查 [dependencies] 部分,并下载任何列出的但尚未下载的 crate。在本例中,虽然我们只将 rand 列为依赖项,但 Cargo 也会抓取 rand 正常运行所依赖的其他 crate。下载完这些 crate 后,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 build,除了 Finished 行之外,你不会得到任何输出。Cargo 知道它已经下载并编译了依赖项,并且你没有在 Cargo.toml 文件中更改关于它们的任何内容。Cargo 还知道你没有更改关于代码的任何内容,因此它也不会重新编译代码。由于无事可做,它直接退出。

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.

如果你打开 src/main.rs 文件,做一些微不足道的更改,然后保存并再次构建,你将只能看到两行输出:

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:

$ cargo build
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s

这些行显示 Cargo 仅根据你对 src/main.rs 文件的微小更改更新了构建。你的依赖项没有改变,因此 Cargo 知道它可以重用已经为这些依赖项下载和编译的内容。

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.

确保可重复构建 (Ensuring Reproducible Builds)

Ensuring Reproducible Builds

Cargo 有一种机制可以确保你或任何其他人在构建你的代码时,每次都能重建相同的产物:Cargo 将仅使用你指定的依赖项版本,除非你另有指示。例如,假设下周 rand crate 的 0.8.6 版本发布了,该版本包含一个重要的错误修复,但也包含一个会导致你的代码损坏的回归。为了处理这种情况,Rust 在你第一次运行 cargo build 时创建了 Cargo.lock 文件,因此我们现在在 guessing_game 目录中有了这个文件。

Cargo has a mechanism that ensures that 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.lock 文件。当你将来构建项目时,Cargo 会发现 Cargo.lock 文件存在,并使用其中指定的版本,而不是再次执行所有找出版本的工作。这使你能够自动拥有可重复的构建。换句话说,由于 Cargo.lock 文件的存在,你的项目将保持在 0.8.5,直到你显式升级。由于 Cargo.lock 文件对于可重复构建非常重要,因此它通常与项目中的其余代码一起提交到源代码控制系统中。

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.

更新 crate 以获取新版本 (Updating a Crate to Get a New Version)

Updating a Crate to Get a New Version

当你 确实 想更新 crate 时,Cargo 提供了 update 命令,它将忽略 Cargo.lock 文件,并找出符合你在 Cargo.toml 中指定的所有最新版本。然后,Cargo 会将这些版本写入 Cargo.lock 文件。否则,默认情况下,Cargo 仅会查找大于 0.8.5 且小于 0.9.0 的版本。如果 rand crate 发布了两个新版本 0.8.6 和 0.999.0,如果你运行 cargo update,你将看到以下内容:

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. Otherwise, by default, 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.999.0, you would see the following if you ran cargo update:

$ cargo update
    Updating crates.io index
     Locking 1 package to latest Rust 1.85.0 compatible version
    Updating rand v0.8.5 -> v0.8.6 (available: v0.999.0)

Cargo 忽略了 0.999.0 版本。此时,你还会注意到 Cargo.lock 文件发生了变化,指出你现在使用的 rand crate 版本是 0.8.6。要使用 rand 版本 0.999.0 或 0.999.x 系列中的任何版本,你必须更新 Cargo.toml 文件,使其看起来像这样(实际上不要做此更改,因为以下示例假设你使用的是 rand 0.8):

Cargo ignores the 0.999.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.999.0 or any version in the 0.999.x series, you’d have to update the Cargo.toml file to look like this instead (don’t actually make this change because the following examples assume you’re using rand 0.8):

[dependencies]
rand = "0.999.0"

下一次运行 cargo build 时,Cargo 将更新可用 crate 的注册表,并根据你指定的新版本重新评估你的 rand 需求。

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 及其 生态系统 还有很多内容要讲,我们将在第 14 章中讨论,但现在,这就是你需要知道的全部内容。Cargo 使得重用库变得非常容易,因此 Rustaceans 能够编写由许多包组装而成的小型项目。

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.

生成一个随机数 (Generating a Random Number)

Generating a Random Number

让我们开始使用 rand 来生成一个要猜测的数字。下一步是更新 src/main.rs,如示例 2-3 所示。

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.

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs:all}}

首先,我们添加 use rand::Rng; 这一行。Rng trait 定义了随机数生成器实现的方法,并且这个 trait 必须在作用域内,我们才能使用这些方法。第 10 章将详细介绍 trait。

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.

接下来,我们在中间添加两行。在第一行中,我们调用 rand::thread_rng 函数,它为我们提供了我们将要使用的特定随机数生成器:一个位于当前执行线程本地并由操作系统设定种子的生成器。然后,我们在随机数生成器上调用 gen_range 方法。此方法由我们使用 use rand::Rng; 语句引入作用域的 Rng trait 定义。gen_range 方法采用一个范围表达式作为参数,并生成该范围内的随机数。我们在这里使用的这种范围表达式采用 start..=end 的形式,并且包含下限和上限,因此我们需要指定 1..=100 来请求 1 到 100 之间的数字。

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.

注意:你不会仅凭直觉就知道要从一个 crate 中使用哪些 trait 以及调用哪些方法和函数,因此每个 crate 都有包含其使用说明的文档。Cargo 的另一个巧妙功能是,运行 cargo doc --open 命令将在本地构建所有依赖项提供的文档,并在浏览器中打开。例如,如果你对 rand crate 中的其他功能感兴趣,请运行 cargo doc --open 并在左侧边栏中点击 rand

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.

第二个新行打印秘密数字。这在开发程序以便能够对其进行测试时非常有用,但我们将在最终版本中删除它。如果程序一启动就打印答案,那就不成其为游戏了!

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` profile [unoptimized + debuginfo] target(s) in 0.02s
     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` profile [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

你应该得到不同的随机数,并且它们都应该是 1 到 100 之间的数字。干得好!

You should get different random numbers, and they should all be numbers between 1 and 100. Great job!

比较猜测数字与秘密数字 (Comparing the Guess to the Secret Number)

Comparing the Guess to the Secret Number

现在我们有了用户输入和随机数,我们可以对它们进行比较。这一步如示例 2-4 所示。请注意,正如我们将要解释的,这段代码暂时还不能编译。

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.

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs:here}}

首先,我们添加另一个 use 语句,从标准库中将一个名为 std::cmp::Ordering 的类型引入作用域。Ordering 类型是另一个枚举,其变体为 LessGreaterEqual。当你比较两个值时,这是可能出现的三种结果。

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.

然后,我们在底部添加了五行使用 Ordering 类型的新代码。cmp 方法比较两个值,并且可以被任何可以进行比较的对象调用。它采用指向你要比较的任何内容的引用:在这里,它正在将 guesssecret_number 进行比较。然后,它返回我们在 use 语句中引入作用域的 Ordering 枚举的一个变体。我们使用 match 表达式,根据调用 cmp 比较 guesssecret_number 的值后返回的 Ordering 变体来决定下一步该做什么。

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.

match 表达式由 分支 (arm) 组成。一个分支包含一个用于匹配的 模式 (pattern),以及如果提供给 match 的值符合该分支模式时应运行的代码。Rust 获取提供给 match 的值,并依次检查每个分支的模式。模式和 match 结构是强大的 Rust 功能:它们让你能够表达代码可能遇到的各种情况,并确保你处理了所有情况。这些功能将分别在第 6 章和第 19 章中详细介绍。

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 19, respectively.

让我们用这里使用的 match 表达式走一遍例子。假设用户猜测了 50,而这次随机生成的秘密数字是 38。

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.

当代码将 50 与 38 进行比较时,cmp 方法将返回 Ordering::Greater,因为 50 大于 38。match 表达式获取 Ordering::Greater 值,并开始检查每个分支的模式。它查看第一个分支的模式 Ordering::Less,发现值 Ordering::GreaterOrdering::Less 不匹配,因此它忽略该分支中的代码并移至下一个分支。下一个分支的模式是 Ordering::Greater,它 确实Ordering::Greater 匹配!该分支中的相关代码将执行,并在屏幕上打印 Too big!match 表达式在第一次成功匹配后结束,因此在这种情况下它不会查看最后一个分支。

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.

但是,示例 2-4 中的代码暂时还无法编译。让我们试一下:

However, the code in Listing 2-4 won’t compile yet. Let’s try it:

{{#include ../listings/ch02-guessing-game-tutorial/listing-02-04/output.txt}}

错误的核心指出存在 类型不匹配 (mismatched types)。Rust 具有强大的静态类型系统。但是,它也有类型推断 (type inference)。当我们编写 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 无法比较字符串和数字类型。

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.

最终,我们希望将程序读取为输入的 String 转换为数字类型,以便我们可以将其与秘密数字进行数值比较。我们通过在 main 函数体中添加这一行来实现:

Ultimately, we want to convert the String the program reads as input into a number type so that we can compare it numerically to the secret number. We do so by adding this line to the main function body:

文件名:src/main.rs (Filename: src/main.rs)

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs:here}}

这一行是:

The line is:

let guess: u32 = guess.trim().parse().expect("Please type a number!");

我们创建了一个名为 guess 的变量。但等等,程序不是已经有一个名为 guess 的变量了吗?确实有,但幸好 Rust 允许我们用一个新值来重影 (shadow) 之前的 guess 值。重影 (Shadowing) 允许我们重用 guess 变量名,而不是强迫我们创建两个唯一的变量,例如 guess_strguess。我们将在 第 3 章 中更详细地讨论这一点,但现在,请记住,当你想要将一个值从一种类型转换为另一种类型时,经常会使用此功能。

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.trim().parse()。表达式中的 guess 指的是包含字符串输入的原始 guess 变量。String 实例上的 trim 方法将消除开头和结尾的任何空白,在我们将字符串转换为 u32 之前必须这样做,因为 u32 只能包含数字数据。用户必须按下 enter 键才能满足 read_line 并输入他们的猜测,这会向字符串中添加一个换行符。例如,如果用户输入 5 并按下 enterguess 看起来像这样:5\n\n 代表 “换行符”。(在 Windows 上,按下 enter 键会产生回车符和换行符 \r\n。)trim 方法会消除 \n\r\n,结果只剩下 5

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 before we can convert the string to a 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.

字符串上的 parse 方法 将字符串转换为另一种类型。在这里,我们使用它将字符串转换为数字。我们需要通过使用 let guess: u32 来告诉 Rust 我们需要的确切数字类型。guess 之后的冒号 (:) 告诉 Rust 我们将标注变量的类型。Rust 有几种内置的数字类型;这里看到的 u32 是一个无符号 32 位整数。它是小型正数的良好默认选择。你将在 第 3 章 中了解其他数字类型。

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.

此外,此示例程序中的 u32 标注以及与 secret_number 的比较意味着 Rust 也会推断出 secret_number 也应该是 u32。所以,现在比较将在两个相同类型的值之间进行!

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!

parse 方法仅对逻辑上可以转换为数字的字符起作用,因此很容易导致错误。例如,如果字符串包含 A👍%,则无法将其转换为数字。因为它可能会失败,所以 parse 方法返回一个 Result 类型,就像 read_line 方法一样(前面在 “使用 Result 处理潜在的失败” 中讨论过)。我们将通过再次使用 expect 方法以相同的方式处理此 Result。如果 parse 因为无法从字符串创建数字而返回 Err Result 变体,则 expect 调用将使游戏崩溃并打印我们给它的消息。如果 parse 能够成功地将字符串转换为数字,它将返回 ResultOk 变体,而 expect 将从 Ok 值中返回我们想要的数字。

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.

现在让我们运行程序:

Let’s run the program now:

$ cargo run
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.26s
     Running `target/debug/guessing_game`
Guess the number!
The secret number is: 58
Please input your guess.
  76
You guessed: 76
Too big!

不错!即使在猜测数字前添加了空格,程序仍然算出用户猜的是 76。运行程序几次,以验证不同种类输入的行为:正确猜中数字、猜的数字太高以及猜的数字太低。

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.

现在我们已经完成了大部分游戏的运行,但是用户只能进行一次猜测。让我们通过添加循环来改变这一点!

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)

Allowing Multiple Guesses with Looping

loop 关键字创建了一个无限循环。我们将添加一个循环,让用户有更多机会猜测数字:

The loop keyword creates an infinite loop. We’ll add a loop to give users more chances at guessing the number:

文件名:src/main.rs (Filename: src/main.rs)

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs:here}}

如你所见,我们将从猜测输入提示开始的所有内容都移到了循环中。确保将循环内的各行再缩进四个空格,并再次运行程序。程序现在将永远请求另一个猜测,这实际上引入了一个新问题。看起来用户无法退出了!

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!

用户始终可以使用键盘快捷键 ctrl-C 中断程序。但还有另一种方法可以逃离这个贪得无厌的怪物,正如在 “比较猜测数字与秘密数字”parse 讨论中提到的:如果用户输入非数字答案,程序将崩溃。我们可以利用这一点来允许用户退出,如下所示:

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:

$ cargo run
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.23s
     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 src/main.rs:28:47:
Please type a number!: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

输入 quit 将退出游戏,但正如你将注意到的,输入任何其他非数字输入也会退出。这充其量只是次优选择;我们希望游戏在猜中正确数字时也停止。

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.

猜对后退出 (Quitting After a Correct Guess)

Quitting After a Correct Guess

让我们通过添加 break 语句,将游戏编写为在用户获胜时退出:

Let’s program the game to quit when the user wins by adding a break statement:

文件名:src/main.rs (Filename: src/main.rs)

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs:here}}

You win! 之后添加 break 行,使程序在用户正确猜中秘密数字时退出循环。退出循环也意味着退出程序,因为循环是 main 的最后一部分。

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.

处理无效输入 (Handling Invalid Input)

Handling Invalid Input

为了进一步完善游戏的运行方式,与其在用户输入非数字时使程序崩溃,不如让游戏忽略非数字,以便用户可以继续猜测。我们可以通过更改将 guessString 转换为 u32 的那一行来实现,如示例 2-5 所示。

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 that 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.

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs:here}}

我们将 expect 调用切换为 match 表达式,以便从错误崩溃转向错误处理。请记住,parse 返回一个 Result 类型,而 Result 是一个包含 OkErr 变体的枚举。我们在这里使用的是 match 表达式,就像处理 cmp 方法的 Ordering 结果一样。

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.

如果 parse 能够成功地将字符串转换为数字,它将返回一个包含生成的数字的 Ok 值。该 Ok 值将匹配第一个分支的模式,并且 match 表达式将仅返回 parse 产生并放入 Ok 值中的 num 值。该数字最终将出现在我们正在创建的新 guess 变量中,正是我们想要它的地方。

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 不能 将字符串转换为数字,它将返回一个包含更多错误信息的 Err 值。Err 值不匹配第一个 match 分支中的 Ok(num) 模式,但它确实匹配第二个分支中的 Err(_) 模式。下划线 _ 是一个全匹配值;在这个例子中,我们要说的是我们想要匹配所有的 Err 值,不管里面有什么信息。因此,程序将执行第二个分支的代码 continue,它告诉程序进入 loop 的下一次迭代并请求另一个猜测。因此,实际上程序忽略了 parse 可能遇到的所有错误!

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 catch-all 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!

现在程序中的一切都应该按预期工作了。让我们试一下:

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` profile [unoptimized + debuginfo] target(s) in 0.13s
     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!

太棒了!通过最后一点微调,我们将完成猜数字游戏。回想一下,程序仍在打印秘密数字。这对于测试非常有用,但它破坏了游戏。让我们删除输出秘密数字的 println!。示例 2-6 显示了最终代码。

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.

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs}}

至此,你已经成功构建了猜数字游戏。恭喜!

At this point, you’ve successfully built the guessing game. Congratulations!

总结 (Summary)

Summary

这个项目是通过实践向你介绍许多新的 Rust 概念的一种方式:letmatch、函数、外部 crate 的使用等等。在接下来的几章中,你将更详细地学习这些概念。第 3 章介绍了大多数编程语言都有的概念,如变量、数据类型和函数,并展示了如何在 Rust 中使用它们。第 4 章探讨了所有权 (ownership),这是使 Rust 区别于其他语言的功能。第 5 章讨论了结构体 (structs) 和方法语法,而第 6 章则解释了枚举 (enums) 的工作原理。

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.

通用编程概念 (Common Programming Concepts)


x-i18n: generated_at: “2026-03-01T13:14:33Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 577cfc9c38aef8a921625806872f74d15d26e6457e3f7249665ea7afef29e014 source_path: ch03-00-common-programming-concepts.md workflow: 16

通用编程概念 (Common Programming Concepts)

Common Programming Concepts

本章介绍了几乎在所有编程语言中都会出现的概念,以及它们在 Rust 中是如何工作的。许多编程语言的核心都有很多共同点。本章介绍的概念都不是 Rust 特有的,但我们将在 Rust 的背景下讨论它们,并解释使用它们的约定。

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 them.

具体来说,你将学习变量、基本类型、函数、注释和控制流。这些基础将出现在每一个 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.

关键字 (Keywords)

Keywords

与其他语言类似,Rust 语言有一组仅供语言本身使用的 关键字 (keywords)。请记住,你不能使用这些单词作为变量或函数的名称。大多数关键字具有特殊的含义,你将使用它们在 Rust 程序中完成各种任务;少数关键字目前没有关联的功能,但已为将来可能添加到 Rust 的功能而保留。你可以在 附录 A 中找到关键字列表。

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 the list of the keywords in Appendix A.

变量与可变性 (Variables and Mutability)


x-i18n: generated_at: “2026-03-01T13:14:54Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f8e3bd09891f35846d61ec183508fcd4e88ef3450da1107cb6749eeddc815f60 source_path: ch03-01-variables-and-mutability.md workflow: 16

变量与可变性 (Variables and Mutability)

Variables and Mutability

正如在 “使用变量存储值” 部分提到的,默认情况下,变量是不可变的。这是 Rust 给予你的众多暗示之一,旨在让你利用 Rust 提供的安全性和便捷的并发性来编写代码。然而,你仍然可以选择让你的变量变成可变的。让我们探讨一下 Rust 为何以及如何鼓励你优先选择不可变性,以及为什么有时你可能想要选择退出。

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.

当变量不可变时,一旦一个值绑定到一个名称,你就不能更改该值。为了说明这一点,请在你的 projects 目录中通过使用 cargo new variables 生成一个名为 variables 的新项目。

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.

然后,在你新的 variables 目录中,打开 src/main.rs 并将其代码替换为以下代码,这段代码目前还无法编译:

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)

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs}}

保存并使用 cargo run 运行程序。你应该会收到一条关于不可变性错误的错误消息,如下输出所示:

Save and run the program using cargo run. You should receive an error message regarding an immutability error, as shown in this output:

{{#include ../listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt}}

这个例子展示了编译器如何帮助你查找程序中的错误。编译器错误可能会让人感到沮丧,但实际上它们只意味着你的程序目前还无法安全地执行你想要它执行的操作;它们并不意味着你不是一个好的程序员!经验丰富的 Rustaceans 仍然会遇到编译器错误。

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.

你收到了错误消息 cannot assign twice to immutable variable `x`,因为你试图为不可变的 x 变量分配第二个值。

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.

当我们试图更改被指定为不可变的值时,获得编译时错误非常重要,因为这种情况本身就可能导致 bug。如果代码的一部分基于一个值永远不会改变的假设运行,而代码的另一部分改变了该值,那么代码的第一部分就有可能无法实现其设计功能。这种类型的 bug 的原因事后可能很难追踪,尤其是当第二段代码只是在 有时 更改值时。Rust 编译器保证当你声明一个值不会改变时,它就真的不会改变,所以你不需要自己跟踪它。因此,你的代码更容易推导。

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.

但可变性可能非常有用,并且可以使代码编写起来更加方便。虽然变量默认是不可变的,但你可以通过在变量名前添加 mut 来使其变为可变,就像你在 第 2 章 中所做的那样。添加 mut 还能向未来的代码读者传达意图,表明代码的其他部分将会更改此变量的值。

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.

例如,让我们将 src/main.rs 更改为以下内容:

For example, let’s change src/main.rs to the following:

文件名:src/main.rs (Filename: src/main.rs)

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs}}
}

现在运行程序,我们得到:

When we run the program now, we get this:

{{#include ../listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt}}

当使用 mut 时,我们被允许将绑定到 x 的值从 5 更改为 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.

声明常量 (Declaring Constants)

Declaring Constants

与不可变变量类似,常量 (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.

首先,你不被允许对常量使用 mut。常量不仅默认不可变——它们始终不可变。你使用 const 关键字而不是 let 关键字来声明常量,并且值的大小 必须 标注类型。我们将在下一节 “数据类型” 中介绍类型和类型标注,所以现在不用担心细节。只要知道你必须始终标注类型即可。

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.

常量可以在任何作用域中声明,包括全局作用域,这使得它们对于代码中许多部分都需要了解的值非常有用。

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:

#![allow(unused)]
fn main() {
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}

常量的名称是 THREE_HOURS_IN_SECONDS,它的值被设置为 60(一分钟的秒数)乘以 60(一小时的分钟数)再乘以 3(我们在这个程序中想要计算的小时数)的结果。Rust 对常量的命名约定是使用全大写字母,并在单词之间使用下划线。编译器能够在编译时评估有限的一组操作,这让我们可以选择以一种更容易理解和验证的方式写出这个值,而不是将这个常量设置为值 10,800。有关声明常量时可以使用哪些操作的更多信息,请参阅 Rust 参考手册中关于常量求值的部分

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.

常量在程序运行的整个时间内都有效,且在声明它们的作用域内。这一特性使得常量对于应用程序域中程序多个部分可能需要知道的值非常有用,例如游戏允许任何玩家获得的最大积分数,或光速。

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 that you would need to change if the hardcoded value needed to be updated in the future.

重影 (Shadowing)

Shadowing

正如你在 第 2 章 的猜数字游戏教程中所看到的,你可以声明一个与之前的变量同名的新变量。Rustaceans 说第一个变量被第二个变量 重影 (shadowed) 了,这意味着当你使用变量名称时,编译器看到的是第二个变量。实际上,第二个变量遮蔽了第一个变量,将所有对变量名的使用都据为己有,直到它自己被重影或作用域结束。我们可以通过使用相同的变量名并重复使用 let 关键字来重影一个变量,如下所示:

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:

文件名:src/main.rs (Filename: src/main.rs)

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs}}
}

这个程序首先将 x 绑定到值 5。然后,它通过重复 let x = 创建一个新变量 x,获取原始值并加上 1,使得 x 的值为 6。接着,在由花括号创建的内部作用域中,第三个 let 语句也重影了 x 并创建了一个新变量,将之前的值乘以 2,使 x 的值为 12。当该作用域结束时,内部重影结束,x 回到 6。当我们运行这个程序时,它将输出以下内容:

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 that the value of x is 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:

{{#include ../listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt}}

重影与将变量标记为 mut 不同,因为如果我们不小心尝试在不使用 let 关键字的情况下重新分配给此变量,我们将得到编译时错误。通过使用 let,我们可以对一个值执行一些变换,但在这些变换完成后使变量保持不可变。

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 completed.

mut 和重影之间的另一个区别是,因为当我们再次使用 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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs:here}}
}

第一个 spaces 变量是字符串类型,第二个 spaces 变量是数字类型。因此,重影让我们免于想出不同的名称,例如 spaces_strspaces_num;相反,我们可以重用更简单的 spaces 名称。但是,如果我们尝试为此使用 mut,如下所示,我们将得到编译时错误:

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:

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs:here}}

错误提示说我们不被允许更改变量的类型:

The error says we’re not allowed to mutate a variable’s type:

{{#include ../listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt}}

现在我们已经探索了变量的工作原理,让我们看看它们可以拥有的更多数据类型。

Now that we’ve explored how variables work, let’s look at more data types they can have.

数据类型 (Data Types)


x-i18n: generated_at: “2026-03-01T13:35:10Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: ea25fb8634eb835bf887c5038786423c09a7a7fe14e802c721e9900dfbe52bc9 source_path: ch03-02-data-types.md workflow: 16

Data Types

数据类型 (Data Types)

Every value in Rust is of a certain data type, which tells Rust what kind of data is being specified so that it knows how to work with that data. We’ll look at two data type subsets: scalar and compound.

Rust 中的每一个值都属于某一种“数据类型 (data type)”,这告诉了 Rust 指定的是哪种数据,以便它知道如何处理这些数据。我们将介绍两类数据类型子集:标量(scalar)和复合(compound)。

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 是一种“静态类型 (statically typed)”语言,这意味着它必须在编译时知道所有变量的类型。编译器通常可以根据值及其使用方式推断出我们想要使用的类型。在可能有多种类型的情况下,例如在第 2 章的“比较猜测数字与秘密数字”部分中,我们使用 parseString 转换为数值类型时,我们必须添加类型注解,如下所示:

#![allow(unused)]
fn main() {
let guess: u32 = "42".parse().expect("Not a number!");
}

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 将显示以下错误,这意味着编译器需要我们提供更多信息才能知道我们要使用哪种类型:

{{#include ../listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt}}

You’ll see different type annotations for other data types.

你也会在其他数据类型中看到不同的类型注解。

Scalar 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.

“标量 (scalar)”类型代表单个值。Rust 有四种主要的标量类型:整数、浮点数、布尔值和字符。你可能在其他编程语言中也见过这些。让我们来看看它们在 Rust 中是如何工作的。

Integer Types

整数类型 (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.

“整数 (integer)”是没有小数部分的数字。我们在第 2 章中使用过一种整数类型,即 u32 类型。这个类型声明表明与之关联的值应该是一个占用 32 位空间的无符号整数(有符号整数类型以 i 开头,而不是 u)。表 3-1 列出了 Rust 中的内置整数类型。我们可以使用这些变体中的任何一个来声明整数值的类型。

Table 3-1: Integer Types in Rust

表 3-1:Rust 中的整数类型

LengthSignedUnsigned
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
Architecture-dependentisizeusize
长度有符号 (Signed)无符号 (Unsigned)
8 位i8u8
16 位i16u16
32 位i32u32
64 位i64u64
128 位i128u128
依赖架构isizeusize

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.

每个变体都可以是有符号的或无符号的,并且具有明确的大小。“有符号 (signed)”和“无符号 (unsigned)”是指数字是否可能为负数——换句话说,数字是否需要带有符号(有符号),或者它是否永远只有正数,因此可以在没有符号的情况下表示(无符号)。这就像在纸上写数字一样:当符号很重要时,数字会显示加号或减号;但是,当可以放心地假设数字为正数时,它就不显示符号。有符号数使用二进制补码 (two’s complement)表示法存储。

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.

每个有符号变体可以存储从 -(2n - 1) 到 2n - 1 - 1(包含端点)的数字,其中 n 是该变体使用的位数。因此,i8 可以存储从 -(27) 到 27 - 1 的数字,即 -128 到 127。无符号变体可以存储从 0 到 2n - 1 的数字,因此 u8 可以存储从 0 到 28 - 1 的数字,即 0 到 255。

Additionally, the isize and usize types depend on the architecture of the computer your program is running on: 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture.

此外,isizeusize 类型取决于程序运行所在的计算机架构:如果你在 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 时的值相同。

Table 3-2: Integer Literals in Rust

表 3-2:Rust 中的整数型字面量

Number literalsExample
Decimal98_222
Hex0xff
Octal0o77
Binary0b1111_0000
Byte (u8 only)b'A'
数字字面量示例
十进制 (Decimal)98_222
十六进制 (Hex)0xff
八进制 (Octal)0o77
二进制 (Binary)0b1111_0000
字节 (Byte,仅限 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。使用 isizeusize 的主要场景是作为某种集合的索引。

Integer Overflow
整数溢出 (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),则会发生“整数溢出 (integer overflow)”,这可能导致两种行为之一。当你在调试模式下编译时,Rust 会包含整数溢出检查,如果发生这种行为,会导致你的程序在运行时“恐慌 (panic)”。Rust 使用“恐慌”一词来描述程序因错误而退出的情况;我们将在第 9 章的“使用 panic! 处理不可恢复的错误”部分深入讨论恐慌。

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 会执行“二进制补码回绕 (two’s complement wrapping)”。简而言之,大于类型可持有最大值的值会“回绕”到该类型可持有值的最小值。在 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 as wrapping_add.
  • 在所有模式下使用 wrapping_* 方法(如 wrapping_add)进行回绕。
  • Return the None value if there is overflow with the checked_* 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

浮点类型 (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 还有两种用于“浮点数 (floating-point numbers)”的原始类型,即带有小数点的数字。Rust 的浮点类型是 f32f64,其大小分别为 32 位和 64 位。默认类型是 f64,因为在现代 CPU 上,它的速度与 f32 大致相同,但精度更高。所有浮点类型都是有符号的。

Here’s an example that shows floating-point numbers in action:

下面是一个展示浮点数运行情况的示例:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs}}
}

Floating-point numbers are represented according to the IEEE-754 standard.

浮点数是根据 IEEE-754 标准表示的。

Numeric Operations

数值运算 (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 语句中使用每种数值运算:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs}}
}

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

布尔类型 (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 中的布尔类型有两个可能的值:truefalse。布尔值的大小为一个字节。Rust 中的布尔类型使用 bool 指定。例如:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs}}
}

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

字符类型 (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 值的示例:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs}}
}

Note that we specify char literals with single quotation marks, as opposed to string literals, which use double quotation marks. Rust’s char type is 4 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; emojis; 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+0000U+D7FF 以及 U+E000U+10FFFF(包含端点)。然而,在 Unicode 中,“字符 (character)”并不是一个真正的概念,因此你对什么是“字符”的直觉可能与 Rust 中的 char 不匹配。我们将在第 8 章的“使用字符串存储 UTF-8 编码的文本”中详细讨论这个话题。

Compound Types

复合类型 (Compound Types)

Compound types can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.

“复合类型 (Compound types)”可以将多个值组合成一个类型。Rust 有两种原始复合类型:元组 (tuple) 和数组 (array)。

The Tuple Type

元组类型 (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.

“元组 (tuple)”是将具有多种类型的多个值组合成一个复合类型的通用方法。元组具有固定长度:一旦声明,它们的大小就不能增加或减少。

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:

我们通过在圆括号内编写逗号分隔的值列表来创建元组。元组中的每个位置都有一个类型,并且元组中不同值的类型不必相同。在这个例子中,我们添加了可选的类型注解:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs}}
}

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 绑定到整个元组,因为元组被视为单个复合元素。要从元组中提取单个值,我们可以使用模式匹配来解构元组值,如下所示:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs}}
}

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 并将其转换为三个独立的变量 xyz。这被称为“解构 (destructuring)”,因为它将单个元组拆分为三个部分。最后,程序打印 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:

我们还可以通过使用句点 (.) 后跟我们要访问的值的索引来直接访问元组元素。例如:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs}}
}

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

数组类型 (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.

拥有多个值集合的另一种方法是使用“数组 (array)”。与元组不同,数组的每个元素必须具有相同的类型。与某些其他语言中的数组不同,Rust 中的数组具有固定长度。

We write the values in an array as a comma-separated list inside square brackets:

我们将数组中的值写在方括号内,作为一个以逗号分隔的列表:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs}}
}

Arrays are useful when you want your data allocated on the stack, the same as the other types we have seen so far, rather than the heap (we will discuss the stack and the heap more in Chapter 4) or when you want to ensure that 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 because its contents live on the heap. 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.

当你希望将数据分配在栈 (stack)(就像我们目前看到的其他类型一样)而不是堆 (heap) 上时(我们将在第 4 章中更多地讨论栈和堆),或者当你希望确保始终具有固定数量的元素时,数组非常有用。不过,数组不如 vector(向量)类型灵活。vector 是由标准库提供的一种类似的集合类型,它“允许”增长或缩小规模,因为它的内容位于堆上。如果你不确定该使用数组还是 vector,很可能你应该使用 vector。 第 8 章 详细讨论了 vector。

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:

但是,当你确切知道元素数量不需要更改时,数组会更有用。例如,如果你在程序中使用月份的名称,你可能会使用数组而不是 vector,因为你知道它将始终包含 12 个元素:

#![allow(unused)]
fn main() {
let months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];
}

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:

你使用方括号编写数组的类型,其中包含每个元素的类型、一个分号,然后是数组中的元素数量,如下所示:

#![allow(unused)]
fn main() {
let a: [i32; 5] = [1, 2, 3, 4, 5];
}

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:

你还可以通过指定初始值,后跟分号,然后在方括号中指定数组长度来初始化一个使每个元素都包含相同值的数组,如下所示:

#![allow(unused)]
fn main() {
let a = [3; 5];
}

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]; 效果相同,但方式更为简洁。

Array Element Access

访问数组元素 (Array Element Access)

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:

数组是已知固定大小的单块内存,可以分配在栈上。你可以使用索引访问数组的元素,如下所示:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs}}
}

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

无效的数组元素访问 (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 章中的猜谜游戏)以从用户那里获取数组索引:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs}}

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 运行此代码并输入 01234,程序将打印出数组中该索引处对应的数值。如果你输入一个超出数组末尾的数字,例如 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)


x-i18n: generated_at: “2026-03-01T13:36:13Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: e7e7b8a143345a7deaf64163ea8a728526fe6d6af6e42f3a5191cd682ae0f268 source_path: ch03-03-how-functions-work.md workflow: 16

函数 (Functions)

Functions

函数在 Rust 代码中无处不在。你已经见过该语言中最重要的函数之一:main 函数,它是许多程序的入口点。你还见过 fn 关键字,它允许你声明新函数。

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 代码使用“蛇形命名法 (snake case)”作为函数和变量名的常规风格,其中所有字母均为小写,并用下划线分隔单词。下面是一个包含示例函数定义的程序:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs}}
}

我们在 Rust 中通过输入 fn 后跟函数名和一对圆括号来定义函数。花括号告诉编译器函数体的开始和结束位置。

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.

我们可以通过输入函数名后跟一对圆括号来调用定义的任何函数。因为 another_function 是在程序中定义的,所以可以在 main 函数内部调用它。注意,我们在源代码中的 main 函数“之后”定义了 another_function;我们也可以在它之前定义。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.

让我们开始一个名为 functions 的新二进制项目,以进一步探索函数。将 another_function 示例放入 src/main.rs 中并运行它。你应该会看到以下输出:

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:

{{#include ../listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt}}

各行按其在 main 函数中出现的顺序执行。首先打印 “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.

参数 (Parameters)

Parameters

我们在定义函数时可以设置“参数 (parameters)”,它们是函数签名的一部分。当函数有参数时,你可以为这些参数提供具体的值。从技术上讲,这些具体的值被称为“实参 (arguments)”,但在日常谈话中,人们往往倾向于将“形参 (parameter)”和“实参 (argument)”这两个词混用,既指函数定义中的变量,也指调用函数时传入的具体值。

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.

在这个版本的 another_function 中,我们添加了一个参数:

In this version of another_function we add a parameter:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs}}
}

尝试运行此程序;你应该会得到以下输出:

Try running this program; you should get the following output:

{{#include ../listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt}}

another_function 的声明有一个名为 x 的参数。x 的类型被指定为 i32。当我们向 another_function 传入 5 时,println! 宏会将格式字符串中包含 x 的那对花括号替换为 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.

在函数签名中,你“必须”声明每个参数的类型。这是 Rust 设计中的一个深思熟虑的决定:要求在函数定义中进行类型注解,意味着编译器几乎永远不需要你在代码的其他地方使用它们来弄清楚你的意图。如果编译器知道函数期望的类型,它也能提供更有帮助的错误消息。

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.

定义多个参数时,请用逗号分隔参数声明,如下所示:

When defining multiple parameters, separate the parameter declarations with commas, like this:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs}}
}

这个例子创建了一个名为 print_labeled_measurement 的函数,它有两个参数。第一个参数名为 value,类型是 i32。第二个参数名为 unit_label,类型是 char。该函数随后打印包含 valueunit_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.

让我们尝试运行这段代码。将当前 functions 项目中 src/main.rs 文件的内容替换为前面的示例,并使用 cargo run 运行它:

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:

{{#include ../listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt}}

因为我们调用该函数时,value 的值为 5unit_label 的值为 'h',所以程序输出中包含了这些值。

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.

语句与表达式 (Statements and Expressions)

Statements and Expressions

函数体由一系列语句组成,可选地以一个表达式结尾。到目前为止,我们介绍的函数还不包含结尾表达式,但你已经见过表达式作为语句的一部分。因为 Rust 是一门基于表达式的语言,所以这是一个需要理解的重要区别。其他语言没有这种区别,所以让我们来看看什么是语句和表达式,以及它们的区别如何影响函数体。

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.

  • “语句 (Statements)”是执行某些操作且不返回值的指令。

  • “表达式 (Expressions)”求值得出一个结果值。

  • 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.

实际上我们已经使用过语句和表达式了。使用 let 关键字创建变量并为其赋值就是一条语句。在示例 3-1 中,let y = 6; 是一条语句。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-01/src/main.rs}}
}

函数定义也是语句;前面的整个示例本身就是一条语句。(不过,正如我们稍后将看到的,调用函数并不是一条语句。)

Function definitions are also statements; the entire preceding example is a statement in itself. (As we’ll see shortly, calling a function is not a statement, though.)

语句不返回值。因此,你不能像下面的代码尝试做的那样,将 let 语句赋值给另一个变量;你会得到一个错误:

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:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs}}

当你运行此程序时,你得到的错误看起来像这样:

When you run this program, the error you’ll get looks like this:

{{#include ../listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/output.txt}}

let y = 6 语句不返回值,所以 x 没有可以绑定的内容。这与其他语言(如 C 和 Ruby)中发生的情况不同,在这些语言中,赋值操作会返回所赋的值。在这些语言中,你可以编写 x = y = 6,并让 xy 的值都为 6;而在 Rust 中并非如此。

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.

表达式求得一个值,构成了你在 Rust 中编写的大部分代码。考虑一个数学运算,例如 5 + 6,这是一个求得值 11 的表达式。表达式可以是语句的一部分:在示例 3-1 中,语句 let y = 6; 中的 6 是一个求得值 6 的表达式。调用函数是一个表达式。调用宏是一个表达式。用花括号创建的新作用域块也是一个表达式,例如:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs}}
}

这个表达式:

This expression:

{
    let x = 3;
    x + 1
}

是一个在该例中求值为 4 的代码块。作为 let 语句的一部分,该值被绑定到 y。注意 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 the x + 1 line without 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.

具有返回值的函数 (Functions with Return Values)

Functions with Return Values

函数可以向调用它们的代码返回值。我们不命名返回值,但必须在箭头 (->) 后声明它们的类型。在 Rust 中,函数的返回值与函数体代码块中最后一个表达式的值同义。你可以通过使用 return 关键字并指定一个值从函数中提前返回,但大多数函数会隐式地返回最后一个表达式。下面是一个返回值的函数示例:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs}}
}

five 函数中没有函数调用、宏,甚至没有 let 语句——只有数字 5 本身。这在 Rust 中是一个完全有效的函数。注意,该函数的返回类型也被指定了,为 -> i32。尝试运行这段代码;输出应该如下所示:

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:

{{#include ../listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt}}

five 中的 5 是函数的返回值,这就是为什么返回类型是 i32。让我们更详细地检查一下。有两个重要的部分:首先,let x = five(); 这一行显示我们正在使用函数的返回值来初始化一个变量。因为函数 five 返回 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:

#![allow(unused)]
fn main() {
let x = 5;
}

其次,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.

让我们看另一个例子:

Let’s look at another example:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs}}
}

运行这段代码将打印 The value of x is: 6。但如果我们在包含 x + 1 的行末尾加上分号,将其从表达式改为语句,会发生什么呢?

Running this code will print The value of x is: 6. But what happens if we place a semicolon at the end of the line containing x + 1, changing it from an expression to a statement?

文件名: src/main.rs

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs}}

编译这段代码将产生如下错误:

Compiling this code will produce an error, as follows:

{{#include ../listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt}}

主要错误消息 mismatched types(类型不匹配)揭示了这段代码的核心问题。函数 plus_one 的定义表明它将返回一个 i32,但语句并不求值得出一个值,这由单元类型 () 表示。因此,没有返回任何内容,这与函数定义矛盾并导致错误。在此输出中,Rust 提供了一条消息来可能帮助纠正此问题:它建议删除分号,这将修复错误。

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.

注释 (Comments)


x-i18n: generated_at: “2026-03-01T13:36:29Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 82b0aac1db631041ec36dc64c6eb115c2a34e0deb062464ee0ed86203b044372 source_path: ch03-04-comments.md workflow: 16

注释 (Comments)

Comments

所有的程序员都力求使他们的代码易于理解,但有时仍需要额外的解释。在这些情况下,程序员会在源代码中留下“注释 (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 that people reading the source code may find useful.

这是一个简单的注释:

Here’s a simple comment:

#![allow(unused)]
fn main() {
// hello, world
}

在 Rust 中,惯用的注释风格是以两个斜杠开始注释,并且注释一直持续到行尾。对于超过一行的注释,你需要在每一行都包含 //,就像这样:

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:

#![allow(unused)]
fn main() {
// So we're doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what's going on.
}

注释也可以放在包含代码的行末:

Comments can also be placed at the end of lines containing code:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs}}
}

但你更常看到这种格式的使用方式,即注释位于其所注释的代码上方的独立行中:

But you’ll more often see them used in this format, with the comment on a separate line above the code it’s annotating:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs}}
}

Rust 还有另一种注释,即文档注释,我们将在第 14 章的“将 Crate 发布到 Crates.io”部分进行讨论。

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.

控制流 (Control Flow)


x-i18n: generated_at: “2026-03-01T13:38:13Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: dcf589530b27653579874f189bf572600a3061712964f525a06844642a2defb6 source_path: ch03-05-control-flow.md workflow: 16

控制流 (Control Flow)

Control Flow

根据条件是否为 true 来运行某些代码,以及在条件为 true 时重复运行某些代码的能力,是大多数编程语言的基本构建模块。在 Rust 中,让你控制执行流最常见的结构是 if 表达式和循环。

The ability to run some code depending on whether a condition is true and the ability 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.

if 表达式 (if Expressions)

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.”

在你的 projects 目录下创建一个名为 branches 的新项目来探索 if 表达式。在 src/main.rs 文件中,输入以下内容:

Create a new project called branches in your projects directory to explore the if expression. In the src/main.rs file, input the following:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs}}
}

所有 if 表达式都以关键字 if 开头,后跟一个条件。在这个例子中,条件检查变量 number 的值是否小于 5。我们将条件为 true 时要执行的代码块放在条件之后的花括号内。与 if 表达式中的条件相关联的代码块有时被称为“分支 (arms)”,就像我们在第 2 章“比较猜测数字与秘密数字”部分讨论过的 match 表达式中的分支一样。

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.

可选地,我们还可以包含一个 else 表达式,我们在这里选择了这样做,以便在条件求值为 false 时为程序提供另一个可执行的代码块。如果你不提供 else 表达式且条件为 false,程序将直接跳过 if 块并继续执行下一段代码。

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.

尝试运行此代码;你应该会看到以下输出:

Try running this code; you should see the following output:

{{#include ../listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt}}

让我们尝试将 number 的值更改为使条件为 false 的值,看看会发生什么:

Let’s try changing the value of number to a value that makes the condition false to see what happens:

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs:here}}

再次运行程序,查看输出:

Run the program again, and look at the output:

{{#include ../listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt}}

还值得注意的是,这段代码中的条件“必须”是一个 bool。如果条件不是 bool,我们会得到一个错误。例如,尝试运行以下代码:

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:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs}}

这次 if 条件求得的值为 3,Rust 抛出了一个错误:

The if condition evaluates to a value of 3 this time, and Rust throws an error:

{{#include ../listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt}}

该错误表明 Rust 期望得到一个 bool 但得到了一个整数。与 Ruby 和 JavaScript 等语言不同,Rust 不会自动尝试将非布尔类型转换为布尔类型。你必须显式地始终为 if 提供一个布尔值作为其条件。例如,如果我们希望 if 代码块仅在数字不等于 0 时运行,我们可以将 if 表达式更改为:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs}}
}

运行这段代码将打印 number was something other than zero

Running this code will print number was something other than zero.

使用 else if 处理多个条件 (Handling Multiple Conditions with else if)

Handling Multiple Conditions with else if

你可以通过在 else if 表达式中组合 ifelse 来使用多个条件。例如:

You can use multiple conditions by combining if and else in an else if expression. For example:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs}}
}

这个程序有四条可能的路径。运行它后,你应该会看到以下输出:

This program has four possible paths it can take. After running it, you should see the following output:

{{#include ../listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt}}

当此程序执行时,它会依次检查每个 if 表达式,并执行第一个条件求值为 true 的代码体。注意,尽管 6 可以被 2 整除,但我们没有看到输出 number is divisible by 2,也没有看到来自 else 块的 number is not divisible by 4, 3, or 2 文本。这是因为 Rust 只执行第一个 true 条件对应的代码块,一旦找到一个,它甚至不会检查剩余的条件。

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.

使用过多的 else if 表达式会使你的代码变得混乱,所以如果你有超过一个,你可能需要重构你的代码。第 6 章描述了 Rust 中一个强大的分支结构,称为 match,用于处理这些情况。

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.

let 语句中使用 if (Using if in a let Statement)

Using if in a let Statement

因为 if 是一个表达式,我们可以将其放在 let 语句的右侧,将结果分配给一个变量,如示例 3-2 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-02/src/main.rs}}
}

number 变量将根据 if 表达式的结果绑定一个值。运行此代码看看会发生什么:

The number variable will be bound to a value based on the outcome of the if expression. Run this code to see what happens:

{{#include ../listings/ch03-common-programming-concepts/listing-03-02/output.txt}}

请记住,代码块求值得出其中最后一个表达式的值,而数字本身也是表达式。在这种情况下,整个 if 表达式的值取决于执行哪个代码块。这意味着 if 的每个分支可能产生的结果必须具有相同的类型;在示例 3-2 中,if 分支和 else 分支的结果都是 i32 整数。如果类型不匹配,如下例所示,我们将得到一个错误:

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:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs}}

当我们尝试编译这段代码时,会得到一个错误。ifelse 分支的值类型不兼容,Rust 准确地指出了程序中出现问题的位置:

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:

{{#include ../listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt}}

if 块中的表达式求值得出一个整数,而 else 块中的表达式求值得出一个字符串。这行不通,因为变量必须具有单一类型,而且 Rust 需要在编译时明确知道 number 变量是什么类型。知道 number 的类型可以让编译器验证在使用 number 的每个地方该类型是否有效。如果 number 的类型仅在运行时确定,Rust 将无法做到这一点;如果编译器必须跟踪任何变量的多种假设类型,它将变得更加复杂,并且对代码提供的保证也会减少。

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 definitively at compile time what type the number variable is. 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.

使用循环重复执行 (Repetition with Loops)

Repetition with Loops

多次执行一个代码块通常很有用。为了完成这项任务,Rust 提供了几种“循环 (loops)”,它们会运行循环体内的代码直到结束,然后立即重新从头开始。为了实验循环,让我们创建一个名为 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 有三种循环:loopwhilefor。让我们逐一尝试。

Rust has three kinds of loops: loop, while, and for. Let’s try each one.

使用 loop 重复代码 (Repeating Code with loop)

loop 关键字告诉 Rust 一遍又一遍地执行一个代码块,直到你显式地告诉它停止。

The loop keyword tells Rust to execute a block of code over and over again either forever or until you explicitly tell it to stop.

作为一个例子,修改 loops 目录下的 src/main.rs 文件,使其看起来像这样:

As an example, change the src/main.rs file in your loops directory to look like this:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs}}

当我们运行此程序时,我们会看到 again! 被不断打印,直到我们手动停止程序。大多数终端支持键盘快捷键 ctrl-C 来中断陷入死循环的程序。试一试:

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-C to interrupt a program that is stuck in a continual loop. Give it a try:

$ cargo run
   Compiling loops v0.1.0 (file:///projects/loops)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
     Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!

符号 ^C 代表你按下 ctrl-C 的位置。

The symbol ^C represents where you pressed ctrl-C.

你可能会也可能不会在 ^C 之后看到打印出的 again! 单词,这取决于代码在接收到中断信号时处于循环的哪个位置。

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.

幸运的是,Rust 还提供了一种使用代码跳出循环的方法。你可以在循环中放置 break 关键字来告诉程序何时停止执行循环。回想一下,我们在第 2 章“猜测正确后退出”部分中在猜谜游戏中执行了此操作,以便在用户通过猜测正确数字赢得游戏时退出程序。

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.

我们还在猜谜游戏中使用了 continue,它在循环中告诉程序跳过此迭代中循环的任何剩余代码,并进入下一次迭代。

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.

从循环中返回值 (Returning Values from Loops)

loop 的用途之一是重试你已知可能会失败的操作,例如检查线程是否已完成其作业。你可能还需要将该操作的结果从循环传出给代码的其余部分。为此,你可以在用于停止循环的 break 表达式之后添加你想要返回的值;该值将从循环中返回,以便你可以使用它,如下所示:

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 that you can use it, as shown here:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs}}
}

在循环之前,我们声明了一个名为 counter 的变量并将其初始化为 0。然后,我们声明一个名为 result 的变量来保存从循环返回的值。在循环的每次迭代中,我们都将 1 加到 counter 变量上,然后检查 counter 是否等于 10。如果是,我们使用 break 关键字并带上值 counter * 2。在循环之后,我们使用分号结束将值分配给 result 的语句。最后,我们打印 result 中的值,在这个例子中是 20

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.

你也可以从循环内部 return。虽然 break 只退出当前循环,但 return 总是退出当前函数。

You can also return from inside a loop. While break only exits the current loop, return always exits the current function.

使用循环标签进行消除歧义 (Disambiguating with Loop Labels)

如果你有循环嵌套循环,breakcontinue 将应用于该点最内层的循环。你可以选择在循环上指定一个“循环标签 (loop label)”,然后将其与 breakcontinue 一起使用,以指定这些关键字应用于带标签的循环,而不是最内层的循环。循环标签必须以单引号开头。这是一个带有两个嵌套循环的示例:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-32-5-loop-labels/src/main.rs}}
}

外层循环具有标签 'counting_up,它将从 0 数到 2。没有标签的内层循环从 10 倒数到 9。第一个没有指定标签的 break 将仅退出内层循环。break 'counting_up; 语句将退出外层循环。这段代码打印:

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:

{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-32-5-loop-labels/output.txt}}

使用 while 简化条件循环 (Streamlining Conditional Loops with while)

程序通常需要在循环中评估一个条件。当条件为 true 时,循环运行。当条件不再为 true 时,程序调用 break 停止循环。可以使用 loopifelsebreak 的组合来实现这种行为;如果你愿意,现在可以在程序中尝试一下。然而,这种模式非常常见,以至于 Rust 为其提供了一个内置的语言结构,称为 while 循环。在示例 3-3 中,我们使用 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, to print a message and exit.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-03/src/main.rs}}
}

如果你使用 loopifelsebreak,这种结构消除了很多必要的嵌套,并且更清晰。只要条件求值为 true,代码就会运行;否则,它将退出循环。

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.

使用 for 遍历集合 (Looping Through a Collection with for)

你可以选择使用 while 结构来遍历集合(如数组)的元素。例如,示例 3-4 中的循环打印数组 a 中的每个元素。

You can choose to 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-04/src/main.rs}}
}

在这里,代码对数组中的元素进行计数。它从索引 0 开始,然后循环直到达到数组中的最后一个索引(即当 index < 5 不再为 true 时)。运行此代码将打印数组中的每个元素:

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:

{{#include ../listings/ch03-common-programming-concepts/listing-03-04/output.txt}}

如预期的那样,所有五个数组值都出现在终端中。尽管 index 会在某个时刻达到 5,但循环在尝试从数组中获取第六个值之前就会停止执行。

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.

然而,这种方法容易出错;如果索引值或测试条件不正确,我们可能会导致程序恐慌。例如,如果你将 a 数组的定义更改为包含四个元素,但忘记将条件更新为 while index < 4,代码就会恐慌。它的速度也很慢,因为编译器会添加运行时代码,以便在每次循环迭代时执行索引是否在数组范围内的条件检查。

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.

作为一个更简洁的替代方案,你可以使用 for 循环,并为集合中的每一项执行某些代码。for 循环看起来像示例 3-5 中的代码。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-05/src/main.rs}}
}

当我们运行这段代码时,我们会看到与示例 3-4 相同的输出。更重要的是,我们现在提高了代码的安全性,并消除了因超出数组末尾或没数到头而遗漏某些项而可能产生的 bug。由 for 循环生成的机器代码也可以更高效,因为不需要在每次迭代时将索引与数组长度进行比较。

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. Machine code generated from for loops can be more efficient as well because the index doesn’t need to be compared to the length of the array at every iteration.

使用 for 循环,如果你更改了数组中值的数量,你不需要像使用示例 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 循环的安全性及其简洁性使其成为 Rust 中最常用的循环结构。即使在你想运行某些代码特定次数的情况下,比如在示例 3-3 中使用 while 循环的倒数例子,大多数 Rustaceans 也会使用 for 循环。实现的方法是使用标准库提供的 Range,它可以按顺序生成从一个数字开始、在另一个数字之前结束的所有数字。

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 循环和另一个我们尚未谈到的方法 rev(用于反转范围)实现的倒数样子:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs}}
}

这段代码看起来更漂亮了,不是吗?

This code is a bit nicer, isn’t it?

总结 (Summary)

Summary

你做到了!这是一个相当大的章节:你学习了变量、标量和复合数据类型、函数、注释、if 表达式和循环!为了练习本章讨论的概念,请尝试构建程序来执行以下操作:

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:

  • 在华氏温度和摄氏温度之间转换。

  • 生成第 n 个斐波那契数。

  • 打印圣诞颂歌“圣诞节的十二天 (The Twelve Days of Christmas)”的歌词,利用歌曲中的重复性。

  • Convert temperatures between Fahrenheit and Celsius.

  • Generate the nth Fibonacci number.

  • Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song.

当你准备好继续前进时,我们将讨论 Rust 中一个在其他编程语言中通常“不存在”的概念:所有权 (ownership)。

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.

理解所有权 (Understanding Ownership)


x-i18n: generated_at: “2026-03-01T13:38:28Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: c928725db99b50317a78423e90e790868e7efa4ffb87c62062b71ad6f3b5e59f source_path: ch04-00-understanding-ownership.md workflow: 16

理解所有权 (Understanding Ownership)

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.

所有权 (Ownership) 是 Rust 最独特的功能,对语言的其余部分有着深远的影响。它使 Rust 能够在不需要垃圾回收器的情况下做出内存安全保证,因此了解所有权的工作原理非常重要。在本章中,我们将讨论所有权以及几个相关功能:借用 (borrowing)、切片 (slices) 以及 Rust 如何在内存中布局数据。

什么是所有权? (What is Ownership?)


x-i18n: generated_at: “2026-03-01T13:40:28Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 873724c6862ad0cc447becf0e818eb39a324c5d4bfa26ef721286aae1941c0ba source_path: ch04-01-what-is-ownership.md workflow: 16

什么是所有权? (What Is Ownership?)

What Is Ownership?

“所有权 (Ownership)”是 Rust 程序管理内存的一套规则。所有程序在运行时都必须管理它们使用计算机内存的方式。一些语言具有垃圾回收机制,在程序运行时定期寻找不再使用的内存;在其他语言中,程序员必须显式地分配和释放内存。Rust 采用了第三种方法:通过所有权系统管理内存,该系统具有一组编译器检查的规则。如果违反了任何规则,程序将无法编译。所有权的任何功能都不会在程序运行时减慢速度。

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 和所有权系统规则越熟悉,你就越能自然地开发出既安全又高效的代码。坚持下去!

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.

栈和堆 (The Stack and the Heap)

The Stack and the Heap

许多编程语言并不要求你经常思考栈 (stack) 和堆 (heap)。但在像 Rust 这样的系统编程语言中,值是在栈上还是在堆上会影响语言的行为以及你为什么必须做出某些决定。本章稍后将结合栈和堆来描述所有权的部分内容,因此这里先做一个简要的解释作为准备。

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.

栈和堆都是程序在运行时可用的内存部分,但它们的结构方式不同。栈按接收值的顺序存储值,并按相反的顺序删除值。这被称为“后进先出 (last in, first out,LIFO)”。想象一叠盘子:当你添加更多盘子时,你把它们放在那叠盘子的顶部,当你需要盘子时,你从顶部取下一个。从中间或底部添加或移除盘子就不那么方便了!添加数据被称为“压入栈 (pushing onto the stack)”,移除数据被称为“弹出栈 (popping off the stack)”。所有存储在栈上的数据必须具有已知的、固定的大小。在编译时大小未知或大小可能发生变化的数据必须存储在堆上。

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 (LIFO). 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.

堆的组织性较弱:当你把数据放在堆上时,你会请求一定数量的空间。内存分配器在堆中找到一个足够大的空位,将其标记为正在使用,并返回一个“指针 (pointer)”,即该位置的地址。这个过程被称为“在堆上分配 (allocating on the heap)”,有时简称为“分配 (allocating)”(将值压入栈不被视为分配)。由于指向堆的指针具有已知的固定大小,你可以将指针存储在栈上,但当你想要实际数据时,必须跟随指针。想象一下在餐厅就座。当你进入时,你说明你这组的人数,领位员会找到一张适合所有人的空桌子并领你过去。如果你这组中有人来晚了,他们可以询问你坐在哪里来找到你。

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.

访问堆中的数据通常比访问栈上的数据慢,因为你必须跟随指针才能到达那里。如果处理器在内存中跳跃较少,现代处理器的速度会更快。继续这个类比,考虑餐厅的服务员为许多桌子点餐。在移动到下一张桌子之前点完一张桌子上的所有订单是最有效的。从 A 桌点一个菜,然后从 B 桌点一个菜,然后再从 A 桌点一个菜,然后再从 B 桌点一个菜,这将是一个慢得多的过程。出于同样的原因,如果处理器处理与其他数据物理距离较近的数据(如在栈上),而不是较远的数据(如在堆上),它通常可以更好地完成工作。

Accessing data in the heap is generally 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 usually 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).

当你的代码调用函数时,传递给函数的值(可能包括指向堆上数据的指针)和函数的局部变量会被压入栈。当函数结束时,这些值会从栈中弹出。

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 that 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)

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:

  • Rust 中的每个值都有一个“所有者 (owner)”。

  • 同一时间只能有一个所有者。

  • 当所有者超出作用域时,该值将被删除。

  • Each value in Rust has an owner.

  • There can only be one owner at a time.

  • When the owner goes out of scope, the value will be dropped.

变量作用域 (Variable Scope)

Variable Scope

既然我们已经了解了 Rust 的基本语法,在示例中我们将不再包含所有的 fn main() { 代码。因此,如果你在跟着练习,请确保手动将以下示例放入 main 函数中。这样,我们的示例将更加简洁,让我们能够专注于实际细节而不是样板代码。

Now that we’re past basic Rust syntax, we won’t include all the fn main() { code in the 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.

作为所有权的第一个例子,我们将观察一些变量的“作用域 (scope)”。作用域是程序中某个项有效的范围。以以下变量为例:

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:

#![allow(unused)]
fn main() {
let s = "hello";
}

变量 s 指向一个字符串字面量,其中字符串的值被硬编码在程序的文本中。该变量从声明点开始有效,直到当前作用域结束。示例 4-1 显示了一个带有注释的程序,标注了变量 s 有效的位置。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-01/src/main.rs:here}}
}

换句话说,这里有两个重要时间点:

In other words, there are two important points in time here:

  • s “进入”作用域时,它是有效的。

  • 它一直保持有效,直到“超出”作用域。

  • When s comes into scope, it is valid.

  • It remains valid until it goes out of scope.

在这一点上,作用域与变量何时有效的关系与其他编程语言类似。现在我们将通过引入 String 类型来进一步加深这种理解。

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)

The String Type

为了说明所有权规则,我们需要一种比我们在第 3 章“数据类型”部分介绍的类型更复杂的数据类型。之前介绍的类型大小已知,可以存储在栈上,当它们的作用域结束时从栈中弹出,并且如果代码的其他部分需要在不同的作用域使用相同的值,可以快速且简单地进行复制以创建一个新的、独立的实例。但我们想要观察存储在堆上的数据,并探索 Rust 如何知道何时清理这些数据,而 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.

我们将专注于 String 中与所有权相关的部分。这些方面也适用于其他复杂的数据类型,无论它们是由标准库提供的还是由你创建的。我们将在第 8 章讨论 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 non-ownership aspects of String in Chapter 8.

我们已经见过字符串字面量,即硬编码在程序中的字符串值。字符串字面量很方便,但并不适用于我们可能想要使用文本的所有情况。原因之一是它们是不可变的。另一个原因是在编写代码时,并非每个字符串值都是已知的:例如,如果我们想获取用户输入并将其存储起来该怎么办?针对这些情况,Rust 提供了 String 类型。此类型管理分配在堆上的数据,因此能够存储我们在编译时未知的文本量。你可以使用 from 函数从字符串字面量创建一个 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? It is for these situations that Rust has the String type. 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:

#![allow(unused)]
fn main() {
let s = String::from("hello");
}

双冒号 :: 运算符允许我们将这个特定的 from 函数命名空间置于 String 类型下,而不是使用类似 string_from 的名称。我们将在第 5 章的“方法”部分以及第 7 章“在模块树中引用项的路径”讨论使用模块的命名空间时,进一步讨论这种语法。

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 “Methods” 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.

这种类型的字符串“可以”被修改:

This kind of string can be mutated:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs:here}}
}

那么,这里的区别是什么?为什么 String 可以被修改而字面量却不行?区别在于这两种类型处理内存的方式不同。

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.

内存与分配 (Memory and Allocation)

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.

对于 String 类型,为了支持可变的、可增长的文本片段,我们需要在堆上分配一定数量的内存在编译时未知的数据以保存内容。这意味着:

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::from 时,它的实现会请求它需要的内存。这在编程语言中几乎是通用的。

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.

然而,第二部分有所不同。在具有“垃圾回收器 (garbage collector,GC)”的语言中,GC 会跟踪并清理不再使用的内存,我们不需要思考这个问题。在大多数没有 GC 的语言中,我们有责任识别内存何时不再使用,并调用代码显式释放它,就像我们请求它一样。正确地做到这一点历来是一个困难的编程问题。如果我们忘记了,我们将浪费内存。如果我们做得太早,我们将得到一个无效的变量。如果我们做两次,那也是一个 bug。我们需要将恰好一个 allocate(分配)与恰好一个 free(释放)配对。

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.

Rust 走了一条不同的路:一旦拥有内存的变量超出作用域,内存就会自动返回。这里是示例 4-1 中作用域示例的一个版本,使用了 String 而不是字符串字面量:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs:here}}
}

有一个自然的时间点,我们可以将 String 所需的内存返回给分配器:当 s 超出作用域时。当变量超出作用域时,Rust 为我们调用一个特殊的函数。这个函数被称为 dropString 的作者可以在其中放入返回内存的代码。Rust 在结束花括号处自动调用 drop

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.

注意:在 C++ 中,这种在项的生命周期结束时释放资源的模式有时被称为“资源获取即初始化 (Resource Acquisition Is Initialization,RAII)”。如果你使用过 RAII 模式,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.

这种模式对 Rust 代码的编写方式有着深远的影响。现在看来可能很简单,但在更复杂的情况下,当我们想要让多个变量使用我们在堆上分配的数据时,代码的行为可能是意想不到的。让我们现在来探索其中的一些情况。

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.

变量与数据交互的方式:移动 (Variables and Data Interacting with Move)

在 Rust 中,多个变量可以以不同的方式与相同的数据进行交互。示例 4-2 显示了一个使用整数的例子。

Multiple variables can interact with the same data in different ways in Rust. Listing 4-2 shows an example using an integer.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-02/src/main.rs:here}}
}

我们大概可以猜到这是在做什么:“将值 5 绑定到 x;然后,对 x 中的值做一个拷贝并将其绑定到 y。”我们现在有两个变量 xy,它们都等于 5。这确实是正在发生的情况,因为整数是具有已知固定大小的简单值,并且这两个 5 的值被压入了栈。

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.

现在让我们来看看 String 版本:

Now let’s look at the String version:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs:here}}
}

这看起来非常相似,所以我们可能会假设它的工作方式是相同的:即第二行会对 s1 中的值做一个拷贝并将其绑定到 s2。但这并不是完全发生的事情。

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.

看看图 4-1,了解 String 内部发生了什么。String 由三部分组成,如左图所示:一个指向存放字符串内容内存的指针、一个长度和一个容量。这组数据存储在栈上。右图是堆上存放内容的内存。

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.

两张表格:第一张表包含了 s1 在栈上的表示,由其长度 (5)、容量 (5) 以及一个指向第二张表中第一个值的指针组成。第二张表包含了字符串数据在堆上的表示,逐字节显示。

图 4-1:绑定到 s1 的持有值 "hello"String 在内存中的表示

长度是 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.

当我们把 s1 分配给 s2 时,String 数据被复制了,这意味着我们复制了栈上的指针、长度和容量。我们并没有复制指针指向的堆上的数据。换句话说,内存中的数据表示如图 4-2 所示。

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 分别代表栈上的那些字符串,并且都指向堆上的相同字符串数据。

图 4-2:变量 s2 的内存表示,它持有 s1 的指针、长度和容量的拷贝

这种表示“不”如图 4-3 所示,即如果 Rust 也复制堆数据,内存看起来会是什么样子。如果 Rust 这样做,如果堆上的数据很大,那么操作 s2 = s1 在运行时性能方面可能会非常昂贵。

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.

四张表格:两张表格代表 s1 和 s2 的栈数据,每张表都指向自己在堆上的字符串数据拷贝。

图 4-3:如果 Rust 也复制堆数据,s2 = s1 可能做的另一种可能性

早些时候,我们说过当变量超出作用域时,Rust 会自动调用 drop 函数并清理该变量的堆内存。但图 4-2 显示两个数据指针指向同一个位置。这是一个问题:当 s2s1 超出作用域时,它们都会尝试释放相同的内存。这被称为“双重释放 (double free)”错误,是之前提到的内存安全 bug 之一。释放内存两次可能导致内存损坏,进而可能导致安全漏洞。

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.

为了确保内存安全,在 let s2 = s1; 行之后,Rust 认为 s1 不再有效。因此,当 s1 超出作用域时,Rust 不需要释放任何东西。看看当你尝试在创建 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:

{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs:here}}

你会得到一个类似这样的错误,因为 Rust 阻止你使用失效的引用:

You’ll get an error like this because Rust prevents you from using the invalidated reference:

{{#include ../listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt}}

如果你在接触其他语言时听说过“浅拷贝 (shallow copy)”和“深拷贝 (deep copy)”,那么复制指针、长度和容量而不复制数据的概念听起来可能就像进行浅拷贝。但由于 Rust 还会使第一个变量失效,因此它不被称为浅拷贝,而是被称为“移动 (move)”。在这个例子中,我们会说 s1 被“移动”到了 s2 中。因此,实际发生的情况如图 4-4 所示。

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.

三张表格:表 s1 和 s2 分别代表栈上的那些字符串,并且都指向堆上的相同字符串数据。表 s1 变灰,因为 s1 不再有效;只有 s2 可以用于访问堆数据。

图 4-4:s1 失效后的内存表示

这解决了我们的问题!由于只有 s2 有效,当它超出作用域时,只有它会释放内存,我们就完成了。

That solves our problem! With only s2 valid, when it goes out of scope it alone will free the memory, and we’re done.

此外,这还隐含了一个设计选择:Rust 永远不会自动创建数据的“深”拷贝。因此,任何“自动”复制都可以被认为在运行时性能方面开销较小。

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.

作用域与赋值 (Scope and Assignment)

Scope and Assignment

与此相反,作用域、所有权以及通过 drop 函数释放内存之间的关系也同样适用于赋值。当你为一个现有变量分配一个全新的值时,Rust 会调用 drop 并立即释放原始值的内存。例如,考虑这段代码:

The inverse of this is true for the relationship between scoping, ownership, and memory being freed via the drop function as well. When you assign a completely new value to an existing variable, Rust will call drop and free the original value’s memory immediately. Consider this code, for example:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-04b-replacement-drop/src/main.rs:here}}
}

我们最初声明一个变量 s 并将其绑定到一个值为 "hello"String。然后,我们立即创建一个值为 "ahoy" 的新 String 并将其分配给 s。此时,没有任何东西再指向堆上的原始值。图 4-5 说明了现在的栈和堆数据:

We initially declare a variable s and bind it to a String with the value "hello". Then, we immediately create a new String with the value "ahoy" and assign it to s. At this point, nothing is referring to the original value on the heap at all. Figure 4-5 illustrates the stack and heap data now:

一张代表栈上字符串值的表格,指向堆上的第二段字符串数据 (ahoy),原来的字符串数据 (hello) 变灰,因为它再也无法被访问了。

图 4-5:初始值被整体替换后的内存表示

因此,原始字符串立即超出作用域。Rust 将对其运行 drop 函数,其内存将立即被释放。当我们最后打印该值时,它将是 "ahoy, world!"

The original string thus immediately goes out of scope. Rust will run the drop function on it and its memory will be freed right away. When we print the value at the end, it will be "ahoy, world!".

变量与数据交互的方式:克隆 (Variables and Data Interacting with Clone)

如果我们“确实”想要深度复制 String 的堆数据,而不仅仅是栈数据,我们可以使用一个常用的方法叫做 clone。我们将在第 5 章讨论方法语法,但由于方法是许多编程语言的共同特征,你可能以前见过它们。

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.

这里是 clone 方法运行的一个例子:

Here’s an example of the clone method in action:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs:here}}
}

这工作得很好,并显式地产生了如图 4-3 所示的行为,即堆数据“确实”被复制了。

This works just fine and explicitly produces the behavior shown in Figure 4-3, where the heap data does get copied.

当你看到对 clone 的调用时,你就知道某些任意代码正在被执行,并且该代码的开销可能很大。它是一个视觉指示器,表明正在发生一些不同的事情。

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.

只限栈的数据:拷贝 (Stack-Only Data: Copy)

Stack-Only Data: Copy

还有一个我们还没谈到的细节。这段使用整数的代码——其中一部分显示在示例 4-2 中——是可以运行且有效的:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs:here}}
}

但这代码似乎与我们刚刚学到的相矛盾:我们没有调用 clone,但 x 仍然有效,并没有被移动到 y 中。

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.

原因是像整数这样在编译时具有已知大小的类型完全存储在栈上,因此实际值的拷贝可以快速完成。这意味着我们没有理由在创建变量 y 之后阻止 x 继续有效。换句话说,这里的深拷贝和浅拷贝没有区别,因此调用 clone 不会比通常的浅拷贝多做任何事情,我们可以省去它。

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.

Rust 有一个特殊的注解,叫做 Copy 特征 (trait),我们可以将其放置在像整数这样存储在栈上的类型上(我们将在第 10 章更多地讨论特征)。如果一个类型实现了 Copy 特征,使用它的变量不会发生移动,而是简单地被拷贝,使它们在分配给另一个变量后仍然有效。

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.

如果类型或其任何部分实现了 Drop 特征,Rust 将不允许我们为该类型标注 Copy。如果该类型在值超出作用域时需要发生一些特殊操作,而我们为该类型添加了 Copy 注解,我们将得到一个编译时错误。要了解如何为你的类型添加 Copy 注解以实现该特征,请参阅附录 C 中的“可派生特征”

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.

那么,哪些类型实现了 Copy 特征呢?你可以查看给定类型的文档来确定,但作为一般规则,任何简单标量值的组合都可以实现 Copy,任何需要分配内存或属于某种资源的东西都不能实现 Copy。以下是一些实现 Copy 的类型:

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:

  • 所有整数类型,例如 u32

  • 布尔类型 bool,具有值 truefalse

  • 所有浮点类型,例如 f64

  • 字符类型 char

  • 元组,如果它们仅包含也实现 Copy 的类型。例如,(i32, i32) 实现了 Copy,但 (i32, String) 则没有。

  • All the integer types, such as u32.

  • The Boolean type, bool, with values true and false.

  • All the floating-point types, such as f64.

  • The character type, char.

  • Tuples, if they only contain types that also implement Copy. For example, (i32, i32) implements Copy, but (i32, String) does not.

所有权与函数 (Ownership and Functions)

Ownership and Functions

将值传递给函数的机制与将值分配给变量类似。向函数传递变量会发生移动或拷贝,就像赋值一样。示例 4-3 有一个带有注释的例子,显示了变量进入和超出作用域的位置。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-03/src/main.rs}}
}

如果我们尝试在调用 takes_ownership 后使用 s,Rust 会抛出编译时错误。这些静态检查保护我们免受错误的影响。尝试向 main 添加使用 sx 的代码,看看在哪里可以使用它们,以及所有权规则在哪里阻止你这样做。

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.

返回值与作用域 (Return Values and Scope)

Return Values and Scope

返回值也可以转移所有权。示例 4-4 显示了一个返回某些值的函数示例,带有与示例 4-3 中类似的标注。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-04/src/main.rs}}
}

变量的所有权每次都遵循相同的模式:将值分配给另一个变量会发生移动。当包含堆上数据的变量超出作用域时,除非数据的所有权已移动到另一个变量,否则该值将被 drop 清理。

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.

虽然这种方法可行,但在每个函数中获取所有权然后又返回所有权有点繁琐。如果我们想让函数使用值但不获取所有权该怎么办?如果我们想再次使用传递进去的任何东西,它也需要被传回来,再加上我们可能想要返回的函数体产生的任何数据,这非常令人烦恼。

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 确实允许我们使用元组返回多个值,如示例 4-5 所示。

Rust does let us return multiple values using a tuple, as shown in Listing 4-5.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-05/src/main.rs}}
}

但对于一个应该是很常见的概念来说,这种做法太过于仪式化,且工作量很大。幸运的是,Rust 有一个功能可以让我们在不转移所有权的情况下使用值:引用。

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: references.

引用与借用 (References and Borrowing)


x-i18n: generated_at: “2026-03-01T13:40:54Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 7d983eec6235630df6e85c7a5b4cfbdfc7c380c780f60774df65ba2fa1d05ca4 source_path: ch04-02-references-and-borrowing.md workflow: 16

引用与借用 (References and Borrowing)

References and Borrowing

示例 4-5 中元组代码的问题在于,我们必须将 String 返回给调用函数,以便在调用 calculate_length 之后仍能使用该 String,因为 String 已被移动到了 calculate_length 中。相反,我们可以提供对 String 值的“引用 (reference)”。引用就像指针,因为它是一个地址,我们可以通过该地址访问存储在其中的数据;而该数据归其他变量所有。与指针不同的是,引用保证在引用的生命周期内指向特定类型的有效值。

The issue with the tuple code in Listing 4-5 is that we have to return the String to the calling function so that 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.

下面是你如何定义和使用一个 calculate_length 函数,该函数将对象的引用作为参数,而不是获取值的所有权:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs:all}}
}

首先,请注意变量声明和函数返回值中所有的元组代码都消失了。其次,请注意我们将 &s1 传递给 calculate_length,并且在其定义中,我们接收的是 &String 而不是 String。这些 & 符号代表“引用 (references)”,它们允许你引用某些值而不获取其所有权。图 4-6 描绘了这一概念。

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-6 depicts this concept.

三张表格:s 表格仅包含指向 s1 表格的指针。s1 表格包含 s1 的栈数据,并指向堆上的字符串数据。

图 4-6:&String s 指向 String s1 的图示

注意:与使用 & 进行引用的相反操作是“解引用 (dereferencing)”,它是通过解引用运算符 * 完成的。我们将在第 8 章看到解引用运算符的一些用法,并在第 15 章讨论解引用的细节。

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.

让我们仔细看看这里的函数调用:

Let’s take a closer look at the function call here:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs:here}}
}

&s1 语法让我们创建一个“指向 (refers)”s1 的值但不拥有它的引用。因为引用不拥有它,所以当引用停止使用时,它指向的值不会被删除。

The &s1 syntax lets us create a reference that refers to the value of s1 but does not own it. Because the reference does not own it, the value it points to will not be dropped when the reference stops being used.

同样,函数签名使用 & 来指示参数 s 的类型是一个引用。让我们添加一些解释性的标注:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs:here}}
}

变量 s 有效的作用域与任何函数参数的作用域相同,但是当 s 停止使用时,引用指向的值不会被删除,因为 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.

我们将创建引用的行为称为“借用 (borrowing)”。就像在现实生活中一样,如果一个人拥有某样东西,你可以从他们那里借来。当你用完后,你必须把它还回去。你不拥有它。

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.

那么,如果我们尝试修改正在借用的东西会发生什么呢?尝试示例 4-6 中的代码。剧透警告:它行不通!

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!

{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-06/src/main.rs}}

这是错误信息:

Here’s the error:

{{#include ../listings/ch04-understanding-ownership/listing-04-06/output.txt}}

正如变量默认是不可变的一样,引用也是不可变的。我们不允许修改我们拥有引用的内容。

Just as variables are immutable by default, so are references. We’re not allowed to modify something we have a reference to.

可变引用 (Mutable References)

Mutable References

我们可以通过一些小小的调整来修复示例 4-6 中的代码,通过使用“可变引用 (mutable reference)”来允许我们修改借用的值:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs}}
}

首先,我们将 s 更改为 mut。然后,我们在调用 change 函数的地方使用 &mut s 创建一个可变引用,并更新函数签名以接受 some_string: &mut String 类型的可变引用。这非常清楚地表明 change 函数将修改它借用的值。

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 的可变引用的代码将会失败:

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:

{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs:here}}

这是错误信息:

Here’s the error:

{{#include ../listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt}}

这个错误表明这段代码是无效的,因为我们不能在同一时间多次将 s 借用为可变的。第一次可变借用在 r1 中,并且必须持续到它在 println! 中被使用,但在创建该可变引用及其使用之间,我们尝试在 r2 中创建另一个借用与 r1 相同数据的可变引用。

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.

防止同一时间对同一数据进行多个可变引用的限制允许修改,但方式受控。这是新 Rustaceans 经常挣扎的问题,因为大多数语言允许你随时随地进行修改。拥有此限制的好处是 Rust 可以在编译时防止“数据竞争 (data races)”。数据竞争类似于竞争条件 (race condition),当以下三种行为发生时就会出现:

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:

  • 两个或多个指针同时访问同一数据。

  • 至少有一个指针正在用于写入数据。

  • 没有使用同步访问数据的机制。

  • 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.

数据竞争会导致未定义的行为,并且在你尝试在运行时追踪它们时很难诊断和修复;Rust 通过拒绝编译带有数据竞争的代码来防止此问题!

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!

一如既往,我们可以使用花括号创建一个新的作用域,允许存在多个可变引用,但不是“同时”存在:

As always, we can use curly brackets to create a new scope, allowing for multiple mutable references, just not simultaneous ones:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs:here}}
}

Rust 对于组合可变引用和不可变引用也强制执行类似的规则。这段代码会导致错误:

Rust enforces a similar rule for combining mutable and immutable references. This code results in an error:

{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs:here}}

这是错误信息:

Here’s the error:

{{#include ../listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt}}

呼!当我们拥有指向某个值的不可变引用时,我们“也不能”拥有该值的可变引用。

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.

请注意,引用的作用域从引入它的地方开始,一直持续到该引用最后一次被使用。例如,这段代码可以编译,因为不可变引用最后一次使用是在 println! 中,即在引入可变引用之前:

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 is in the println!, before the mutable reference is introduced:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs:here}}
}

不可变引用 r1r2 的作用域在它们最后一次使用的 println! 之后结束,这发生在创建可变引用 r3 之前。这些作用域没有重叠,因此这段代码是允许的:编译器可以判断出在作用域结束之前的一点,引用就不再被使用了。

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.

尽管借用错误有时可能令人沮丧,但请记住,这是 Rust 编译器在早期(在编译时而不是在运行时)指出潜在的 bug,并向你准确展示问题所在。这样,你就不必追踪为什么你的数据不是你想象中的样子了。

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.

悬垂引用 (Dangling References)

Dangling References

在拥有指针的语言中,很容易通过释放某些内存同时保留指向该内存的指针,从而错误地创建一个“悬垂指针 (dangling pointer)”——即引用内存中可能已分配给其他人的位置的指针。相比之下,在 Rust 中,编译器保证引用永远不会是悬垂引用:如果你拥有对某些数据的引用,编译器将确保数据不会在引用之前超出作用域。

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:

{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs}}

这是错误信息:

Here’s the error:

{{#include ../listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt}}

这条错误消息提到了一个我们尚未介绍的功能:生命周期 (lifetimes)。我们将在第 10 章详细讨论生命周期。但是,如果你忽略有关生命周期的部分,该消息确实包含了为什么这段代码有问题的关键:

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:

this function's return type contains a borrowed value, but there is no value
for it to be borrowed from

(该函数的返回类型包含一个借用的值,但没有可供借用的值)

让我们仔细看看 dangle 代码的每个阶段究竟发生了什么:

Let’s take a closer look at exactly what’s happening at each stage of our dangle code:

{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs:here}}

由于 s 是在 dangle 内部创建的,当 dangle 的代码执行完毕后,s 将被释放。但我们尝试返回指向它的引用。这意味着这个引用将指向一个无效的 String。这可不行!Rust 不允许我们这样做。

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.

这里的解决方案是直接返回 String

The solution here is to return the String directly:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs:here}}
}

这工作起来没有任何问题。所有权被移出,没有任何东西被释放。

This works without any problems. Ownership is moved out, and nothing is deallocated.

引用的规则 (The Rules of References)

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.

接下来,我们将了解另一种引用:切片 (slices)。

Next, we’ll look at a different kind of reference: slices.

切片类型 (The Slice Type)


x-i18n: generated_at: “2026-03-01T13:42:06Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: fb0ac90f3652f4096624bc008f2a5ade603ed1d7af078281cec7a88da66e82bb source_path: ch04-03-slices.md workflow: 16

切片类型 (The Slice Type)

The Slice Type

“切片 (Slices)”让你能引用集合 (collection)中连续的一系列元素。切片是一种引用,因此它没有所有权。

Slices let you reference a contiguous sequence of elements in a 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.

注意:为了介绍切片,本节我们假设仅使用 ASCII;关于 UTF-8 处理的更详尽讨论请参见第 8 章的“使用字符串存储 UTF-8 编码的文本”部分。

Note: For the purposes of introducing 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.

让我们先看看在不使用切片的情况下如何编写此函数的签名,以理解切片将解决的问题:

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) -> ?

first_word 函数有一个类型为 &String 的参数。我们不需要所有权,所以这没问题。(在惯用的 Rust 中,除非需要,否则函数不会获取其参数的所有权,随着深入学习,其原因会变得清晰。)但我们应该返回什么呢?我们并没有真正的方法来表达字符串的“一部分”。然而,我们可以返回单词结尾的索引,由空格表示。让我们尝试一下,如示例 4-7 所示。

The first_word function has a parameter of type &String. We don’t need ownership, so this is fine. (In idiomatic Rust, functions do not take ownership of their arguments unless they need to, and the reasons for that will become clear as we keep going.) 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-07/src/main.rs:here}}
}

因为我们需要逐个元素地检查 String 并检查值是否为空格,所以我们将使用 as_bytes 方法将 String 转换为字节数组。

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.

{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-07/src/main.rs:as_bytes}}

接下来,我们使用 iter 方法在字节数组上创建一个迭代器:

Next, we create an iterator over the array of bytes using the iter method:

{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-07/src/main.rs:iter}}

我们将在第 13 章中更详细地讨论迭代器。目前,只需知道 iter 是一个返回集合中每个元素的方法,而 enumerate 包装了 iter 的结果,并将每个元素作为元组的一部分返回。enumerate 返回的元组的第一个元素是索引,第二个元素是该元素的引用。这比我们自己计算索引要方便一些。

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.

因为 enumerate 方法返回一个元组,所以我们可以使用模式来解构该元组。我们将在第 6 章中更多地讨论模式。在 for 循环中,我们指定了一个模式,其中 i 代表元组中的索引,&item 代表元组中的单个字节。因为我们从 .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.

for 循环内部,我们通过使用字节字面量语法搜索代表空格的字节。如果我们找到了空格,就返回该位置。否则,我们通过使用 s.len() 返回字符串的长度。

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().

{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-07/src/main.rs:inside_for}}

我们现在有一种方法可以找出字符串中第一个单词结尾的索引,但有一个问题。我们只返回了一个 usize,但它只有在 &String 的上下文中才是有意义的数字。换句话说,因为它是一个独立于 String 的值,所以无法保证它在将来仍然有效。考虑示例 4-8 中的程序,它使用了示例 4-7 中的 first_word 函数。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-08/src/main.rs:here}}
}

该程序编译时没有任何错误,如果我们在调用 s.clear() 之后使用 word 也是如此。因为 words 的状态完全没有联系,所以 word 仍然包含值 5。我们可以将该值 5 与变量 s 一起使用,尝试提取出第一个单词,但这将是一个 bug,因为自从我们在 word 中保存 5 以来,s 的内容已经发生了变化。

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.

必须担心 word 中的索引与 s 中的数据不同步是乏味且容易出错的!如果我们编写一个 second_word 函数,管理这些索引会更加脆弱。它的签名必须看起来像这样:

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:

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.

幸运的是,Rust 为这个问题提供了一个解决方案:字符串切片。

Luckily, Rust has a solution to this problem: string slices.

字符串切片 (String Slices)

String Slices

“字符串切片 (string slice)”是对 String 中一部分连续元素的引用,它看起来像这样:

A string slice is a reference to a contiguous sequence of the elements of a String, and it looks like this:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs:here}}
}

hello 不是对整个 String 的引用,而是对 String 一部分的引用,由额外的 [0..5] 部分指定。我们使用方括号内的范围来创建切片,通过指定 [starting_index..ending_index],其中 starting_index 是切片中的第一个位置,而 ending_index 比切片中的最后一个位置大 1。在内部,切片数据结构存储切片的起始位置和长度,长度对应于 ending_index 减去 starting_index。因此,在 let world = &s[6..11]; 的情况下,world 将是一个包含指向 s 索引 6 处字节的指针以及长度值 5 的切片。

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 square 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.

图 4-7 以图表形式展示了这一点。

Figure 4-7 shows this in a diagram.

三张表格:一张代表 s 的栈数据的表格,它指向堆上字符串数据 "hello world" 索引 0 处的字节。第三张表代表切片 world 的栈数据,它有一个长度值 5,并指向堆数据表的第 6 个字节。

图 4-7:引用 String 一部分的字符串切片

利用 Rust 的 .. 范围语法,如果你想从索引 0 开始,可以省略两个点之前的数值。换句话说,这两者是等价的:

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:

#![allow(unused)]
fn main() {
let s = String::from("hello");

let slice = &s[0..2];
let slice = &s[..2];
}

同理,如果你的切片包含 String 的最后一个字节,你可以省略末尾的数字。这意味着这两者是等价的:

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:

#![allow(unused)]
fn main() {
let s = String::from("hello");

let len = s.len();

let slice = &s[3..len];
let slice = &s[3..];
}

你也可以省略这两个值来获取整个字符串的切片。所以,这两者是等价的:

You can also drop both values to take a slice of the entire string. So, these are equal:

#![allow(unused)]
fn main() {
let s = String::from("hello");

let len = s.len();

let slice = &s[0..len];
let slice = &s[..];
}

注意:字符串切片范围索引必须发生在有效的 UTF-8 字符边界处。如果你尝试在多字节字符的中间创建字符串切片,程序将因错误而退出。

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.

记住所有这些信息后,让我们重写 first_word 以返回切片。表示“字符串切片”的类型写作 &str

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs:here}}
}

我们以示例 4-7 中相同的方式获取单词结尾的索引,即寻找第一次出现的空格。当我们找到空格时,我们使用字符串的开头作为起始索引,空格的索引作为结束索引,返回一个字符串切片。

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.

现在当我们调用 first_word 时,我们会得到一个与底层数据相关联的单一值。该值由切片起始点的引用和切片中的元素数量组成。

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.

返回切片对于 second_word 函数也同样有效:

Returning a slice would also work for a second_word function:

fn second_word(s: &String) -> &str {

我们现在有了一个简单直观的 API,它更难出错,因为编译器将确保指向 String 的引用保持有效。还记得示例 4-8 程序中的那个 bug 吗?当时我们获取了第一个单词结尾的索引,但随后清空了字符串,导致索引失效。那段代码逻辑上是错误的,但没有显示任何即时错误。如果以后我们继续尝试将第一个单词索引与清空的字符串一起使用,问题就会显现出来。切片使这个 bug 变得不可能,并让我们更早地知道代码存在问题。使用切片版本的 first_word 会抛出一个编译时错误:

We now have a straightforward API that’s much harder to mess up because the compiler will ensure that 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 much sooner that we have a problem with our code. Using the slice version of first_word will throw a compile-time error:

{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs:here}}

这是编译器错误:

Here’s the compiler error:

{{#include ../listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt}}

回想一下借用规则,如果我们拥有某样东西的不可变引用,就不能同时再获取一个可变引用。因为 clear 需要截断 String,所以它需要获取一个可变引用。在调用 clear 之后的 println! 使用了 word 中的引用,因此不可变引用在该点必须仍然有效。Rust 不允许 clear 中的可变引用和 word 中的不可变引用同时存在,编译失败。Rust 不仅使我们的 API 更易于使用,还消除了一整类编译时错误!

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!

字符串字面量即切片 (String Literals as Slices)

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:

#![allow(unused)]
fn main() {
let s = "Hello, world!";
}

这里的 s 类型是 &str:它是一个指向二进制文件特定点的切片。这也是为什么字符串字面量是不可变的;&str 是一个不可变引用。

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.

字符串切片作为参数 (String Slices as Parameters)

String Slices as Parameters

既然知道可以获取字面量和 String 值的切片,这引导我们对 first_word 进行最后一次改进,即它的签名:

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:

fn first_word(s: &String) -> &str {

更有经验的 Rustacean 会转而编写示例 4-9 中显示的签名,因为它允许我们在 &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.

{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-09/src/main.rs:here}}

如果我们有一个字符串切片,可以直接传递。如果我们有一个 String,可以传递该 String 的切片或对该 String 的引用。这种灵活性利用了“解引用强制转换 (deref coercions)”,这是我们将在第 15 章“Using Deref Coercions in Functions and Methods”部分介绍的功能。

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 “Using Deref Coercions in Functions and Methods” section of Chapter 15.

定义函数以接收字符串切片而不是对 String 的引用,使我们的 API 更加通用且有用,同时不损失任何功能:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-09/src/main.rs:usage}}
}

其他切片 (Other Slices)

Other Slices

正如你可能想象的,字符串切片是特定于字符串的。但也有更通用的切片类型。考虑这个数组:

String slices, as you might imagine, are specific to strings. But there’s a more general slice type too. Consider this array:

#![allow(unused)]
fn main() {
let a = [1, 2, 3, 4, 5];
}

正如我们可能想要引用字符串的一部分一样,我们也可能想要引用数组的一部分。我们会这样做:

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:

#![allow(unused)]
fn main() {
let a = [1, 2, 3, 4, 5];

let slice = &a[1..3];

assert_eq!(slice, &[2, 3]);
}

这个切片的类型是 &[i32]。它的工作方式与字符串切片相同,通过存储第一个元素的引用和长度。你将为各种其他集合使用这种切片。我们将在第 8 章讨论向量 (vectors) 时详细讨论这些集合。

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.

总结 (Summary)

Summary

所有权、借用和切片的概念确保了 Rust 程序在编译时的内存安全。Rust 语言让你以与其他系统编程语言相同的方式控制内存使用。但是,让数据的所有者在超出作用域时自动清理该数据,意味着你不需要为了获得这种控制权而编写和调试额外的代码。

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 的许多其他部分的工作方式,因此在本书的其余部分中,我们将进一步讨论这些概念。让我们继续第 5 章,看看如何在 struct(结构体)中将各部分数据组合在一起。

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.

使用结构体组织相关数据 (Using Structs to Structure Related Data)


x-i18n: generated_at: “2026-03-01T13:42:29Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f868f22d0149966b0d0b7191ce20318bf12981275cb0e393dbcd52caaab8b173 source_path: ch05-00-structs.md workflow: 16

使用结构体组织相关数据 (Using Structs to Structure Related Data)

Using Structs to Structure Related Data

“结构体 (struct)”,全称“structure”,是一种自定义数据类型,它允许你将多个相关的值打包在一起并命名,从而组成一个有意义的组合。如果你熟悉面向对象的语言,结构体就像是对象的数据属性。在本章中,我们将对比元组与结构体,在你的既有知识基础上,演示何时结构体是更好的数据分组方式。

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.

我们将演示如何定义和实例化结构体。我们将讨论如何定义关联函数 (associated functions),特别是被称为“方法 (methods)”的一类关联函数,以指定与结构体类型相关联的行为。结构体和枚举 (enums)(在第 6 章讨论)是在程序领域中创建新类型的基础,从而充分利用 Rust 的编译时类型检查。

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.

定义并实例化结构体 (Defining and Instantiating Structs)


x-i18n: generated_at: “2026-03-01T13:44:32Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 344424e680093f9fd0291e895cd1002c5645a769d3b928de541d78148b93caa7 source_path: ch05-01-defining-structs.md workflow: 16

定义并实例化结构体 (Defining and Instantiating Structs)

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.

要定义结构体,我们输入关键字 struct 并为整个结构体命名。结构体的名称应该描述被组合在一起的数据片段的意义。然后,在花括号内,我们定义数据片段的名称和类型,我们称之为“字段 (fields)”。例如,示例 5-1 展示了一个存储用户账户信息的结构体。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs:here}}
}

要在定义结构体后使用它,我们通过为每个字段指定具体值来创建该结构体的“实例 (instance)”。我们通过声明结构体的名称来创建一个实例,然后添加包含 key: value 对的花括号,其中键是字段的名称,值是我们想要存储在这些字段中的数据。我们不必按照在结构体中声明字段的相同顺序来指定字段。换句话说,结构体定义就像是该类型的通用模板,而实例则用特定数据填充该模板以创建该类型的值。例如,我们可以像示例 5-2 所示那样声明一个特定的用户。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs:here}}
}

要从结构体中获取特定值,我们使用点号表示法。例如,要访问此用户的电子邮件地址,我们使用 user1.email。如果实例是可变的,我们可以通过使用点号表示法并赋值给特定字段来更改值。示例 5-3 展示了如何更改可变 User 实例中 email 字段的值。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs:here}}
}

注意,整个实例必须是可变的;Rust 不允许我们仅将某些字段标记为可变的。与任何表达式一样,我们可以构造结构体的新实例作为函数体的最后一个表达式,以隐式返回该新实例。

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.

示例 5-4 展示了一个 build_user 函数,该函数返回一个具有给定电子邮件和用户名的 User 实例。active 字段获取值 true,而 sign_in_count 获取值 1

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 true, and the sign_in_count gets a value of 1.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs:here}}
}

用与结构体字段相同的名称来命名函数参数是有意义的,但必须重复 emailusername 字段名称和变量有点乏味。如果结构体有更多字段,重复每个名称会变得更加烦人。幸运的是,有一个方便的简写!

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!

使用字段初始化简写语法 (Using the Field Init Shorthand)

Using the Field Init Shorthand

由于示例 5-4 中的参数名称和结构体字段名称完全相同,我们可以使用“字段初始化简写 (field init shorthand)”语法来重写 build_user,使其行为完全相同,但没有 usernameemail 的重复,如示例 5-5 所示。

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 that it behaves exactly the same but doesn’t have the repetition of username and email, as shown in Listing 5-5.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs:here}}
}

在这里,我们正在创建 User 结构体的一个新实例,该结构体有一个名为 email 的字段。我们想要将 email 字段的值设置为 build_user 函数的 email 参数中的值。因为 email 字段和 email 参数具有相同的名称,我们只需要写 email 而不是 email: email

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.

使用结构体更新语法从其他实例创建实例 (Creating Instances with Struct Update Syntax)

Creating Instances with Struct Update Syntax

从同一个类型的另一个实例创建一个包含大部分值但更改其中一些值的新结构体实例通常很有用。你可以使用“结构体更新语法 (struct update syntax)”来做到这一点。

It’s often useful to create a new instance of a struct that includes most of the values from another instance of the same type, but changes some of them. You can do this using struct update syntax.

首先,在示例 5-6 中,我们展示了如何以常规方式(不使用更新语法)在 user2 中创建一个新的 User 实例。我们为 email 设置了一个新值,但在其他方面使用了我们在示例 5-2 中创建的 user1 中的相同值。

First, in Listing 5-6 we show how to create a new User instance in user2 in the regular way, 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs:here}}
}

使用结构体更新语法,我们可以用更少的代码实现相同的效果,如示例 5-7 所示。语法 .. 指定未显式设置的剩余字段应具有与给定实例中字段相同的值。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs:here}}
}

示例 5-7 中的代码也在 user2 中创建了一个实例,该实例的 email 值不同,但 usernameactivesign_in_count 字段的值与 user1 相同。..user1 必须放在最后,以指定任何剩余字段都应从 user1 的相应字段中获取其值,但我们可以选择以任何顺序为任意数量的字段指定值,而不管结构体定义中字段的顺序如何。

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.

注意,结构体更新语法像赋值一样使用 =;这是因为它会移动数据,正如我们在 “变量与数据交互的方式:移动” 部分看到的那样。在这个例子中,我们在创建 user2 之后不能再使用 user1,因为 user1username 字段中的 String 被移动到了 user2 中。如果我们为 user2emailusername 都提供了新的 String 值,从而仅使用了 user1activesign_in_count 值,那么 user1 在创建 user2 后仍然有效。activesign_in_count 都是实现了 Copy 特征的类型,因此我们在 “只限栈的数据:拷贝” 部分讨论的行为将适用。在这个例子中,我们仍然可以使用 user1.email,因为它的值没有从 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 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. We can also still use user1.email in this example, because its value was not moved out of user1.

使用没有具名字段的元组结构体创建不同的类型 (Creating Different Types with Tuple Structs)

Creating Different Types with Tuple Structs

Rust 还支持看起来类似于元组的结构体,称为“元组结构体 (tuple structs)”。元组结构体具有结构体名称提供的附加含义,但没有与其字段关联的名称;相反,它们只有字段的类型。当你想要给整个元组起一个名字,并使该元组与其他元组具有不同的类型,且像在常规结构体中那样为每个字段命名会显得冗长或多余时,元组结构体非常有用。

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.

要定义元组结构体,以 struct 关键字和结构体名称开头,后跟元组中的类型。例如,在这里我们定义并使用了两个名为 ColorPoint 的元组结构体:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs}}
}

注意,blackorigin 值是不同的类型,因为它们是不同元组结构体的实例。你定义的每个结构体都是它自己的类型,即使结构体内的字段可能具有相同的类型。例如,一个接收 Color 类型参数的函数不能接收 Point 作为参数,即使这两种类型都由三个 i32 值组成。在其他方面,元组结构体实例与元组类似,因为你可以将它们解构为单独的部分,并且可以使用 . 后跟索引来访问单个值。与元组不同,元组结构体要求你在解构它们时命名结构体的类型。例如,我们会写 let Point(x, y, z) = origin; 来将 origin 点中的值解构为名为 xyz 的变量。

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. Unlike tuples, tuple structs require you to name the type of the struct when you destructure them. For example, we would write let Point(x, y, z) = origin; to destructure the values in the origin point into variables named x, y, and z.

定义没有任何字段的类单元结构体 (Defining Unit-Like Structs)

Defining Unit-Like Structs

你也可以定义没有任何字段的结构体!这些被称为“类单元结构体 (unit-like structs)”,因为它们的行为类似于 (),即我们在 “元组类型” 部分提到的单元类型。当你需要在某种类型上实现一个特征 (trait) 但没有任何想要存储在类型本身中的数据时,类单元结构体非常有用。我们将在第 10 章讨论特征。这是一个声明并实例化名为 AlwaysEqual 的单元结构体的示例:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-04-unit-like-structs/src/main.rs}}
}

要定义 AlwaysEqual,我们使用 struct 关键字、我们想要的名称,然后是一个分号。不需要花括号或圆括号!然后,我们可以以类似的方式在 subject 变量中获取 AlwaysEqual 的实例:使用我们定义的名称,不带任何花括号或圆括号。想象一下,稍后我们将为此类型实现行为,使得 AlwaysEqual 的每个实例始终等于任何其他类型的每个实例,也许是为了获得已知的测试结果。实现该行为不需要任何数据!你将在第 10 章中看到如何定义特征并在任何类型(包括类单元结构体)上实现它们。

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.

结构体数据的所有权 (Ownership of Struct Data)

Ownership of Struct Data

在示例 5-1 的 User 结构体定义中,我们使用了拥有的 String 类型而不是 &str 字符串切片类型。这是一个深思熟虑的选择,因为我们希望此结构体的每个实例都拥有其所有数据,并希望该数据在整个结构体有效期间保持有效。

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.

结构体也可以存储对归其他东西所有的数据的引用,但这样做需要使用“生命周期 (lifetimes)”,这是我们将在第 10 章讨论的一个 Rust 功能。生命周期确保结构体引用的数据与结构体本身一样有效。假设你尝试在结构体中存储引用而不指定生命周期,如下面 src/main.rs 中的内容;这将无法工作:

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 in src/main.rs; this won’t work:

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

在第 10 章中,我们将讨论如何修复 these 错误,以便你可以在结构体中存储引用,但现在,我们将使用像 String 这样的拥有类型而不是像 &str 这样的引用来修复此类错误。

In Chapter 10, we’ll discuss how to fix these errors so that 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.

结构体示例程序 (An Example Program Using Structs)


x-i18n: generated_at: “2026-03-01T13:45:01Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: bebb0dfbd5dd94bfcd19f9d2f6216fcac10a9b168eef6a07a1d753ae85512557 source_path: ch05-02-example-structs.md workflow: 16

一个使用结构体的示例程序 (An Example Program Using Structs)

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.

让我们用 Cargo 创建一个名为 rectangles 的新二进制项目,它将接收以像素为单位的长方形宽度和高度,并计算长方形的面积。示例 5-8 展示了一个简短的程序,在项目的 src/main.rs 中以一种方式实现了这一点。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs:all}}
}

现在,使用 cargo run 运行此程序:

Now, run this program using cargo run:

{{#include ../listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt}}

这段代码通过调用带有每个维度的 area 函数成功算出了长方形的面积,但我们可以做更多工作来使代码清晰易读。

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:

{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs:here}}

area 函数本应计算“一个”长方形的面积,但我们编写的函数有两个参数,而且在程序的任何地方都没有明确表明这两个参数是相关的。将宽度和高度组合在一起会更易读且更易于管理。我们已经在第 3 章的 “元组类型” 部分讨论了实现这一点的一种方法:使用元组。

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.

使用元组重构 (Refactoring with Tuples)

Refactoring with Tuples

示例 5-9 展示了程序的另一个使用元组的版本。

Listing 5-9 shows another version of our program that uses tuples.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs}}
}

从某种角度来说,这个程序更好。元组让我们增加了一点结构,而且我们现在只传递一个参数。但从另一种角度来说,这个版本不太清晰:元组没有命名它们的元素,所以我们必须通过索引访问元组的部分,这使得我们的计算不够直观。

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.

混淆宽度和高度对于面积计算来说并不重要,但如果我们想在屏幕上画出这个长方形,那就重要了!我们将不得不记住 width 是元组索引 0,而 height 是元组索引 1。如果别人使用我们的代码,这对于他们来说会更难弄清楚并记住。因为我们没有在代码中传达数据的含义,现在更容易引入错误。

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.

使用结构体重构:赋予更多意义 (Refactoring with Structs)

Refactoring with Structs

我们使用结构体通过标记数据来赋予意义。我们可以将正在使用的元组转换为结构体,既为整体命名,也为部分命名,如示例 5-10 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs}}
}

在这里,我们定义了一个名为 Rectangle 的结构体。在花括号内,我们将字段定义为 widthheight,它们的类型都是 u32。然后,在 main 中,我们创建了 Rectangle 的一个特定实例,其宽度为 30,高度为 50

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.

我们的 area 函数现在定义了一个参数,我们将其命名为 rectangle ,其类型是结构体 Rectangle 实例的一个不可变借用。正如第 4 章所述,我们希望借用结构体而不是获取它的所有权。这样,main 就可以保留所有权并继续使用 rect1,这也是我们在函数签名和调用函数的地方使用 & 的原因。

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 实例的 widthheight 字段(注意访问借用的结构体实例的字段不会移动字段值,这就是为什么你经常看到结构体的借用)。我们的 area 函数签名现在准确表达了我们的意思:使用 Rectanglewidthheight 字段计算它的面积。这传达了宽度和高度是相互关联的,并且为这些值赋予了描述性的名称,而不是使用元组索引值 01。这在清晰度上是一种进步。

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.

通过派生特征添加功能 (Adding Functionality with Derived Traits)

Adding Functionality with Derived Traits

能够在调试程序时打印 Rectangle 的实例并查看其所有字段的值将非常有用。示例 5-11 尝试使用我们在前几章中使用过的 println!。然而,这行不通。

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.

{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs}}

当我们编译这段代码时,会得到一个包含核心消息的错误:

When we compile this code, we get an error with this core message:

{{#include ../listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt:3}}

println! 宏可以执行多种格式化,默认情况下,花括号告诉 println! 使用称为 Display 的格式化:旨在直接供最终用户使用的输出。到目前为止我们见过的原始类型默认都实现了 Display,因为你只想向用户显示 1 或任何其他原始类型的一种方式。但对于结构体,println! 应该如何格式化输出就不那么明确了,因为有更多的显示可能性:你要逗号吗?你要打印花括号吗?所有字段都要显示吗?由于这种歧义,Rust 不会尝试猜测我们想要什么,而且结构体没有提供可以与 println!{} 占位符一起使用的 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.

如果我们继续阅读错误,会发现这条有用的提示:

If we continue reading the errors, we’ll find this helpful note:

{{#include ../listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt:9:10}}

让我们试试看!println! 宏调用现在看起来像 println!("rect1 is {rect1:?}");。在花括号内放入限定符 :? 告诉 println! 我们想要使用一种名为 Debug 的输出格式。Debug 特征使我们能够以一种对开发者有用的方式打印结构体,以便我们在调试代码时查看其值。

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 that we can see its value while we’re debugging our code.

更改后编译代码。糟糕!还是报错:

Compile the code with this change. Drat! We still get an error:

{{#include ../listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt:3}}

但编译器再次给了我们一条有用的提示:

But again, the compiler gives us a helpful note:

{{#include ../listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt:9:10}}

Rust “确实” 包含了打印调试信息的功能,但我们必须显式选择加入才能为我们的结构体提供该功能。为此,我们在结构体定义之前添加外部属性 #[derive(Debug)],如示例 5-12 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs}}
}

现在当我们运行程序时,不会收到任何错误,并且会看到以下输出:

Now when we run the program, we won’t get any errors, and we’ll see the following output:

{{#include ../listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt}}

太棒了!虽然不是最漂亮的输出,但它显示了该实例所有字段的值,这绝对有助于调试。当我们有更大的结构体时,让输出更容易阅读一些会很有用;在这些情况下,我们可以在 println! 字符串中使用 {:#?} 代替 {:?}。在这个例子中,使用 {:#?} 风格将输出以下内容:

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:

{{#include ../listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt}}

使用 Debug 格式打印值的另一种方法是使用 dbg!,它接收表达式的所有权(与接收引用的 println! 不同),打印代码中 dbg! 宏调用发生的文件和行号以及该表达式的结果值,并返回该值的所有权。

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.

注意:调用 dbg! 宏会打印到标准错误控制台流 (stderr),而 println! 则打印到标准输出控制台流 (stdout)。我们将在第 12 章的“将错误重定向到标准错误”部分中更多地讨论 stderrstdout

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 “Redirecting Errors to Standard Error” section in Chapter 12.

这里有一个例子,我们对分配给 width 字段的值以及 rect1 中整个结构体的值感兴趣:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-05-dbg-macro/src/main.rs}}
}

我们可以将 dbg! 放在表达式 30 * scale 周围,由于 dbg! 会返回表达式值的所有权,width 字段将获得与我们不使用 dbg! 调用时相同的值。我们不希望 dbg! 获取 rect1 的所有权,所以我们在下一次调用中使用 rect1 的引用。以下是该示例的输出结果:

{{#include ../listings/ch05-using-structs-to-structure-related-data/no-listing-05-dbg-macro/output.txt}}

我们可以看到第一部分输出源自 src/main.rs 第 10 行,我们正在调试表达式 30 * scale ,其结果值为 60(为整数实现的 Debug 格式是仅打印其值)。在 src/main.rs 第 14 行调用的 dbg! 输出 &rect1 的值,即 Rectangle 结构体。此输出使用了 Rectangle 类型漂亮的 Debug 格式化。当你试图弄清楚代码在做什么时,dbg! 宏真的非常有帮助!

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!

除了 Debug 特征之外,Rust 还为我们提供了许多可以与 derive 属性配合使用的特征,从而为我们的自定义类型添加有用的行为。这些特征及其行为列在 附录 C 中。我们将在第 10 章介绍如何使用自定义行为实现这些特征,以及如何创建你自己的特征。除了 derive 之外还有许多其他属性;更多信息请参阅 Rust 参考手册中的 “属性 (Attributes)” 部分

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.

我们的 area 函数非常具体:它只计算长方形的面积。将此行为与我们的 Rectangle 结构体更紧密地联系起来会很有帮助,因为它不适用于任何其他类型。让我们来看看如何通过将 area 函数转变为定义在 Rectangle 类型上的 area “方法 (method)” 来继续重构代码。

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.

方法 (Methods)


x-i18n: generated_at: “2026-03-01T13:45:55Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 7c99bde44d1cb2735239a441e1898be4cfd4b21ef6862978640491903624d06a source_path: ch05-03-method-syntax.md workflow: 16

方法 (Methods)

Methods

方法与函数类似:我们使用 fn 关键字和名称来声明它们,它们可以有参数和返回值,并且包含一段在从其他地方调用该方法时运行的代码。与函数不同的是,方法是在结构体的上下文中定义的(或者是枚举或特征对象,我们分别在第 6 章第 18 章中介绍),并且它们的第一个参数总是 self,它代表调用该方法的结构体实例。

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 18, respectively), and their first parameter is always self, which represents the instance of the struct the method is being called on.

方法语法 (Method Syntax)

Method Syntax

让我们改变以 Rectangle 实例作为参数的 area 函数,改为在 Rectangle 结构体上定义一个 area 方法,如示例 5-13 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs}}
}

为了在 Rectangle 的上下文中定义函数,我们为 Rectangle 开启了一个 impl(实现)块。这个 impl 块中的所有内容都将与 Rectangle 类型相关联。然后,我们将 area 函数移动到 impl 的花括号内,并将签名中以及函数体各处的第一个(在此例中也是唯一的)参数更改为 self。在 main 中,原先我们调用 area 函数并将 rect1 作为参数传递的地方,现在可以使用“方法语法 (method syntax)”在我们的 Rectangle 实例上调用 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.

area 的签名中,我们使用 &self 而不是 rectangle: &Rectangle&self 实际上是 self: &Self 的缩写。在一个 impl 块中,类型 Selfimpl 块所对应的类型的别名。方法的第一个参数必须有一个名为 self 且类型为 Self 的参数,因此 Rust 允许你在第一个参数位置仅用名称 self 来简写。请注意,我们仍然需要在 self 简写前面使用 & 来表示该方法借用 Self 实例,就像我们在 rectangle: &Rectangle 中所做的那样。方法可以获取 self 的所有权、不可变地借用 self(如我们这里所做的),或者可变地借用 self,就像处理任何其他参数一样。

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.

我们在这里选择 &self 的原因与在函数版本中使用 &Rectangle 的原因相同:我们不想获取所有权,只想读取结构体中的数据,而不是写入。如果我们想在方法执行过程中更改调用该方法的实例,我们会使用 &mut 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 的类型之外,使用方法而不是函数的主要原因是为了组织代码。我们将对一个类型的实例可以执行的所有操作都放在一个 impl 块中,而不是让未来的代码使用者在我们提供的库的各个地方寻找 Rectangle 的功能。

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.

注意,我们可以选择给方法起一个与结构体字段相同的名称。例如,我们可以在 Rectangle 上定义一个也名为 width 的方法:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-06-method-field-interaction/src/main.rs:here}}
}

在这里,我们选择让 width 方法在实例的 width 字段值大于 0 时返回 true,如果值为 0 则返回 false:我们可以在同名方法中使用字段来达到任何目的。在 main 中,当我们在 rect1.width 后面跟着圆括号时,Rust 知道我们的意思是 width 方法。当我们不使用圆括号时,Rust 知道我们的意思是 width 字段。

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.

通常(但并非总是),当我们给方法起一个与字段相同的名称时,我们希望它只返回字段中的值而不做其他操作。像这样的方法被称为 “getter 方法”,Rust 不像其他一些语言那样为结构体字段自动实现它们。getter 方法很有用,因为你可以将字段设为私有但将方法设为公有,从而作为类型公有 API 的一部分实现对该字段的只读访问。我们将在第 7 章中讨论什么是公有和私有,以及如何将字段或方法指定为公有或私有。

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.

-> 运算符在哪? (Where’s the -> Operator?)

Where’s the -> Operator?

在 C 和 C++ 中,调用方法使用两个不同的运算符:如果你直接在对象上调用方法,使用 .;如果你在对象的指针上调用方法,并且需要先对指针进行解引用,则使用 ->。换句话说,如果 object 是一个指针,object->something() 类似于 (*object).something()

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().

Rust 没有与 -> 运算符等效的运算符;相反,Rust 有一个名为“自动引用和解引用 (automatic referencing and dereferencing)”的功能。调用方法是 Rust 中少数具有此行为的地方之一。

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 with this behavior.

它是这样工作的:当你使用 object.something() 调用方法时,Rust 会自动添加 &&mut*,以便 object 符合方法的签名。换句话说,以下代码是相同的:

Here’s how it works: When you call a method with object.something(), Rust automatically adds in &, &mut, or * so that object matches the signature of the method. In other words, the following are the same:

#![allow(unused)]
fn main() {
#[derive(Debug,Copy,Clone)]
struct Point {
    x: f64,
    y: f64,
}

impl Point {
   fn distance(&self, other: &Point) -> f64 {
       let x_squared = f64::powi(other.x - self.x, 2);
       let y_squared = f64::powi(other.y - self.y, 2);

       f64::sqrt(x_squared + y_squared)
   }
}
let p1 = Point { x: 0.0, y: 0.0 };
let p2 = Point { x: 5.0, y: 6.5 };
p1.distance(&p2);
(&p1).distance(&p2);
}

第一种写法看起来整洁得多。这种自动引用的行为之所以有效,是因为方法有一个明确的接收者——self 的类型。给定接收者和方法名称,Rust 可以确定地判断出该方法是读取(&self)、修改(&mut self)还是消耗(self)。Rust 让方法接收者的借用变成隐式的,这在很大程度上让所有权在实践中变得符合人体工程学。

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.

带有更多参数的方法 (Methods with More Parameters)

Methods with More Parameters

让我们通过在 Rectangle 结构体上实现第二个方法来练习使用方法。这一次,我们希望 Rectangle 的一个实例接收另一个 Rectangle 实例,如果第二个 Rectangle 可以完全放入 self(第一个 Rectangle)内部,则返回 true;否则返回 false。也就是说,一旦我们定义了 can_hold 方法,我们希望能够编写示例 5-14 所示的程序。

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.

{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs}}

预期的输出如下所示,因为 rect2 的两个维度都小于 rect1 的维度,但 rect3rect1 宽:

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:

Can rect1 hold rect2? true
Can rect1 hold rect3? false

我们知道我们要定义一个方法,所以它将位于 impl Rectangle 块内。方法名将是 can_hold,它将接收另一个 Rectangle 的不可变借用作为参数。我们可以通过观察调用该方法的代码来确定参数的类型:rect1.can_hold(&rect2) 传入了 &rect2,它是对 Rectangle 实例 rect2 的不可变借用。这是合理的,因为我们只需要读取 rect2(而不是写入,写入意味着我们需要可变借用),并且我们希望 main 保留 rect2 的所有权,以便在调用 can_hold 方法后可以再次使用它。can_hold 的返回值将是一个布尔值,其实现将分别检查 self 的宽度和高度是否大于另一个 Rectangle 的宽度和高度。让我们将新的 can_hold 方法添加到示例 5-13 的 impl 块中,如示例 5-15 所示。

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 that 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs:here}}
}

当我们使用示例 5-14 中的 main 函数运行这段代码时,我们将得到想要的输出。方法可以接收多个参数,我们将这些参数在 self 参数之后添加到签名中,这些参数的作用与函数中的参数完全一样。

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.

关联函数 (Associated Functions)

Associated Functions

impl 块中定义的所有函数都被称为“关联函数 (associated functions)”,因为它们与 impl 后面命名的类型相关联。我们可以定义不以 self 作为第一个参数的关联函数(因此它们不是方法),因为它们不需要该类型的实例来配合。我们已经使用过一个这样的函数:定义在 String 类型上的 String::from 函数。

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.

非方法的关联函数通常用于返回结构体新实例的构造函数。这些函数通常被命名为 new,但 new 并不是一个特殊的名称,也不是语言内置的。例如,我们可以选择提供一个名为 square 的关联函数,它接收一个维度参数,并将其同时用作宽度和高度,从而更容易创建一个正方形的 Rectangle,而不需要指定两次相同的值:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs:here}}
}

在返回值类型和函数体中的 Self 关键字是 impl 关键字之后出现的类型的别名,在此例中是 Rectangle

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.

要调用这个关联函数,我们使用带有结构体名称的 :: 语法;let sq = Rectangle::square(3); 就是一个例子。该函数由结构体命名空间化::: 语法既用于关联函数,也用于由模块创建的命名空间。我们将在第 7 章讨论模块。

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.

多个 impl 块 (Multiple impl Blocks)

Multiple impl Blocks

每个结构体允许有多个 impl 块。例如,示例 5-15 与示例 5-16 所示的代码是等价的,后者将每个方法放在各自的 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs:here}}
}

在这里没有理由将这些方法分成多个 impl 块,但这是有效的语法。我们将在第 10 章讨论泛型和特征时看到多个 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.

总结 (Summary)

Summary

结构体允许你创建对你的领域有意义的自定义类型。通过使用结构体,你可以保持相关数据片段的连接,并为每一片段命名,使你的代码清晰。在 impl 块中,你可以定义与你的类型相关联的函数,而方法是一种特殊的关联函数,允许你指定结构体实例所具有的行为。

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.

但结构体并不是你创建自定义类型的唯一方式:让我们转到 Rust 的枚举功能,为你的工具箱添加另一个工具。

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.

枚举与模式匹配 (Enums and Pattern Matching)


x-i18n: generated_at: “2026-03-01T13:46:29Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: efa473933293ae1d6cdca81c2efd61e9d2a602d43f4b8978b7bd145ec8e6c2c1 source_path: ch06-00-enums.md workflow: 16

枚举与模式匹配 (Enums and Pattern Matching)

Enums and Pattern Matching

在本章中,我们将研究枚举 (enumerations),也称为“enums”。枚举允许你通过列举其可能的变体来定义一种类型。首先,我们将定义并使用一个枚举,以展示枚举如何将含义与数据一起编码。接下来,我们将探索一个特别有用的枚举,名为 Option,它表示一个值既可以是某个东西,也可以是无。然后,我们将研究 match 表达式中的模式匹配如何轻松地为枚举的不同值运行不同的代码。最后,我们将介绍 if let 结构是如何在代码中处理枚举的另一种方便且简洁的惯用法。

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.

定义枚举 (Defining an Enum)


x-i18n: generated_at: “2026-03-01T13:48:01Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: d0958df229fd25f89f140896449ce69bbd6f40db8398a99e4a53635dba0438f2 source_path: ch06-01-defining-an-enum.md workflow: 16

定义枚举 (Defining an Enum)

Defining an Enum

结构体让你能够将相关的字段和数据组合在一起,比如 Rectangle 及其 widthheight;而枚举则让你能够表达一个值是可能值集合中的一个。例如,我们可能想说 Rectangle 是可能形状集合中的一种,该集合还包括 CircleTriangle。为此,Rust 允许我们将这些可能性编码为一个枚举。

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.

让我们看一个我们可能想在代码中表达的情况,并了解为什么在这种情况下枚举比结构体更有用且更合适。假设我们需要处理 IP 地址。目前,IP 地址主要有两种标准:版本 4 和版本 6。因为这些是我们的程序会遇到的 IP 地址的仅有可能性,所以我们可以“列举 (enumerate)”所有可能的变体,这就是枚举名称的由来。

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 地址要么是版本 4 地址,要么是版本 6 地址,但不能同时是两者。IP 地址的这种属性使得枚举数据结构非常合适,因为枚举值只能是其变体之一。版本 4 和版本 6 地址从根本上讲仍然是 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.

我们可以通过定义一个 IpAddrKind 枚举并列出 IP 地址可能的种类 V4V6 来在代码中表达这个概念。这些是枚举的变体:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs:def}}
}

IpAddrKind 现在是一个自定义数据类型,我们可以在代码的其他地方使用它。

IpAddrKind is now a custom data type that we can use elsewhere in our code.

枚举值 (Enum Values)

Enum Values

我们可以像这样创建 IpAddrKind 两个变体各自的实例:

We can create instances of each of the two variants of IpAddrKind like this:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs:instance}}
}

请注意,枚举的变体位于其标识符的命名空间下,我们使用双冒号来分隔两者。这很有用,因为现在 IpAddrKind::V4IpAddrKind::V6 这两个值都属于同一类型:IpAddrKind。例如,我们可以定义一个接收任何 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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs:fn}}
}

我们可以使用任一变体来调用此函数:

And we can call this function with either variant:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs:fn_call}}
}

使用枚举还有更多优势。进一步思考我们的 IP 地址类型,目前我们没有办法存储实际的 IP 地址“数据”;我们只知道它是哪种“类型”。鉴于你刚刚在第 5 章学习了结构体,你可能会倾向于使用结构体来解决这个问题,如示例 6-1 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs:here}}
}

在这里,我们定义了一个结构体 IpAddr,它有两个字段:一个是 IpAddrKind 类型的 kind 字段(我们之前定义的枚举),另一个是 String 类型的 address 字段。我们有两个此结构体的实例。第一个是 home,它的 kind 值为 IpAddrKind::V4,关联的地址数据为 127.0.0.1。第二个实例是 loopback。它的 kind 值为 IpAddrKind 的另一个变体 V6,并且有关联地址 ::1。我们使用结构体将 kindaddress 值捆绑在一起,因此现在变体与值关联在一起。

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.

然而,仅使用枚举来表示相同的概念更为简洁:与其在结构体内部放一个枚举,我们可以直接将数据放入每个枚举变体中。IpAddr 枚举的这个新定义表明 V4V6 变体都将具有关联的 String 值:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs:here}}
}

我们直接将数据附加到枚举的每个变体上,因此不需要额外的结构体。在这里,也更容易看到枚举工作方式的另一个细节:我们定义的每个枚举变体的名称也变成了一个构造枚举实例的函数。也就是说,IpAddr::V4() 是一个函数调用,它接收一个 String 参数并返回 IpAddr 类型的一个实例。由于定义了枚举,我们自动获得了这个构造函数的定义。

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.

使用枚举而不是结构体还有另一个优点:每个变体可以具有不同类型和数量的关联数据。版本 4 IP 地址始终会有四个数字组件,其值在 0 到 255 之间。如果我们想将 V4 地址存储为四个 u8 值,但仍将 V6 地址表示为一个 String 值,使用结构体将无法实现。枚举可以轻松处理这种情况:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs:here}}
}

我们展示了定义数据结构来存储版本 4 和版本 6 IP 地址的几种不同方式。然而,事实证明,想要存储 IP 地址并对其类型进行编码是非常普遍的需求,以至于标准库中有一个我们可以使用的定义! 让我们看看标准库是如何定义 IpAddr 的。它具有与我们定义和使用的完全相同的枚举和变体,但它以两个不同结构体的形式将地址数据嵌入到变体内部,这两个结构体针对每个变体的定义都不同:

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:

#![allow(unused)]
fn main() {
struct Ipv4Addr {
    // --snip--
}

struct Ipv6Addr {
    // --snip--
}

enum IpAddr {
    V4(Ipv4Addr),
    V6(Ipv6Addr),
}
}

这段代码说明你可以在枚举变体中放入任何类型的数据:例如字符串、数值类型或结构体。你甚至可以包含另一个枚举!此外,标准库类型通常并不比你可能想出来的复杂多少。

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.

请注意,即使标准库包含 IpAddr 的定义,我们仍然可以创建并使用我们自己的定义而不会发生冲突,因为我们没有将标准库的定义引入到我们的作用域中。我们将在第 7 章中详细讨论将类型引入作用域。

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.

让我们在示例 6-2 中看另一个枚举示例:这个枚举的变体中嵌入了各种各样的类型。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs:here}}
}

此枚举具有四种不同类型的变体:

This enum has four variants with different types:

  • Quit:完全没有关联数据
  • Move:具有具名字段,就像结构体一样
  • Write:包含一个 String
  • ChangeColor:包含三个 i32

定义具有示例 6-2 中此类变体的枚举类似于定义不同种类的结构体定义,不同之处在于枚举不使用 struct 关键字,并且所有变体都归组在 Message 类型下。以下结构体可以持有与上述枚举变体持有的相同数据:

  • Quit: Has no data associated with it at all
  • Move: Has named fields, like a struct does
  • Write: Includes a single String
  • ChangeColor: Includes three i32 values

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs:here}}
}

但是,如果我们使用不同的结构体(每个结构体都有自己的类型),我们就无法像使用示例 6-2 中定义的 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.

枚举和结构体之间还有一个相似之处:正如我们可以使用 impl 在结构体上定义方法一样,我们也可以在枚举上定义方法。这是一个名为 call 的方法,我们可以在 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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs:here}}
}

方法体将使用 self 来获取我们调用该方法的值。在这个例子中,我们创建了一个变量 m,它的值为 Message::Write(String::from("hello")),当 m.call() 运行时,这就是 call 方法体中的 self

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.

让我们看看标准库中另一个非常常见且有用的枚举:Option

Let’s look at another enum in the standard library that is very common and useful: Option.

Option 枚举 (The Option Enum)

The Option Enum

本节将深入探讨 Option 的案例研究,它是标准库定义的另一个枚举。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.

例如,如果你请求一个非空列表中的第一项,你会得到一个值。如果你请求一个空列表中的第一项,你将一无所获。用类型系统的术语来表达这个概念,意味着编译器可以检查你是否处理了所有应该处理的情况;这种功能可以防止在其他编程语言中极其常见的 bug。

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.

编程语言设计通常被认为是根据你包含了哪些功能来考虑的,但你排除的功能也很重要。Rust 没有许多其他语言所具有的 null 功能。“Null” 是一个表示那里没有值的值。在具有 null 的语言中,变量始终处于两种状态之一:null 或非 null。

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.

在 2009 年的演讲 “Null References: The Billion Dollar Mistake” 中,null 的发明者 Tony Hoare 曾这样说道:

In his 2009 presentation “Null References: The Billion Dollar Mistake,” Tony Hoare, the inventor of null, had this to say:

我称之为我价值十亿美元的错误。当时,我正在为一种面向对象的语言设计第一个全面的引用类型系统。我的目标是确保所有引用的使用都应该是绝对安全的,由编译器自动执行检查。但我无法抗拒放入空引用的诱惑,仅仅是因为它实现起来非常容易。这导致了无数的错误、漏洞和系统崩溃,在过去的四十年里,这些错误、漏洞和系统崩溃可能造成了十亿美元的痛苦和损失。

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.

null 值的问题在于,如果你尝试将 null 值作为非 null 值使用,你会得到某种类型的错误。因为这种 null 或非 null 的属性无处不在,所以极其容易犯这类错误。

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.

问题并不在于概念本身,而在于具体的实现方式。因此,Rust 没有 null,但它确实有一个可以编码值存在或不存在概念的枚举。这个枚举就是 Option<T>,它由标准库定义如下:

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:

#![allow(unused)]
fn main() {
enum Option<T> {
    None,
    Some(T),
}
}

Option<T> 枚举非常有用,以至于它甚至被包含在 prelude(预导入)中;你不需要显式地将其引入作用域。它的变体也包含在 prelude 中:你可以直接使用 SomeNone,而不需要 Option:: 前缀。Option<T> 枚举仍然只是一个普通的枚举,而 Some(T)None 仍然是 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>.

<T> 语法是 Rust 的一个我们尚未讨论过的功能。它是一个泛型类型参数,我们将在第 10 章中详细介绍泛型。目前,你只需要知道 <T> 意味着 Option 枚举的 Some 变体可以持有任何类型的一段数据,并且每个用于替代 T 的具体类型都会使整个 Option<T> 类型成为一种不同的类型。以下是一些使用 Option 值来持有数字类型和字符类型的示例:

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 char types:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs:here}}
}

some_number 的类型是 Option<i32>some_char 的类型是 Option<char>,这是一种不同的类型。Rust 可以推断出这些类型,因为我们已经在 Some 变体内部指定了一个值。对于 absent_number,Rust 要求我们标注整体的 Option 类型:编译器无法通过仅查看 None 值来推断出相应的 Some 变体将持有的类型。在这里,我们告诉 Rust 我们希望 absent_number 的类型是 Option<i32>

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 值时,我们知道值是存在的,并且该值被持有在 Some 内部。当我们有一个 None 值时,从某种意义上说,它与 null 的含义相同:我们没有一个有效的值。那么,为什么拥有 Option<T> 比拥有 null 更好呢?

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?

简而言之,因为 Option<T>T(其中 T 可以是任何类型)是不同的类型,编译器不会让我们像使用肯定有效的值那样去使用 Option<T> 值。例如,这段代码将无法编译,因为它试图将一个 i8 加到一个 Option<i8> 上:

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>:

{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs:here}}

如果我们运行这段代码,我们会得到一条如下所示的错误消息:

If we run this code, we get an error message like this one:

{{#include ../listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt}}

真够严厉的!实际上,这条错误消息意味着 Rust 不理解如何将 i8Option<i8> 相加,因为它们是不同的类型。当我们拥有 Rust 中类似 i8 类型的值时,编译器将确保我们始终拥有一个有效值。我们可以自信地继续运行,而不必在使用该值之前检查它是否为 null。只有当我们拥有 Option<i8>(或我们正在处理的任何类型的值)时,我们才需要担心可能没有值的情况,编译器将确保我们在使用该值之前处理了这种情况。

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.

换句话说,你必须先将 Option<T> 转换为 T,然后才能对其执行 T 操作。一般来说,这有助于捕捉 null 最常见的问题之一:假设某样东西不是 null,而它实际上是 null。

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.

消除错误假设非 null 值的风险可以帮助你对代码更有信心。为了拥有一个可能为 null 的值,你必须通过将该值的类型设为 Option<T> 来显式选择加入。然后,当你使用该值时,你必须显式处理值为 null 的情况。只要一个值的类型不是 Option<T>,你就可以安全地假设该值不是 null。这是 Rust 的一项深思熟虑的设计决定,旨在限制 null 的泛滥并提高 Rust 代码的安全性。

Eliminating the risk of incorrectly assuming a not-null value helps you 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.

那么,当你拥有 Option<T> 类型的值时,如何从 Some 变体中取出 T 值以便使用该值呢?Option<T> 枚举拥有大量在各种情况下都有用的方法;你可以在其文档中查看它们。在 Rust 的学习过程中,熟悉 Option<T> 的方法将极其有用。

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) 值时运行,并且这些代码被允许使用内部的 T。你希望另一些代码仅在拥有 None 值时运行,且这些代码没有可用的 T 值。match 表达式是一种控制流结构,当与枚举一起使用时,它正可以做到这一点:它将根据拥有的枚举变体运行不同的代码,并且这些代码可以使用匹配值内部的数据。

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.

match 控制流结构 (The match Control Flow Construct)


x-i18n: generated_at: “2026-03-01T13:49:04Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: db9a32dfa0c24d89d74362e0bbdb9e5793a6e61fe3aa487b67897b1cb3f90899 source_path: ch06-02-match.md workflow: 16

match 控制流结构 (match Control Flow Construct)

match Control Flow Construct

Rust 拥有一个极其强大的控制流结构,称为 match,它允许你将一个值与一系列模式进行比较,然后根据匹配的模式执行代码。模式可以由字面量值、变量名、通配符和许多其他内容组成;第 19 章涵盖了所有不同种类的模式及其作用。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 19 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.

可以把 match 表达式想象成一台硬币分拣机:硬币沿着一条轨道滑行,轨道上分布着大小不一的孔洞,每枚硬币都会从它遇到的第一个能钻进去的孔洞掉下去。以同样的方式,值会经过 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 的例子!我们可以编写一个函数,它接收一枚未知的美国硬币,并以类似于分拣机的方式确定它是哪种硬币,并返回其以美分为单位的价值,如示例 6-3 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs:here}}
}

让我们分解 value_in_cents 函数中的 match。首先,我们列出 match 关键字,后跟一个表达式,在这个例子中是值 coin。这看起来与 if 使用的条件表达式非常相似,但有一个很大的区别:对于 if,条件需要求值为布尔值,但在这里它可以是任何类型。在这个例子中,coin 的类型是我们第一行定义的 Coin 枚举。

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.

接下来是 match 分支 (arms)。一个分支有两个部分:一个模式 (pattern) 和一些代码。这里的第一个分支有一个模式,即值 Coin::Penny,然后是 => 运算符,它分隔了模式和要运行的代码。在这个例子中,代码只是值 1。每个分支都用逗号与下一个分支隔开。

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 表达式执行时,它会按顺序将结果值与每个分支的模式进行比较。如果模式与值匹配,则执行与该模式关联的代码。如果该模式与值不匹配,则继续执行下一个分支,就像在硬币分拣机中一样。我们可以根据需要拥有任意数量的分支:在示例 6-3 中,我们的 match 有四个分支。

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 表达式返回的值。

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 分支代码很短(如示例 6-3 中每个分支仅返回一个值),我们通常不使用花括号。如果你想在 match 分支中运行多行代码,必须使用花括号,此时分支后的逗号是可选的。例如,以下代码在每次使用 Coin::Penny 调用方法时都会打印 “Lucky penny!”,但它仍然返回代码块的最后一个值 1

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 it still returns the last value of the block, 1:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs:here}}
}

绑定到值的模式 (Patterns That Bind to Values)

Patterns That Bind to Values

match 分支的另一个有用功能是它们可以绑定到匹配模式的值的部分。这就是我们如何从枚举变体中提取值的方法。

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.

举个例子,让我们更改其中一个枚举变体以在内部持有数据。从 1999 年到 2008 年,美国铸造了 25 美分硬币(quarters),其一面为 50 个州分别设计了不同的图案。其他硬币没有州设计,所以只有 25 美分硬币有这个额外的值。我们可以通过更改 Quarter 变体以包含内部存储的 UsState 值来将此信息添加到我们的 enum 中,我们在示例 6-4 中已经这样做了。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs:here}}
}

让我们想象一个朋友正在尝试收集所有 50 个州的 25 美分硬币。当我们按硬币类型分拣零钱时,我们还会喊出与每枚 25 美分硬币相关的州的名称,这样如果是我们朋友没有的,他们就可以将其添加到收藏中。

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.

在此代码的 match 表达式中,我们在匹配 Coin::Quarter 变体值的模式中添加了一个名为 state 的变量。当匹配到 Coin::Quarter 时,state 变量将绑定到该 25 美分硬币所属州的值。然后,我们可以在该分支的代码中使用 state,如下所示:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs:here}}
}

如果我们调用 value_in_cents(Coin::Quarter(UsState::Alaska))coin 将会是 Coin::Quarter(UsState::Alaska)。当我们将该值与每个 match 分支进行比较时,直到遇到 Coin::Quarter(state) 才会匹配。此时,state 的绑定将是 UsState::Alaska。然后我们可以在 println! 表达式中使用该绑定,从而从 QuarterCoin 枚举变体中提取出内部的州值。

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.

Option<T>match 模式 (The Option<T> match Pattern)

The Option<T> match Pattern

在上一节中,我们想在使用 Option<T> 时从 Some 情况下提取出内部的 T 值;我们也可以像处理 Coin 枚举那样使用 match 来处理 Option<T>!我们将比较 Option<T> 的变体,而不是硬币,但 match 表达式的工作方式保持不变。

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<i32>,如果有值,就在该值上加 1。如果没有值,函数应该返回 None 值,而不尝试执行任何操作。

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.

由于有了 match,这个函数非常容易编写,看起来就像示例 6-5 所示。

This function is very easy to write, thanks to match, and will look like Listing 6-5.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:here}}
}

让我们更详细地研究一下 plus_one 的第一次执行。当我们调用 plus_one(five) 时,plus_one 体内的变量 x 将具有值 Some(5)。然后我们将其与每个 match 分支进行比较:

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:

{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:first_arm}}

Some(5) 值与模式 None 不匹配,所以我们继续执行下一个分支:

The Some(5) value doesn’t match the pattern None, so we continue to the next arm:

{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:second_arm}}

Some(5)Some(i) 匹配吗?匹配!我们拥有相同的变体。i 绑定到 Some 中包含的值,因此 i 取得值 5。然后执行 match 分支中的代码,因此我们在 i 的值上加 1,并创建一个内部包含总和 6 的新 Some 值。

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.

现在让我们考虑示例 6-5 中 plus_one 的第二次调用,其中 xNone。我们进入 match 并与第一个分支进行比较:

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:

{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:first_arm}}

匹配了!没有可以加的值,所以程序停止并返回 => 右侧的 None 值。因为第一个分支匹配了,所以不再比较其他分支。

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.

在许多情况下,将 match 和枚举结合使用非常有用。你会经常在 Rust 代码中看到这种模式:对枚举进行 match,将变量绑定到其中的数据,然后根据它执行代码。起初这有点棘手,但一旦你习惯了,你就会希望所有语言都有它。它一直是用户的最爱。

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.

匹配是穷尽的 (Matches Are Exhaustive)

Matches Are Exhaustive

我们还需要讨论 match 的另一个方面:分支的模式必须涵盖所有可能性。考虑一下我们 plus_one 函数的这个版本,它有一个 bug,无法编译:

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:

{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs:here}}

我们没有处理 None 的情况,所以这段代码会导致一个 bug。幸运的是,这是一个 Rust 知道如何捕捉的 bug。如果我们尝试编译这段代码,我们会得到这个错误:

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:

{{#include ../listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt}}

Rust 知道我们没有涵盖每种可能的情况,甚至知道我们忘记了哪种模式!Rust 中的匹配是“穷尽的 (exhaustive)”:为了使代码有效,我们必须穷尽每一种可能性。特别是在 Option<T> 的情况下,当 Rust 阻止我们忘记显式处理 None 情况时,它保护我们不至于假设自己拥有一个值而实际上可能是 null,从而使前面讨论的“十亿美元错误”变得不可能。

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.

通配模式与 _ 占位符 (Catch-All Patterns and the _ Placeholder)

Catch-All Patterns and the _ Placeholder

使用枚举,我们还可以对几个特定的值采取特殊行动,但对所有其他值采取一个默认行动。想象一下我们正在实现一个游戏,如果你在掷骰子时掷出 3,你的玩家不动,而是得到一顶华丽的新帽子。如果你掷出 7,你的玩家会失去一顶华丽的帽子。对于所有其他值,你的玩家在游戏板上移动相应的格数。下面是一个实现该逻辑的 match,其中骰子的结果是硬编码的而不是随机值,所有其他逻辑都由没有主体的函数表示,因为实际实现它们超出了本例的范围:

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 fancy new 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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-15-binding-catchall/src/main.rs:here}}
}

对于前两个分支,模式是字面量值 37。对于涵盖所有其他可能值的最后一个分支,模式是我们选择命名为 other 的变量。为 other 分支运行的代码通过将该变量传递给 move_player 函数来使用它。

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.

这段代码可以编译,即使我们没有列出一个 u8 可以拥有的所有可能值,因为最后一个模式将匹配所有未明确列出的值。这种通配模式 (catch-all pattern) 满足了 match 必须穷尽的要求。请注意,我们必须将通配分支放在最后,因为模式是按顺序评估的。如果我们把通配分支放在前面,其他分支将永远不会运行,所以如果你在通配分支之后添加分支,Rust 会警告我们!

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 had 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!

Rust 还拥有一个模式,当我们想要通配但不想“使用”通配模式中的值时可以使用:_ 是一个特殊的模式,它匹配任何值且不绑定到该值。这告诉 Rust 我们不打算使用该值,所以 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.

让我们改变游戏规则:现在,如果你掷出除 3 或 7 之外的任何数字,你必须重新掷骰子。我们不再需要使用通配值,所以我们可以将代码改为使用 _ 而不是名为 other 的变量:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-16-underscore-catchall/src/main.rs:here}}
}

这个例子也满足穷尽性要求,因为我们在最后一个分支中明确忽略了所有其他值;我们没有遗漏任何东西。

This example also meets the exhaustiveness requirement because we’re explicitly ignoring all other values in the last arm; we haven’t forgotten anything.

最后,我们将再次改变游戏规则,如果你掷出除 3 或 7 之外的任何数字,你的回合内不会发生任何其他事情。我们可以通过使用单元值(我们在 “元组类型” 部分提到的空元组类型)作为与 _ 分支配合的代码来表达这一点:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-17-underscore-unit/src/main.rs:here}}
}

在这里,我们明确告诉 Rust 我们不打算使用任何与前面分支不匹配的其他值,并且在这种情况下我们不想运行任何代码。

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.

关于模式和匹配,我们将在第 19 章涵盖更多内容。现在,我们要继续介绍 if let 语法,它在 match 表达式显得有点冗长的情况下非常有用。

There’s more about patterns and matching that we’ll cover in Chapter 19. 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.

使用 if let 和 let...else 的简洁控制流 (Concise Control Flow with if let and let...else)


x-i18n: generated_at: “2026-03-01T13:49:57Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f6fcaea8b33c8a39aedc4209b7b8bb57a389ab8c64ff051a1793f0c0e025e1da source_path: ch06-03-if-let.md workflow: 16

使用 if letlet...else 的简洁控制流 (Concise Control Flow with if let and let...else)

Concise Control Flow with if let and let...else

if let 语法让你能以一种更简洁的方式组合 iflet,来处理与一个模式相匹配的值,同时忽略其余的值。考虑示例 6-6 中的程序,它匹配 config_max 变量中的 Option<u8> 值,但只想在该值为 Some 变体时执行代码。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs:here}}
}

如果该值是 Some,我们通过将该值绑定到模式中的变量 max 来打印 Some 变体中的值。我们不想对 None 值做任何事情。为了满足 match 表达式,我们必须在仅处理一个变体后添加 _ => (),这是添加起来令人讨厌的样板代码。

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.

相反,我们可以使用 if let 以一种更短的方式来编写。以下代码的行为与示例 6-6 中的 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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs:here}}
}

if let 语法接收一个模式和一个表达式,两者用等号分隔。它的工作方式与 match 相同,其中表达式提供给 match,模式是它的第一个分支。在这种情况下,模式是 Some(max),且 max 绑定到 Some 内部的值。然后我们可以在 if let 块的主体中使用 max,就像我们在对应的 match 分支中使用 max 一样。if let 块中的代码仅在该值匹配模式时运行。

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 only runs if the value matches the pattern.

使用 if let 意味着更少的输入、更少的缩进和更少的样板代码。然而,你失去了 match 强制执行的穷尽性检查,该检查能确保你没有忘记处理任何情况。在 matchif let 之间做出选择取决于你在特定情况下的操作,以及获得简洁性是否是失去穷尽性检查的合适折衷。

Using if let means less typing, less indentation, and less boilerplate code. However, you lose the exhaustive checking match enforces that ensures that you aren’t forgetting to handle any cases. 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 的语法糖,它在值匹配一个模式时运行代码,然后忽略所有其他值。

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 包含一个 else。与 else 配合的代码块与在等效于 if letelsematch 表达式中与 _ 情况配合的代码块相同。回想示例 6-4 中的 Coin 枚举定义,其中 Quarter 变体还持有一个 UsState 值。如果我们想计算看到的除了 25 美分以外的所有硬币,同时宣布 25 美分所属的州,我们可以使用 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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs:here}}
}

或者我们可以使用 if letelse 表达式,如下所示:

Or we could use an if let and else expression, like this:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs:here}}
}

使用 let...else 保持在“快乐路径”上 (Staying on the “Happy Path” with let...else)

Staying on the “Happy Path” with let...else

常见的模式是在存在值时执行某些计算,否则返回一个默认值。继续以带有 UsState 值的硬币为例,如果我们想根据 25 美分硬币上州的年龄说一些有趣的话,我们可能会在 UsState 上引入一个方法来检查州的年龄,如下所示:

The common pattern is to perform some computation when a value is present and return a default value otherwise. Continuing with our example of coins with a UsState value, if we wanted to say something funny depending on how old the state on the quarter was, we might introduce a method on UsState to check the age of a state, like so:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-07/src/main.rs:state}}
}

然后,我们可能会使用 if let 来匹配硬币类型,在条件主体中引入 state 变量,如示例 6-7 所示。

Then, we might use if let to match on the type of coin, introducing a state variable within the body of the condition, as in Listing 6-7.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-07/src/main.rs:describe}}
}

这可以完成任务,但它将工作推到了 if let 语句的主体中,如果要做的工作更复杂,可能很难看清顶层分支是如何关联的。我们也可以利用表达式产生一个值的事实,要么从 if let 产生 state,要么提前返回,如示例 6-8 所示。(你也可以用 match 做类似的事情。)

That gets the job done, but it has pushed the work into the body of the if let statement, and if the work to be done is more complicated, it might be hard to follow exactly how the top-level branches relate. We could also take advantage of the fact that expressions produce a value either to produce the state from the if let or to return early, as in Listing 6-8. (You could do something similar with a match, too.)

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-08/src/main.rs:describe}}
}

不过,这种方式本身也有点烦人!if let 的一个分支产生一个值,而另一个分支则完全从函数返回。

This is a bit annoying to follow in its own way, though! One branch of the if let produces a value, and the other one returns from the function entirely.

为了让这种常见模式更优雅地表达,Rust 提供了 let...elselet...else 语法左侧接收一个模式,右侧接收一个表达式,这与 if let 非常相似,但它没有 if 分支,只有 else 分支。如果模式匹配,它将在外部作用域中绑定来自模式的值。如果模式“不”匹配,程序将流向 else 分支,该分支必须从函数返回。

To make this common pattern nicer to express, Rust has let...else. The let...else syntax takes a pattern on the left side and an expression on the right, very similar to if let, but it does not have an if branch, only an else branch. If the pattern matches, it will bind the value from the pattern in the outer scope. If the pattern does not match, the program will flow into the else arm, which must return from the function.

在示例 6-9 中,你可以看到在使用 let...else 代替 if let 时,示例 6-8 看起来是什么样子。

In Listing 6-9, you can see how Listing 6-8 looks when using let...else in place of if let.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-09/src/main.rs:describe}}
}

请注意,通过这种方式,函数的主体保持在“快乐路径”上,而不会像 if let 那样为两个分支提供明显不同的控制流。

Notice that it stays on the “happy path” in the main body of the function this way, without having significantly different control flow for two branches the way the if let did.

如果你遇到程序逻辑过于冗长而无法使用 match 表达的情况,请记住 if letlet...else 也在你的 Rust 工具箱中。

If you have a situation in which your program has logic that is too verbose to express using a match, remember that if let and let...else are in your Rust toolbox as well.

总结 (Summary)

Summary

我们现在已经涵盖了如何使用枚举来创建可以是枚举值集合之一的自定义类型。我们已经展示了标准库的 Option<T> 类型如何帮助你利用类型系统来防止错误。当枚举值内部持有数据时,你可以根据需要处理的情况数量,使用 matchif let 来提取并使用这些值。

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.

你的 Rust 程序现在可以使用结构体和枚举来表达你领域中的概念。创建要在 API 中使用的自定义类型可确保类型安全:编译器将确保你的函数仅获得每个函数预期的类型值。

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.

为了向用户提供一个组织良好、易于使用且仅公开用户真正需要的 API,现在让我们转向 Rust 的模块系统。

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.

包、Crates 和模块 (Packages, Crates, and Modules)


x-i18n: generated_at: “2026-03-01T13:50:32Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: d5dcbe4f7799c942a95051d313df3b70383a1835cff1fb71510c027c4581a242 source_path: ch07-00-managing-growing-projects-with-packages-crates-and-modules.md workflow: 16

包、Crate 与模块 (Packages, Crates, and Modules)

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.

我们目前编写的程序都在一个文件的单个模块中。随着项目的增长,你应该通过将代码拆分为多个模块然后再拆分为多个文件来组织代码。一个包(package)可以包含多个二进制 crate,并且可选地包含一个库 crate。随着包的增长,你可以将部分内容提取到单独的 crate 中,从而成为外部依赖项。本章涵盖了所有这些技术。对于由一组相互关联且共同发展的包组成的超大型项目,Cargo 提供了工作空间(workspaces),我们将在第 14 章的“Cargo 工作空间”中介绍。

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 “Cargo Workspaces” in Chapter 14.

我们还将讨论封装实现细节,这让你可以在更高层次上重用代码:一旦你实现了一个操作,其他代码就可以通过其公共接口调用你的代码,而无需了解实现是如何工作的。你编写代码的方式定义了哪些部分是公共的供其他代码使用,哪些部分是私有的实现细节(你保留更改这些细节的权利)。这是限制你需要记住的细节量的另一种方式。

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.

一个相关的概念是作用域(scope):编写代码的嵌套上下文具有一组被定义为“在作用域内”的名称。在读取、编写和编译代码时,程序员和编译器需要知道特定位置的特定名称是指变量、函数、结构体、枚举、模块、常量还是其他项,以及该项意味着什么。你可以创建作用域并更改哪些名称在作用域内或作用域外。在同一个作用域内不能有两个同名的项;可以使用工具来解决名称冲突。

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 具有许多功能,允许你管理代码的组织,包括公开哪些细节、哪些细节是私有的,以及程序中每个作用域内有哪些名称。这些功能有时统称为“模块系统 (module system)”,包括:

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:

  • 包 (Packages):Cargo 的一个功能,允许你构建、测试和分享 crate

  • Crate (Crates):产生库或可执行文件的模块树

  • 模块与 use (Modules and use):允许你控制路径的组织、作用域和私有性

  • 路径 (Paths):命名项(如结构体、函数或模块)的一种方式

  • Packages: A Cargo feature that lets you build, test, and share crates

  • 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!

包与 Crates (Packages and Crates)


x-i18n: generated_at: “2026-03-01T13:51:36Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 7141297fcc8bd0d0cb4e850b9f853574ddbb15b48a8b56c615539979c8a9e27e source_path: ch07-01-packages-and-crates.md workflow: 16

包 (Packages) 与 Crate (Crates)

Packages and Crates

我们将介绍的模块系统的第一部分是包(packages)和 crate。

The first parts of the module system we’ll cover are packages and crates.

“Crate” 是 Rust 编译器一次考虑的最小代码量。即使你运行 rustc 而不是 cargo 并且传递了一个源代码文件(正如我们在第 1 章“Rust 程序基础”中所做的那样),编译器也会将该文件视为一个 crate。Crate 可以包含模块,并且这些模块可能在与 crate 一起编译的其他文件中定义,我们将在接下来的章节中看到。

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 “Rust Program Basics” in 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.

Crate 可以有两种形式:二进制 crate 或库 crate。“二进制 crate (Binary crates)” 是可以编译为可执行文件的程序,你可以运行它,例如命令行程序或服务器。每个二进制 crate 必须具有一个名为 main 的函数,该函数定义了可执行文件运行时发生的情况。到目前为止,我们创建的所有 crate 都是二进制 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.

“库 crate (Library crates)” 没有 main 函数,它们不会编译为可执行文件。相反,它们定义了旨在与多个项目共享的功能。例如,我们在第 2 章中使用的 rand crate 提供了生成随机数的功能。大多数时候,Rustaceans 说 “crate” 时是指库 crate,并且他们将 “crate” 与通用编程概念中的“库 (library)”互换使用。

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.”

“Crate 根 (crate root)” 是 Rust 编译器开始并构成 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 “Control Scope and Privacy with Modules”).

“包 (Package)” 是提供一组功能的一个或多个 crate 的捆绑。包包含一个 Cargo.toml 文件,该文件描述了如何构建这些 crate。Cargo 实际上是一个包,其中包含你一直用来构建代码的命令行工具的二进制 crate。Cargo 包还包含一个二进制 crate 所依赖的库 crate。其他项目可以依赖于 Cargo 库 crate,以使用与 Cargo 命令行工具相同的逻辑。

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.

一个包可以包含任意数量的二进制 crate,但最多只能有一个库 crate。一个包必须包含至少一个 crate,无论是库 crate 还是二进制 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.

让我们来看看创建一个包时会发生什么。首先,我们输入命令 cargo new my-project

Let’s walk through what happens when we create a package. First, we enter the command 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

运行 cargo new my-project 后,我们使用 ls 查看 Cargo 创建的内容。在 my-project 目录中,有一个 Cargo.toml 文件,给了我们一个包。还有一个包含 main.rssrc 目录。在文本编辑器中打开 Cargo.toml,注意没有提到 src/main.rs。Cargo 遵循一个惯例,即 src/main.rs 是与包同名的二进制 crate 的 crate 根。同样,Cargo 知道如果包目录包含 src/lib.rs,则该包包含一个与包同名的库 crate,并且 src/lib.rs 是其 crate 根。Cargo 将 crate 根文件传递给 rustc 来构建库或二进制文件。

After we run cargo new my-project, we use ls to see what Cargo creates. In the my-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 that 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.

在这里,我们有一个仅包含 src/main.rs 的包,意味着它仅包含一个名为 my-project 的二进制 crate。如果包同时包含 src/main.rssrc/lib.rs,它就有两个 crate:一个二进制 crate 和一个库 crate,且两者都与包同名。通过在 src/bin 目录中放置文件,一个包可以拥有多个二进制 crate:每个文件都将是一个单独的二进制 crate。

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.

使用模块控制作用域和私有性 (Control Scope and Privacy with Modules)


x-i18n: generated_at: “2026-03-01T13:52:43Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 9a47196bd42516d57eaa32a2813db3f89d404ef3a02f78fb465329acc9c95571 source_path: ch07-02-defining-modules-to-control-scope-and-privacy.md workflow: 16

使用模块控制作用域和私有性 (Control Scope and Privacy with Modules)

Control Scope and Privacy with Modules

在本节中,我们将讨论模块和模块系统的其他部分,即“路径 (paths)”,它们允许你为项命名;use 关键字用于将路径引入作用域;以及 pub 关键字用于使项成为公有的。我们还将讨论 as 关键字、外部包和通配符运算符。

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.

模块速查表 (Modules Cheat Sheet)

Modules Cheat Sheet

在深入了解模块和路径的细节之前,这里我们提供了一个关于模块、路径、use 关键字和 pub 关键字在编译器中如何工作,以及大多数开发人员如何组织代码的快速参考。我们将在本章中贯穿这些规则的示例,但这里是提醒你模块如何工作的绝佳参考。

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.

  • 从 crate 根开始:编译 crate 时,编译器首先在 crate 根文件(通常库 crate 为 src/lib.rs,二进制 crate 为 src/main.rs)中查找要编译的代码。
  • 声明模块:在 crate 根文件中,你可以声明新模块;假设你用 mod garden; 声明了一个 “garden” 模块。编译器将在这些地方查找该模块的代码:
    • 内联,在紧跟 mod garden 之后取代分号的花括号内
    • 在文件 src/garden.rs
    • 在文件 src/garden/mod.rs
  • 声明子模块:在除 crate 根以外的任何文件中,你都可以声明子模块。例如,你可能在 src/garden.rs 中声明 mod vegetables;。编译器将在以父模块命名的目录中的这些地方查找该子模块的代码:
    • 内联,直接跟在 mod vegetables 之后,在花括号内而不是分号处
    • 在文件 src/garden/vegetables.rs
    • 在文件 src/garden/vegetables/mod.rs
  • 模块中代码的路径:一旦模块成为你的 crate 的一部分,只要私有性规则允许,你就可以从同一 crate 的任何其他地方使用该代码的路径来引用该模块中的代码。例如,garden vegetables 模块中的 Asparagus 类型将在 crate::garden::vegetables::Asparagus 处找到。
  • 私有与公有:默认情况下,模块内的代码对其父模块是私有的。要使模块成为公有的,请使用 pub mod 而不是 mod 声明它。要使公有模块内的项也成为公有的,请在它们的声明之前使用 pub
  • use 关键字:在一个作用域内,use 关键字可以为项创建快捷方式,以减少长路径的重复。在任何可以引用 crate::garden::vegetables::Asparagus 的作用域内,你都可以使用 use crate::garden::vegetables::Asparagus; 创建快捷方式,从此以后,你只需要写 Asparagus 就可以在该作用域内使用该类型。

这里,我们创建一个名为 backyard 的二进制 crate 来阐述这些规则。crate 的目录(也名为 backyard)包含这些文件和目录:

backyard
├── Cargo.lock
├── Cargo.toml
└── src
    ├── garden
    │   └── vegetables.rs
    ├── garden.rs
    └── main.rs

在这种情况下,crate 根文件是 src/main.rs,它包含:

{{#rustdoc_include ../listings/ch07-managing-growing-projects/quick-reference-example/src/main.rs}}

pub mod garden; 这一行告诉编译器包含它在 src/garden.rs 中找到的代码,该代码是:

{{#rustdoc_include ../listings/ch07-managing-growing-projects/quick-reference-example/src/garden.rs}}

在这里,pub mod vegetables; 意味着 src/garden/vegetables.rs 中的代码也被包含了。该代码是:

{{#rustdoc_include ../listings/ch07-managing-growing-projects/quick-reference-example/src/garden/vegetables.rs}}

现在让我们深入了解这些规则的细节,并演示它们的实际应用!

Now let’s get into the details of these rules and demonstrate them in action!

“模块 (Modules)” 让我们能够组织 crate 内的代码,以提高可读性和易重用性。模块还允许我们控制项的“私有性 (privacy)”,因为默认情况下,模块内的代码是私有的。私有项是内部实现细节,不可供外部使用。我们可以选择将模块及其内部的项设为公有的,这将公开它们,允许外部代码使用并依赖它们。

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.

作为一个例子,让我们编写一个提供餐厅功能的库 crate。我们将定义函数的签名,但保持其主体为空,以便专注于代码的组织而不是餐厅的实现。

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.

在餐饮业中,餐厅的某些部分被称为前厅(front of house),其他部分被称为后勤(back of house)。“前厅”是顾客所在的地方;这包括领位员为顾客安排座位、服务员下单和收款以及调酒师调酒的地方。“后勤”是厨师在厨房工作、洗碗工清理以及经理进行管理工作的地方。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs}}

我们使用 mod 关键字后跟模块名称(在本例中为 front_of_house)来定义模块。然后,模块的主体放在花括号内。在模块内部,我们可以放置其他模块,就像本例中的 hostingserving 模块一样。模块还可以保存其他项的定义,例如结构体、枚举、常量、特征,以及如示例 7-1 所示的函数。

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.

通过使用模块,我们可以将相关的定义组合在一起,并说明它们为什么相关。使用这些代码的程序员可以根据这些分组来导航代码,而无需阅读所有的定义,从而更容易找到与他们相关的定义。为这些代码添加新功能的程序员将知道代码应该放在哪里,以保持程序井然有序。

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.

早些时候,我们提到 src/main.rssrc/lib.rs 被称为“crate 根 (crate roots)”。它们之所以得名,是因为这两个文件中的任何一个的内容都会在 crate 模块结构的根部形成一个名为 crate 的模块,这就是所谓的“模块树 (module tree)”。

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.

示例 7-2 显示了示例 7-1 中结构的模块树。

Listing 7-2 shows the module tree for the structure in Listing 7-1.

crate
 └── front_of_house
     ├── hosting
     │   ├── add_to_waitlist
     │   └── seat_at_table
     └── serving
         ├── take_order
         ├── serve_order
         └── take_payment

这棵树展示了某些模块是如何嵌套在其他模块内部的;例如,hosting 嵌套在 front_of_house 内部。这棵树还显示了一些模块是“兄弟 (siblings)”,这意味着它们在同一个模块中定义;hostingserving 是在 front_of_house 内部定义的兄弟模块。如果模块 A 包含在模块 B 中,我们说模块 A 是模块 B 的“子 (child)”,模块 B 是模块 A 的“父 (parent)”。请注意,整个模块树都植根于名为 crate 的隐式模块下。

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.

模块树可能会让你联想到计算机上的文件系统目录树;这是一个非常贴切的类比!就像文件系统中的目录一样,你使用模块来组织代码。就像目录中的文件一样,我们需要一种方法来找到我们的模块。

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)


x-i18n: generated_at: “2026-03-01T13:54:06Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: ed9bb2ccb89214a0a47050c4870105a36916c35e634ea68486e5cc669804286b source_path: ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md workflow: 16

在模块树中引用项的路径 (Paths for Referring to an Item in the Module Tree)

Paths for Referring to an Item in the Module Tree

为了向 Rust 展示在模块树的哪里可以找到一个项,我们使用路径,就像在导航文件系统时使用路径一样。要调用一个函数,我们需要知道它的路径。

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.

路径有两种形式:

A path can take two forms:

  • 绝对路径 (absolute path) 是从 crate 根开始的完整路径;对于来自外部 crate 的代码,绝对路径以 crate 名称开始,对于来自当前 crate 的代码,它以字面量 crate 开始。

  • 相对路径 (relative path) 从当前模块开始,并使用 selfsuper 或当前模块中的标识符。

  • 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.

  • A relative path starts from the current module and uses self, super, or an identifier in the current module.

绝对路径和相对路径后面都跟着一个或多个由双冒号 (::) 分隔的标识符。

Both absolute and relative paths are followed by one or more identifiers separated by double colons (::).

回到示例 7-1,假设我们要调用 add_to_waitlist 函数。这相当于在问:add_to_waitlist 函数的路径是什么?示例 7-3 包含了示例 7-1 并删除了一些模块和函数。

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.

我们将展示两种在 crate 根定义的 eat_at_restaurant 新函数中调用 add_to_waitlist 函数的方法。这些路径是正确的,但仍存在另一个问题,将导致此示例目前无法编译。我们稍后会解释原因。

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.

eat_at_restaurant 函数是我们库 crate 公有 API 的一部分,所以我们用 pub 关键字标记它。在“使用 pub 关键字公开路径”部分,我们将详细介绍 pub

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs}}

第一次在 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 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 时,我们使用了相对路径。该路径以 front_of_house 开始,这是定义在与 eat_at_restaurant 相同模块树级别的模块名称。在这里,文件系统的等效表达是使用路径 front_of_house/hosting/add_to_waitlist。以模块名称开始意味着该路径是相对的。

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.

选择使用相对路径还是绝对路径是你根据项目做出的决定,这取决于你更倾向于将项定义代码与使用该项的代码分开移动还是移动到一起。例如,如果我们把 front_of_house 模块和 eat_at_restaurant 函数移动到一个名为 customer_experience 的模块中,我们需要更新 add_to_waitlist 的绝对路径,但相对路径仍然有效。然而,如果我们将 eat_at_restaurant 函数单独移动到一个名为 dining 的模块中,对 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.

让我们尝试编译示例 7-3 并找出它目前为什么无法编译!我们得到的错误如示例 7-4 所示。

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.

{{#include ../listings/ch07-managing-growing-projects/listing-07-03/output.txt}}

错误消息显示模块 hosting 是私有的。换句话说,我们有 hosting 模块和 add_to_waitlist 函数的正确路径,但 Rust 不允许我们使用它们,因为它无法访问私有部分。在 Rust 中,默认情况下所有项(函数、方法、结构体、枚举、模块和常量)对父模块都是私有的。如果你想让一个像函数或结构体这样的项成为私有的,你就把它放在一个模块里。

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.

父模块中的项不能使用子模块内部的私有项,但子模块中的项可以使用其祖先模块中的项。这是因为子模块包装并隐藏了其实现细节,但子模块可以看见它们被定义的上下文。继续我们的比喻,把私有性规则想象成餐厅的后台办公室:里面发生的事情对餐厅顾客是私有的,但办公室经理可以看见并操作他们经营的餐厅里的一切。

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 选择让模块系统以这种方式运行,以便隐藏内部实现细节是默认行为。这样你就知道可以更改内部代码的哪些部分而不会破坏外部代码。然而,Rust 确实为你提供了选项,通过使用 pub 关键字使一个项成为公有的,从而将子模块代码的内部部分暴露给外部祖先模块。

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 the 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.

使用 pub 关键字公开路径 (Exposing Paths with the pub Keyword)

Exposing Paths with the pub Keyword

让我们回到示例 7-4 中告诉我们 hosting 模块是私有的错误。我们希望父模块中的 eat_at_restaurant 函数能够访问子模块中的 add_to_waitlist 函数,因此我们用 pub 关键字标记 hosting 模块,如示例 7-5 所示。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs:here}}

不幸的是,示例 7-5 中的代码仍然导致编译器错误,如示例 7-6 所示。

Unfortunately, the code in Listing 7-5 still results in compiler errors, as shown in Listing 7-6.

{{#include ../listings/ch07-managing-growing-projects/listing-07-05/output.txt}}

发生了什么?在 mod hosting 前面添加 pub 关键字使该模块成为公有的。通过这种更改,如果我们能访问 front_of_house,我们就能访问 hosting。但是 hosting 的“内容”仍然是私有的;使模块公有并不会使其内容也公有。模块上的 pub 关键字仅允许其祖先模块中的代码引用它,而不是访问其内部代码。因为模块是容器,仅使模块公有能做的事情不多;我们需要更进一步,选择使模块内的一个或多个项也成为公有的。

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.

示例 7-6 中的错误显示 add_to_waitlist 函数是私有的。私有性规则适用于结构体、枚举、函数和方法,也适用于模块。

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.

让我们也通过在其定义前添加 pub 关键字使 add_to_waitlist 函数成为公有的,如示例 7-7 所示。

Let’s also make the add_to_waitlist function public by adding the pub keyword before its definition, as in Listing 7-7.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs:here}}

现在代码将可以编译!为了看看添加 pub 关键字如何让我们在遵循私有性规则的情况下在 eat_at_restaurant 中使用这些路径,让我们看看绝对路径和相对路径。

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.

在绝对路径中,我们从 crate 开始,它是 crate 模块树的根。front_of_house 模块定义在 crate 根中。虽然 front_of_house 不是公有的,但由于 eat_at_restaurant 函数与 front_of_house 定义在同一个模块中(也就是说,eat_at_restaurantfront_of_house 是兄弟),我们可以从 eat_at_restaurant 引用 front_of_house。接着是标记为 pubhosting 模块。我们可以访问 hosting 的父模块,所以我们可以访问 hosting。最后,add_to_waitlist 函数被标记为 pub,我们可以访问它的父模块,所以这个函数调用有效!

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 根开始,而是从 front_of_house 开始。front_of_house 模块定义在与 eat_at_restaurant 相同的模块内,所以从定义 eat_at_restaurant 的模块开始的相对路径是有效的。然后,因为 hostingadd_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 以便其他项目可以使用你的代码,你的公有 API 就是你与 crate 使用者之间的契约,它决定了他们如何与你的代码进行交互。关于管理公有 API 的更改以使人们更容易依赖你的 crate,有很多方面的考虑。这些考虑超出了本书的范围;如果你对此话题感兴趣,请参阅 Rust API 指南

If you plan to share your library crate so that 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 beyond the scope of this book; if you’re interested in this topic, see the Rust API Guidelines.

包含二进制文件和库的包的最佳实践

我们提到一个包可以同时包含一个 src/main.rs 二进制 crate 根以及一个 src/lib.rs 库 crate 根,默认情况下,两个 crate 都将具有该包的名称。通常,具有这种同时包含库和二进制 crate 模式的包,在二进制 crate 中只需包含足够的代码来启动一个调用库 crate 中定义的代码的可执行文件。这使得其他项目可以从该包提供的最多功能中受益,因为库 crate 的代码可以被共享。

模块树应该在 src/lib.rs 中定义。然后,任何公有项都可以在二进制 crate 中通过以包名开头的路径来使用。二进制 crate 变成了库 crate 的使用者,就像一个完全外部的 crate 使用该库 crate 一样:它只能使用公有 API。这有助于你设计一个良好的 API;你不仅是作者,也是客户端!

第 12 章中,我们将通过一个同时包含二进制 crate 和库 crate 的命令行程序来演示这种组织实践。

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 defined in the library crate. This lets other projects benefit from the most functionality that the package provides because the library crate’s code can be shared.

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, but you’re also a client!

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.

super 开始相对路径 (Starting Relative Paths with super)

Starting Relative Paths with super

我们可以通过在路径开头使用 super 来构建从父模块开始(而不是当前模块或 crate 根)的相对路径。这就像以 .. 语法开始一个文件系统路径,表示进入父目录。使用 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 that means to go to the parent directory. 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.

考虑示例 7-8 中的代码,它模拟了厨师修正错误的订单并亲自将其送到顾客面前的情况。在 back_of_house 模块中定义的 fix_incorrect_order 函数通过指定以 super 开头的 deliver_order 路径,调用了在父模块中定义的 deliver_order 函数。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs}}

fix_incorrect_order 函数位于 back_of_house 模块中,所以我们可以使用 super 进入 back_of_house 的父模块,在这种情况下是 crate(根)。从那里,我们寻找 deliver_order 并找到了它。成功!我们认为 back_of_house 模块和 deliver_order 函数很可能保持相互之间的这种关系,如果我们决定重组 crate 的模块树,它们会被一起移动。因此,我们使用了 super,这样如果以后代码被移动到不同的模块,我们需要更新代码的地方就会更少。

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 that we’ll have fewer places to update code in the future if this code gets moved to a different module.

使结构体和枚举成为公有的 (Making Structs and Enums Public)

Making Structs and Enums Public

我们也可以使用 pub 将结构体和枚举指定为公有的,但在结构体和枚举中使用 pub 有一些额外的细节。如果在结构体定义前使用 pub,我们使结构体成为公有的,但结构体的字段仍将是私有的。我们可以根据具体情况决定是否使每个字段公有。在示例 7-9 中,我们定义了一个公有的 back_of_house::Breakfast 结构体,带有一个公有的 toast 字段,但有一个私有的 seasonal_fruit 字段。这模拟了餐厅里的情况:顾客可以选择随餐附送的面包类型,但厨师根据当季产品和库存情况决定随餐附送哪种水果。由于水果供应变化很快,顾客无法选择水果,甚至看不到他们将得到哪种水果。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs}}

因为 back_of_house::Breakfast 结构体中的 toast 字段是公有的,在 eat_at_restaurant 中,我们可以使用点号表示法对 toast 字段进行读写。请注意,在 eat_at_restaurant 中我们不能使用 seasonal_fruit 字段,因为 seasonal_fruit 是私有的。尝试取消注释修改 seasonal_fruit 字段值的行,看看会得到什么错误!

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 有一个私有字段,该结构体需要提供一个公有的关联函数来构造 Breakfast 的实例(我们在这里将其命名为 summer)。如果 Breakfast 没有这样一个函数,我们就无法在 eat_at_restaurant 中创建 Breakfast 的实例,因为我们无法在 eat_at_restaurant 中设置私有字段 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.

相比之下,如果我们使一个枚举成为公有的,那么它的所有变体都是公有的。我们只需在 enum 关键字前加上 pub,如示例 7-10 所示。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs}}

因为我们使 Appetizer 枚举成为公有的,所以我们可以在 eat_at_restaurant 中使用 SoupSalad 变体。

Because we made the Appetizer enum public, we can use the Soup and Salad variants in eat_at_restaurant.

除非枚举的变体是公有的,否则枚举并无太大用处;如果在每种情况下都必须用 pub 来标注所有的枚举变体,那将非常烦人,因此枚举变体的默认设置是公有的。结构体通常在字段不公有的情况下也是有用的,因此结构体字段遵循通用的默认私有规则,除非标注了 pub

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 还有一种我们尚未涵盖的情况,那就是我们的最后一个模块系统功能:use 关键字。我们将首先单独介绍 use,然后展示如何组合 pubuse

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.

使用 use 关键字将路径引入作用域 (Bringing Paths Into Scope with the use Keyword)


x-i18n: generated_at: “2026-03-01T13:54:57Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 34c07704e03b7706697506a533d9b66f3c256a08a2c6d8001f8f7707a6e919ff source_path: ch07-04-bringing-paths-into-scope-with-the-use-keyword.md workflow: 16

使用 use 关键字将路径引入作用域 (Bringing Paths into Scope with the use Keyword)

Bringing Paths into Scope with the use Keyword

必须写出调用函数的完整路径可能会让人感到不便且重复。在示例 7-7 中,无论我们选择 add_to_waitlist 函数的绝对路径还是相对路径,每次想要调用 add_to_waitlist 时都必须指定 front_of_househosting。幸运的是,有一种方法可以简化这个过程:我们可以使用 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-11 中,我们将 crate::front_of_house::hosting 模块引入了 eat_at_restaurant 函数的作用域,这样我们只需指定 hosting::add_to_waitlist 即可在 eat_at_restaurant 中调用 add_to_waitlist 函数。

In Listing 7-11, we bring the crate::front_of_house::hosting module into the scope of the eat_at_restaurant function so that we only have to specify hosting::add_to_waitlist to call the add_to_waitlist function in eat_at_restaurant.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs}}

在作用域中添加 use 和路径类似于在文件系统中创建符号链接。通过在 crate 根中添加 use crate::front_of_house::hostinghosting 现在在该作用域中是一个有效的名称,就像 hosting 模块就是在 crate 根中定义的一样。通过 use 引入作用域的路径也会检查私有性,就像其他任何路径一样。

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 仅为发生 use 的特定作用域创建快捷方式。示例 7-12 将 eat_at_restaurant 函数移动到一个名为 customer 的新子模块中,这与 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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs}}

编译器错误显示该快捷方式在 customer 模块内不再适用:

The compiler error shows that the shortcut no longer applies within the customer module:

{{#include ../listings/ch07-managing-growing-projects/listing-07-12/output.txt}}

请注意,还有一个警告,提示 use 在其作用域内不再被使用!要修复此问题,也将 use 移动到 customer 模块内,或者在子模块 customer 内使用 super::hosting 引用父模块中的快捷方式。

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 路径 (Creating Idiomatic use Paths)

Creating Idiomatic use Paths

在示例 7-11 中,你可能会奇怪为什么我们指定 use crate::front_of_house::hosting 然后在 eat_at_restaurant 中调用 hosting::add_to_waitlist ,而不是像示例 7-13 那样一直指定 use 路径到 add_to_waitlist 函数以达到同样的结果。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs}}

虽然示例 7-11 和示例 7-13 都完成了相同的任务,但示例 7-11 是使用 use 将函数引入作用域的惯用方式。将函数的父模块引入作用域意味着我们在调用函数时必须指定父模块。在调用函数时指定父模块可以清楚地表明该函数不是本地定义的,同时还能最大限度地减少完整路径的重复。示例 7-13 中的代码对于 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.

另一方面,当使用 use 引入结构体、枚举和其他项时,惯用的做法是指定完整路径。示例 7-14 显示了将标准库的 HashMap 结构体引入二进制 crate 作用域的惯用方式。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-14/src/main.rs}}
}

这种惯用法背后并没有强有力的理由:这只是一种已经形成的惯例,人们已经习惯了以这种方式阅读和编写 Rust 代码。

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.

这种惯例的例外情况是我们要使用 use 语句将两个同名的项引入作用域,因为 Rust 不允许这样做。示例 7-15 展示了如何将两个同名但父模块不同的 Result 类型引入作用域,以及如何引用它们。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs:here}}

如你所见,使用父模块可以区分这两种 Result 类型。如果相反我们指定 use std::fmt::Resultuse std::io::Result,我们将在同一个作用域内拥有两个 Result 类型,Rust 将不知道我们在使用 Result 时是指哪一个。

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.

使用 as 关键字提供新名称 (Providing New Names with the as Keyword)

Providing New Names with the as Keyword

对于使用 use 将两个同名类型引入同一作用域的问题,还有另一种解决方案:在路径之后,我们可以指定 as 和该类型的一个新本地名称(或“别名”)。示例 7-16 显示了通过使用 as 重命名两个 Result 类型中的一个来编写示例 7-15 代码的另一种方式。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs:here}}

在第二个 use 语句中,我们为 std::io::Result 类型选择了新名称 IoResult,这不会与我们也引入作用域的来自 std::fmtResult 冲突。示例 7-15 和示例 7-16 都被认为是惯用的,所以选择权在你!

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!

使用 pub use 重导出名称 (Re-exporting Names with pub use)

Re-exporting Names with pub use

当我们使用 use 关键字将名称引入作用域时,该名称在导入它的作用域内是私有的。为了使该作用域之外的代码能够像在那个作用域内定义一样引用该名称,我们可以结合使用 pubuse。这种技术被称为“重导出 (re-exporting)”,因为我们不仅将一个项引入作用域,还使该项可供他人引入他们的作用域。

When we bring a name into scope with the use keyword, the name is private to the scope into which we imported it. To enable code outside that scope to refer to that name as if it had been defined in that 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.

示例 7-17 显示了示例 7-11 中的代码,根模块中的 use 更改为 pub use

Listing 7-17 shows the code in Listing 7-11 with use in the root module changed to pub use.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs}}

在此更改之前,外部代码必须通过使用路径 restaurant::front_of_house::hosting::add_to_waitlist() 来调用 add_to_waitlist 函数,这也需要将 front_of_house 模块标记为 pub。现在,由于此 pub use 已从根模块重导出了 hosting 模块,外部代码可以改用路径 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.

当代码的内部结构与调用代码的程序员对该领域的思考方式不同时,重导出非常有用。例如,在这个餐厅比喻中,经营餐厅的人考虑的是“前厅”和“后勤”。但来到餐厅的顾客可能不会用这些术语来考虑餐厅的各个部分。使用 pub use,我们可以用一种结构编写代码,但公开另一种不同的结构。这样做可以使我们的库对于开发库的程序员和调用库的程序员都组织良好。我们将在第 14 章的“公开方便的公有 API”中看到另一个关于 pub use 的例子,以及它如何影响 crate 的文档。

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 “Exporting a Convenient Public API” in Chapter 14.

使用外部包 (Using External Packages)

Using External Packages

在第 2 章中,我们编写了一个猜谜游戏项目,它使用了一个名为 rand 的外部包来获取随机数。为了在我们的项目中使用 rand,我们将此行添加到了 Cargo.toml 中:

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:

{{#include ../listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml:9:}}

Cargo.toml 中添加 rand 作为依赖项告诉 Cargo 从 crates.io 下载 rand 包及其任何依赖项,并使 rand 对我们的项目可用。

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.

然后,为了将 rand 的定义引入我们的包的作用域,我们添加了一行以 crate 名称 rand 开头的 use 语句,并列出了我们想要引入作用域的项。回想一下第 2 章的“生成随机数”中,我们将 Rng 特征引入了作用域并调用了 rand::thread_rng 函数:

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 “Generating a Random Number” in Chapter 2, we brought the Rng trait into scope and called the rand::thread_rng function:

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs:ch07-04}}

Rust 社区成员在 crates.io 上提供了许多包,将其中任何一个拉入你的包都涉及这些相同的步骤:在你的包的 Cargo.toml 文件中列出它们,并使用 use 将它们 crate 中的项引入作用域。

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.

请注意,标准 std 库也是一个对我们的包而言是外部的 crate。由于标准库是随 Rust 语言一起提供的,我们不需要更改 Cargo.toml 来包含 std。但我们确实需要用 use 来引用它,以便将其中的项引入我们的包作用域。例如,对于 HashMap,我们会使用这一行:

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:

#![allow(unused)]
fn main() {
use std::collections::HashMap;
}

这是一个从 std(标准库 crate 的名称)开始的绝对路径。

This is an absolute path starting with std, the name of the standard library crate.

使用嵌套路径清理大型 use 列表 (Using Nested Paths to Clean Up use Lists)

Using Nested Paths to Clean Up use Lists

如果我们使用定义在同一个 crate 或同一个模块中的多个项,将每个项列在单独的一行中会占用我们文件中大量的垂直空间。例如,我们在示例 2-4 的猜谜游戏中有的这两条 use 语句将 std 中的项引入了作用域:

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:

{{#rustdoc_include ../listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs:here}}

相反,我们可以使用嵌套路径在一行中将相同的项引入作用域。我们通过指定路径的公共部分,后跟两个冒号,然后在花括号中列出路径中不同的部分来实现这一点,如示例 7-18 所示。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-18/src/main.rs:here}}

在更大的程序中,使用嵌套路径从同一 crate 或模块引入许多项可以大幅减少所需的单独 use 语句数量!

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 语句时非常有用。例如,示例 7-19 显示了两条 use 语句:一条将 std::io 引入作用域,另一条将 std::io::Write 引入作用域。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs}}

这两条路径的公共部分是 std::io,这正是完整的第一条路径。为了将这两条路径合并为一条 use 语句,我们可以在嵌套路径中使用 self,如示例 7-20 所示。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs}}

这一行将 std::iostd::io::Write 引入了作用域。

This line brings std::io and std::io::Write into scope.

使用通配符运算符导入项 (Importing Items with the Glob Operator)

Importing Items with 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:

#![allow(unused)]
fn main() {
use std::collections::*;
}

这条 use 语句将 std::collections 中定义的所有公有项引入当前作用域。使用通配符运算符时要小心!通配符会使识别哪些名称在作用域内以及程序中使用的名称是在何处定义的变得更加困难。此外,如果依赖项更改了其定义,你导入的内容也会随之更改,这可能会在升级依赖项时导致编译器错误,例如,如果依赖项添加了一个与你在同一作用域内的定义同名的定义。

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. Additionally, if the dependency changes its definitions, what you’ve imported changes as well, which may lead to compiler errors when you upgrade the dependency if the dependency adds a definition with the same name as a definition of yours in the same scope, for example.

通配符运算符常在测试时使用,用于将所有受测项引入 tests 模块;我们将在第 11 章的“如何编写测试”中讨论。通配符运算符有时也被用作 prelude(预导入)模式的一部分:有关该模式的更多信息,请参阅标准库文档

The glob operator is often used when testing to bring everything under test into the tests module; we’ll talk about that in “How to Write Tests” 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.

将模块拆分为不同的文件 (Separating Modules into Different Files)


x-i18n: generated_at: “2026-03-01T13:55:41Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f71fdf4512195e4c048c6b9c89e5575fea219332099660464e1b2a279f9d5782 source_path: ch07-05-separating-modules-into-different-files.md workflow: 16

将模块拆分为不同的文件 (Separating Modules into Different Files)

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.

例如,让我们从示例 7-17 中的代码开始,该代码有多个餐厅模块。我们将把模块提取到文件中,而不是在 crate 根文件中定义所有模块。在这种情况下,crate 根文件是 src/lib.rs,但此过程也适用于 crate 根文件为 src/main.rs 的二进制 crate。

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.

首先,我们将 front_of_house 模块提取到它自己的文件中。删除 front_of_house 模块花括号内的代码,仅保留 mod front_of_house; 声明,使 src/lib.rs 包含示例 7-21 所示的代码。请注意,在我们在示例 7-22 中创建 src/front_of_house.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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs}}

接下来,将花括号中的代码放入名为 src/front_of_house.rs 的新文件中,如示例 7-22 所示。编译器知道要查找这个文件,因为它在 crate 根中遇到了名为 front_of_house 的模块声明。

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.

{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs}}

请注意,在模块树中,你只需要使用 mod 声明加载一个文件“一次”。一旦编译器知道该文件是项目的一部分(并且由于你放置 mod 语句的位置,它知道了代码在模块树中的位置),项目中的其他文件应该使用指向声明位置的路径来引用已加载文件的代码,如“在模块树中引用项的路径”部分所述。换句话说,mod “不是”你在其他编程语言中可能见到的“include”操作。

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.

接下来,我们将 hosting 模块提取到它自己的文件中。过程略有不同,因为 hostingfront_of_house 的子模块,而不是根模块的子模块。我们将把 hosting 的文件放在一个新目录中,该目录将以其在模块树中的祖先命名,在此例中为 src/front_of_house

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,我们将 src/front_of_house.rs 更改为仅包含 hosting 模块的声明:

To start moving hosting, we change src/front_of_house.rs to contain only the declaration of the hosting module:

{{#rustdoc_include ../listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs}}

然后,我们创建一个 src/front_of_house 目录和一个 hosting.rs 文件,以包含在 hosting 模块中所做的定义:

Then, we create a src/front_of_house directory and a hosting.rs file to contain the definitions made in the hosting module:

{{#rustdoc_include ../listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs}}

如果我们转而将 hosting.rs 放在 src 目录中,编译器会期望 hosting.rs 的代码位于在 crate 根中声明的 hosting 模块中,而不是被声明为 front_of_house 模块的子模块。编译器关于检查哪些文件对应哪些模块代码的规则意味着目录和文件能更好地匹配模块树。

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.

备选文件路径 (Alternate File Paths)

Alternate File Paths

到目前为止,我们已经介绍了 Rust 编译器使用的最惯用的文件路径,但 Rust 也支持旧风格的文件路径。对于在 crate 根中声明的名为 front_of_house 的模块,编译器将在以下位置查找该模块的代码:

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:

  • src/front_of_house.rs(我们介绍过的)
  • src/front_of_house/mod.rs(旧风格,仍支持的路径)

对于作为 front_of_house 子模块的名为 hosting 的模块,编译器将在以下位置查找该模块的代码:

For a module named hosting that is a submodule of front_of_house, the compiler will look for the module’s code in:

  • src/front_of_house/hosting.rs(我们介绍过的)
  • 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.

使用名为 mod.rs 文件的主要缺点是你的项目最终可能会有很多名为 mod.rs 的文件,当你同时在编辑器中打开它们时,这可能会变得很混乱。

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.

我们已经将每个模块的代码移动到了单独的文件中,模块树保持不变。eat_at_restaurant 中的函数调用将无需任何修改即可工作,尽管定义位于不同的文件中。这种技术让你可以随着模块规模的增长将其移动到新文件中。

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.

请注意,src/lib.rs 中的 pub use crate::front_of_house::hosting 语句也没有改变,use 对哪些文件作为 crate 的一部分被编译也没有任何影响。mod 关键字声明模块,而 Rust 会在与模块同名的文件中查找进入该模块的代码。

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.

总结 (Summary)

Summary

Rust 允许你将一个包拆分为多个 crate,并将一个 crate 拆分为模块,以便你可以从另一个模块中引用一个模块中定义的项。你可以通过指定绝对或相对路径来实现这一点。这些路径可以通过 use 语句引入作用域,以便你可以在该作用域内多次使用该项时使用较短的路径。模块代码默认是私有的,但你可以通过添加 pub 关键字使定义成为公有的。

Rust lets you split a package into multiple crates and a crate into modules so that 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 that 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.

在下一章中,我们将研究标准库中的一些集合数据结构,你可以在你整齐组织的代码中使用它们。

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)


x-i18n: generated_at: “2026-03-01T13:56:31Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 0226216f7782e55712c8c583b06280c38483c093b9b4ef501b1c95f09eb2514a source_path: ch08-00-common-collections.md workflow: 16

常用集合 (Common Collections)

Common Collections

Rust 的标准库包含许多非常有用的数据结构,称为“集合 (collections)”。大多数其他数据类型代表一个特定的值,但集合可以包含多个值。与内置的数组和元组类型不同,这些集合指向的数据存储在堆上,这意味着数据量不需要在编译时已知,并且可以随着程序的运行而增长或缩小。每种集合都有不同的功能和成本,为当前情况选择合适的集合是你随着时间的推移会培养的一种技能。在本章中,我们将讨论在 Rust 程序中经常使用的三种集合:

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 that 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:

  • “向量 (vector)” 允许你在相邻位置存储可变数量的值。

  • “字符串 (string)” 是字符的集合。我们之前提到过 String 类型,但在本章中,我们将深入讨论它。

  • “哈希映射 (hash map)” 允许你将一个值与一个特定的键关联起来。它是更通用的数据结构“映射 (map)”的一种特定实现。

  • 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.

  • 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.

使用 Vector 存储列表 (Storing Lists of Values with Vectors)


x-i18n: generated_at: “2026-03-01T13:57:53Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 8ded9a736f59d44aa6dc9c9121b503db8ef1d3e2eae8db5be83c04180e3d618f source_path: ch08-01-vectors.md workflow: 16

使用向量存储列表 (Storing Lists of Values with Vectors)

Storing Lists of Values with Vectors

我们要看的第一种集合类型是 Vec<T>,也称为“向量 (vector)”。向量允许你在单个数据结构中存储多个值,这些值在内存中彼此相邻放置。向量只能存储相同类型的值。当你有一个项列表时,例如文件中的文本行或购物车中物品的价格,它们非常有用。

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.

创建新向量 (Creating a New Vector)

Creating a New Vector

要创建一个新的空向量,我们调用 Vec::new 函数,如示例 8-1 所示。

To create a new, empty vector, we call the Vec::new function, as shown in Listing 8-1.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-01/src/main.rs:here}}
}

注意这里我们添加了类型注解。因为我们还没有向这个向量中插入任何值,Rust 不知道我们打算存储哪种类型的元素。这是一个重点。向量是使用泛型实现的;我们将在第 10 章介绍如何在你自己的类型中使用泛型。目前,只需知道标准库提供的 Vec<T> 类型可以持有任何类型。当我们创建一个用于持有特定类型的向量时,可以在尖括号内指定该类型。在示例 8-1 中,我们告诉 Rust v 中的 Vec<T> 将持有 i32 类型的元素。

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.

更多时候,你会创建一个带有初始值的 Vec<T>,而 Rust 会推断你想要存储的值的类型,所以你很少需要做这种类型注解。Rust 方便地提供了 vec! 宏,它会创建一个包含你所提供的值的新向量。示例 8-2 创建了一个新的 Vec<i32>,其中包含值 123。整数类型是 i32,因为正如我们在第 3 章“数据类型”部分讨论的那样,它是默认的整数类型。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-02/src/main.rs:here}}
}

因为我们提供了初始的 i32 值,Rust 可以推断出 v 的类型是 Vec<i32>,因此不需要类型注解。接下来,我们将看看如何修改向量。

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.

更新向量 (Updating a Vector)

Updating a Vector

要创建一个向量并向其中添加元素,我们可以使用 push 方法,如示例 8-3 所示。

To create a vector and then add elements to it, we can use the push method, as shown in Listing 8-3.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-03/src/main.rs:here}}
}

正如我们在第 3 章讨论的任何变量一样,如果我们希望能够改变它的值,我们需要使用 mut 关键字使其可变。我们在其中放置的数字都是 i32 类型,Rust 会根据数据推断出这一点,所以我们不需要 Vec<i32> 注解。

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.

读取向量元素 (Reading Elements of Vectors)

Reading Elements of Vectors

有两种引用存储在向量中的值的方法:通过索引或使用 get 方法。在接下来的示例中,为了更加清晰,我们对这些函数返回的值的类型进行了注解。

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.

示例 8-4 展示了访问向量中值的两种方法,即使用索引语法和 get 方法。

Listing 8-4 shows both methods of accessing a value in a vector, with indexing syntax and the get method.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-04/src/main.rs:here}}
}

注意这里的一些细节。我们使用索引值 2 来获取第三个元素,因为向量是按数字索引的,从零开始。使用 &[] 会给我们一个该索引处元素的引用。当我们使用带有作为参数传递的索引的 get 方法时,我们会得到一个可以与 match 一起使用的 Option<&T>

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.

Rust 提供这两种引用元素的方式,以便你可以选择在尝试使用超出现有元素范围的索引值时程序的行为。举个例子,让我们看看当我们有一个包含五个元素的向量,然后尝试通过每种技术访问索引 100 处的元素时会发生什么,如示例 8-5 所示。

Rust provides these two ways to reference an element so that 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-05/src/main.rs:here}}
}

当我们运行这段代码时,第一种 [] 方法将导致程序恐慌 (panic),因为它引用了一个不存在的元素。当你希望程序在尝试访问超出向量末尾的元素时崩溃时,最好使用此方法。

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.

get 方法接收到一个向量外部的索引时,它会返回 None 而不会恐慌。如果你有时可能会访问超出向量范围的元素(在正常情况下),你可以使用此方法。正如在第 6 章中所讨论的,你的代码随后将拥有逻辑来处理拥有 Some(&element)None 的情况。例如,索引可能来自一个输入数字的人。如果他们不小心输入了一个太大的数字而程序得到了一个 None 值,你可以告诉用户当前向量中有多少项,并给他们另一次输入有效值的机会。这会比由于打字错误而导致程序崩溃更用户友好!

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!

当程序拥有一个有效引用时,借用检查器会强制执行所有权和借用规则(在第 4 章中介绍),以确保此引用以及对向量内容的任何其他引用保持有效。回想一下规则:在同一个作用域内不能同时拥有可变引用和不可变引用。该规则适用于示例 8-6,其中我们持有一个对向量第一个元素的不可变引用,并尝试向末尾添加一个元素。如果我们稍后在函数中也尝试引用该元素,此程序将无法工作。

When the program has a valid reference, the borrow checker enforces the ownership and borrowing rules (covered in Chapter 4) to ensure that 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.

{{#rustdoc_include ../listings/ch08-common-collections/listing-08-06/src/main.rs:here}}

编译这段代码将产生以下错误:

Compiling this code will result in this error:

{{#include ../listings/ch08-common-collections/listing-08-06/output.txt}}

示例 8-6 中的代码看起来似乎应该可以工作:为什么第一个元素的引用要关心向量末尾的更改呢?这个错误是由于向量的工作方式造成的:因为向量在内存中将值相邻放置,如果向量当前存储的位置没有足够的空间将所有元素相邻放置,那么在向量末尾添加新元素可能需要分配新内存并将旧元素复制到新空间。在这种情况下,对第一个元素的引用将指向已释放的内存。借用规则防止程序陷入这种情况。

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.

注意:有关 Vec<T> 类型实现细节的更多信息,请参阅 “The Rustonomicon”

Note: For more on the implementation details of the Vec<T> type, see “The Rustonomicon”.

遍历向量中的值 (Iterating Over the Values in a Vector)

Iterating Over the Values in a Vector

要依次访问向量中的每个元素,我们会遍历所有元素,而不是使用索引一次访问一个。示例 8-7 展示了如何使用 for 循环获取 i32 值向量中每个元素的不可变引用并打印它们。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-07/src/main.rs:here}}
}

我们也可以遍历可变向量中每个元素的可变引用,以便对所有元素进行更改。示例 8-8 中的 for 循环将给每个元素加 50

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-08/src/main.rs:here}}
}

为了更改可变引用所指向的值,在我们可以使用 += 运算符之前,必须使用 * 解引用运算符来获取 i 中的值。我们将在第 15 章的“通过引用获取值”部分更多地讨论解引用运算符。

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 Reference to the Value” section of Chapter 15.

由于借用检查器的规则,无论是不可变地还是可变地遍历向量都是安全的。如果我们尝试在示例 8-7 和示例 8-8 的 for 循环体中插入或删除项,我们将得到类似于示例 8-6 代码中得到的编译器错误。for 循环持有的对向量的引用防止了对整个向量的同时修改。

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.

使用枚举存储多种类型 (Using an Enum to Store Multiple Types)

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!

例如,假设我们想要从电子表格的一行中获取值,其中该行的一些列包含整数,一些包含浮点数,还有一些包含字符串。我们可以定义一个枚举,其变体将持有不同的值类型,并且所有的枚举变体都将被视为相同的类型:即该枚举的类型。然后,我们可以创建一个向量来持有该枚举,从而最终持有不同的类型。我们在示例 8-9 中演示了这一点。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-09/src/main.rs:here}}
}

Rust 需要在编译时知道向量中将会有哪些类型,以便它准确知道在堆上存储每个元素需要多少内存。我们还必须明确这个向量中允许哪些类型。如果 Rust 允许向量持有任何类型,那么一个或多个类型可能会对向量元素执行的操作导致错误。结合使用枚举和 match 表达式意味着 Rust 将在编译时确保处理了每种可能的情况,如第 6 章所述。

Rust needs to know what types will be in the vector at compile time so that 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.

如果你在运行时不知道程序将获取哪些穷尽的类型集来存储在向量中,枚举技术将行不通。相反,你可以使用特征对象(trait object),我们将在第 18 章介绍它。

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 18.

既然我们已经讨论了向量的一些最常见用法,请务必查看标准库为 Vec<T> 定义的所有许多有用方法的 API 文档。例如,除了 push 之外,还有一个 pop 方法可以移除并返回最后一个元素。

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.

丢弃向量也会丢弃其元素 (Dropping a Vector Drops Its Elements)

Dropping a Vector Drops Its Elements

像任何其他 struct 一样,向量在超出作用域时会被释放,如示例 8-10 中标注的那样。

Like any other struct, a vector is freed when it goes out of scope, as annotated in Listing 8-10.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-10/src/main.rs:here}}
}

当向量被丢弃时,它的所有内容也都会被丢弃,这意味着它持有的整数将被清理。借用检查器确保任何对向量内容的引用仅在向量本身有效时才被使用。

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.

让我们继续学习下一种集合类型:String

Let’s move on to the next collection type: String!

使用 String 存储 UTF-8 编码的文本 (Storing UTF-8 Encoded Text with Strings)


x-i18n: generated_at: “2026-03-01T13:59:06Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: c69284d04088681b53c2fd05bc87219f122414aa639d9ea68f8e2d35c7b4b2c4 source_path: ch08-02-strings.md workflow: 16

使用字符串存储 UTF-8 编码的文本 (Storing UTF-8 Encoded Text with Strings)

Storing UTF-8 Encoded Text with Strings

我们在第 4 章谈到了字符串,但现在我们将更深入地研究它们。新 Rustaceans 通常在字符串上遇到困难,这是三个原因的综合:Rust 倾向于暴露可能的错误、字符串是比许多程序员所认为的更复杂的数据结构,以及 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.

我们在集合的上下文中讨论字符串,因为字符串被实现为字节的集合,外加一些当这些字节被解释为文本时提供有用功能的方法。在本节中,我们将讨论每种集合类型都具有的 String 操作,例如创建、更新和读取。我们还将讨论 String 与其他集合的不同之处,即由于人们和计算机对 String 数据的解释差异,对 String 进行索引是如何变得复杂的。

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.

定义字符串 (Defining Strings)

Defining Strings

我们首先定义我们所说的“字符串 (string)”一词是什么意思。Rust 在核心语言中只有一种字符串类型,即字符串切片 str,通常以其借用形式 &str 出现。在第 4 章中,我们讨论了字符串切片,它们是对存储在别处的某些 UTF-8 编码字符串数据的引用。例如,字符串字面量存储在程序的可执行文件中,因此它们是字符串切片。

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 标准库提供而不是编码在核心语言中的,它是一种可增长的、可变的、有所有权的、UTF-8 编码的字符串类型。当 Rustaceans 在 Rust 中提到“字符串”时,他们可能指的是 String 或字符串切片 &str 类型,而不仅仅是其中一种。尽管本节主要关于 String,但在 Rust 的标准库中大量使用了这两种类型,并且 String 和字符串切片都是 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.

创建新字符串 (Creating a New String)

Creating a New String

许多可用于 Vec<T> 的操作也可用于 String,因为 String 实际上被实现为字节向量的包装器,并带有一些额外的保证、限制和功能。new 函数是一个在 Vec<T>String 中以相同方式工作的函数的示例,用于创建实例,如示例 8-11 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-11/src/main.rs:here}}
}

这一行创建了一个名为 s 的新的空字符串,然后我们可以向其中加载数据。通常,我们会从一些初始数据开始字符串。为此,我们使用 to_string 方法,它在实现 Display 特征的任何类型上都可用,字符串字面量正是如此。示例 8-12 显示了两个示例。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-12/src/main.rs:here}}
}

这段代码创建了一个包含 initial contents 的字符串。

This code creates a string containing initial contents.

我们还可以使用 String::from 函数从字符串字面量创建 String。示例 8-13 中的代码与示例 8-12 中使用 to_string 的代码是等效的。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-13/src/main.rs:here}}
}

由于字符串被用于很多事情,我们可以为字符串使用许多不同的泛型 API,为我们提供了很多选择。其中一些可能看起来是多余的,但它们都有各自的地位!在这种情况下,String::fromto_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.

请记住字符串是 UTF-8 编码的,所以我们可以在其中包含任何正确编码的数据,如示例 8-14 所示。

Remember that strings are UTF-8 encoded, so we can include any properly encoded data in them, as shown in Listing 8-14.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-14/src/main.rs:here}}
}

所有这些都是有效的 String 值。

All of these are valid String values.

更新字符串 (Updating a String)

Updating a String

String 可以在大小上增长,其内容也可以改变,就像 Vec<u8> 的内容一样,如果你向其中推送更多数据的话。此外,你可以方便地使用 + 运算符或 format! 宏来拼接 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.

使用 push_strpush 附加 (Appending with push_str or push)

Appending with push_str or push

我们可以通过使用 push_str 方法附加字符串切片来增长 String,如示例 8-15 所示。

We can grow a String by using the push_str method to append a string slice, as shown in Listing 8-15.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-15/src/main.rs:here}}
}

在这两行之后,s 将包含 foobarpush_str 方法接收一个字符串切片,因为我们不一定想获取参数的所有权。例如,在示例 8-16 的代码中,我们希望在将 s2 的内容附加到 s1 后仍能使用 s2

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-16/src/main.rs:here}}
}

如果 push_str 方法获取了 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 方法接收单个字符作为参数并将其添加到 String 中。示例 8-17 使用 push 方法将字母 l 添加到 String 中。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-17/src/main.rs:here}}
}

结果,s 将包含 lol

As a result, s will contain lol.

使用 + 运算符或 format! 宏拼接 (Concatenating with + or format!)

Concatenating with + or format!

通常,你会想要组合两个现有的字符串。一种方法是使用 + 运算符,如示例 8-18 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-18/src/main.rs:here}}
}

字符串 s3 将包含 Hello, world!s1 在相加后失效的原因,以及我们使用 s2 引用的原因,与使用 + 运算符时调用的方法的签名有关。+ 运算符使用 add 方法,其签名看起来像这样:

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:

fn add(self, s: &str) -> String {

在标准库中,你会看到 add 使用泛型和关联类型定义。在这里,我们代入了具体类型,这也是当我们用 String 值调用此方法时发生的情况。我们将在第 10 章讨论泛型。这个签名给了我们理解 + 运算符微妙之处所需的线索。

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.

首先,s2 有一个 &,这意味着我们将第二个字符串的引用添加到第一个字符串中。这是因为 add 函数中的 s 参数:我们只能将字符串切片添加到 String 中;我们不能将两个 String 值相加。但是等一下——&s2 的类型是 &String,而不是 add 的第二个参数中指定的 &str。那么,为什么示例 8-18 能编译呢?

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 string slice 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?

我们之所以能在调用 add 时使用 &s2 ,是因为编译器可以将 &String 参数强转为 &str。当我们调用 add 方法时,Rust 使用了 deref 强制转换 (deref coercion),这里它将 &s2 转换为 &s2[..]。我们将在第 15 章更深入地讨论 deref 强制转换。因为 add 不会获取 s 参数的所有权,所以在此操作之后 s2 仍将是一个有效的 String

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 获取了 self 的所有权,因为 self “没有” &。这意味着示例 8-18 中的 s1 将被移动到 add 调用中,并且在那之后不再有效。因此,虽然 let s3 = s1 + &s2; 看起来像是会复制两个字符串并创建一个新的,但这条语句实际上获取了 s1 的所有权,附加了 s2 内容的副本,然后返回了结果的所有权。换句话说,它看起来像是在进行大量的复制,但实际上并非如此;这个实现比复制更高效。

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.

如果我们需要拼接多个字符串,+ 运算符的行为就会变得笨拙:

If we need to concatenate multiple strings, the behavior of the + operator gets unwieldy:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs:here}}
}

此时,s 将是 tic-tac-toe。伴随着所有的 +" 字符,很难看清发生了什么。对于以更复杂的方式组合字符串,我们可以改用 format! 宏:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/no-listing-02-format/src/main.rs:here}}
}

这段代码也将 s 设置为 tic-tac-toeformat! 宏的工作方式类似于 println!,但它不是将输出打印到屏幕上,而是返回一个包含内容的 String。使用 format! 的版本更易读,并且由 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.

字符串索引 (Indexing into Strings)

Indexing into Strings

在许多其他编程语言中,通过索引引用来访问字符串中的单个字符是一个有效且常见的操作。然而,如果你在 Rust 中尝试使用索引语法访问 String 的部分内容,你将得到一个错误。考虑示例 8-19 中的无效代码。

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.

{{#rustdoc_include ../listings/ch08-common-collections/listing-08-19/src/main.rs:here}}

这段代码将导致以下错误:

This code will result in the following error:

{{#include ../listings/ch08-common-collections/listing-08-19/output.txt}}

错误说明了一切:Rust 字符串不支持索引。但为什么不支持呢?为了回答这个问题,我们需要讨论 Rust 是如何在内存中存储字符串的。

The error tells 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.

内部表示 (Internal Representation)

Internal Representation

StringVec<u8> 的包装。让我们看看示例 8-14 中一些正确编码的 UTF-8 示例字符串。首先,这一个:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-14/src/main.rs:spanish}}
}

在这种情况下,len 将是 4 ,这意味着存储字符串 "Hola" 的向量有 4 个字节长。每个字母在 UTF-8 编码时占用 1 个字节。然而,下面这一行可能会让你感到惊讶(注意这个字符串是以西里尔大写字母 Ze 开头的,不是数字 3):

In this case, len will be 4, which means the vector storing the string "Hola" is 4 bytes long. Each of these letters takes 1 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):

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-14/src/main.rs:russian}}
}

如果问你这个字符串有多长,你可能会说是 12。事实上,Rust 的回答是 24:这是在 UTF-8 中编码 “Здравствуйте” 所需的字节数,因为该字符串中的每个 Unicode 标量值都占用 2 个字节的存储空间。因此,字符串字节的索引并不总是对应于一个有效的 Unicode 标量值。为了演示,考虑这段无效的 Rust 代码:

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:

let hello = "Здравствуйте";
let answer = &hello[0];

你已经知道 answer 不会是 З,即第一个字母。当以 UTF-8 编码时,З 的第一个字节是 208,第二个是 151,所以看起来 answer 实际上应该是 208,但 208 本身并不是一个有效的字符。如果用户要求获取此字符串的第一个字母,返回 208 可能不是他们想要的;然而,这是 Rust 在字节索引 0 处拥有的唯一数据。用户通常不希望返回字节值,即使字符串只包含拉丁字母:如果 &"hi"[0] 是返回字节值的有效代码,它将返回 104,而不是 h

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 &"hi"[0] were valid code that returned the byte value, it would return 104, not h.

那么答案是,为了避免返回意想不到的值并导致可能无法立即发现的 bug,Rust 根本不会编译这段代码,并在开发过程的早期就防止了误解。

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.

字节、标量值和字形集 (Bytes, Scalar Values, and Grapheme Clusters)

Bytes, Scalar Values, and Grapheme Clusters

关于 UTF-8 的另一点是,从 Rust 的角度来看,实际上有三种相关的方式来看待字符串:作为字节、标量值和字形集 (grapheme clusters)(最接近我们所谓的“字母 (letters)”的东西)。

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).

如果我们看用天城文书写的印地语单词 “नमस्ते”,它被存储为一个 u8 值的向量,看起来像这样:

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:

[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
224, 165, 135]

那是 18 个字节,也是计算机最终存储这些数据的方式。如果我们把它们看作 Unicode 标量值(也就是 Rust 的 char 类型),那些字节看起来像这样:

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:

['न', 'म', 'स', '्', 'त', 'े']

这里有六个 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:

["न", "म", "स्", "ते"]

Rust 提供了不同的方式来解释计算机存储的原始字符串数据,以便每个程序可以根据需要选择解释方式,而不管数据是哪种人类语言。

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 不允许我们通过索引 String 来获取字符的最后一个原因是,索引操作预计总是花费常数时间 (O(1))。但在 String 上无法保证这种性能,因为 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.

切片字符串 (Slicing Strings)

Slicing Strings

对字符串进行索引通常是个坏主意,因为不清楚字符串索引操作的返回类型应该是什么:是一个字节值、一个字符、一个字形集,还是一个字符串切片。因此,如果你确实需要使用索引来创建字符串切片,Rust 会要求你更加具体。

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.

与其使用带有单个数字的 [] 进行索引,你可以使用带有范围的 [] 来创建包含特定字节的字符串切片:

Rather than indexing using [] with a single number, you can use [] with a range to create a string slice containing particular bytes:

#![allow(unused)]
fn main() {
let hello = "Здравствуйте";

let s = &hello[0..4];
}

在这里,s 将是一个包含字符串前 4 个字节的 &str。早些时候,我们提到这些字符中的每一个都是 2 个字节,这意味着 s 将是 Зд

Here, s will be a &str that contains the first 4 bytes of the string. Earlier, we mentioned that each of these characters was 2 bytes, which means s will be Зд.

如果我们尝试使用类似 &hello[0..1] 这样的代码仅切片一个字符的部分字节,Rust 在运行时会恐慌,就像在向量中访问了无效索引一样:

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:

{{#include ../listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt}}

你在使用范围创建字符串切片时应该保持谨慎,因为这样做可能会导致程序崩溃。

You should use caution when creating string slices with ranges, because doing so can crash your program.

遍历字符串 (Iterating Over Strings)

Iterating Over Strings

操作字符串片段的最佳方式是明确你是想要字符还是字节。对于单个 Unicode 标量值,请使用 chars 方法。在 “Зд” 上调用 chars 会分离并返回两个 char 类型的值,你可以遍历结果以访问每个元素:

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:

#![allow(unused)]
fn main() {
for c in "Зд".chars() {
    println!("{c}");
}
}

这段代码将打印以下内容:

This code will print the following:

З
д

或者,bytes 方法会返回每个原始字节,这可能适合你的领域:

Alternatively, the bytes method returns each raw byte, which might be appropriate for your domain:

#![allow(unused)]
fn main() {
for b in "Зд".bytes() {
    println!("{b}");
}
}

这段代码将打印组成此字符串的 4 个字节:

This code will print the 4 bytes that make up this string:

208
151
208
180

但请务必记住,有效的 Unicode 标量值可能由超过 1 个字节组成。

But be sure to remember that valid Unicode scalar values may be made up of more than 1 byte.

从字符串中获取字形集(如天城文)很复杂,因此标准库不提供此功能。如果你需要此功能,crates.io 上有可用的 crate。

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.

处理字符串的复杂性 (Handling the Complexities of Strings)

Handling the Complexities of Strings

总而言之,字符串很复杂。不同的编程语言对于如何向程序员展示这种复杂性做出了不同的选择。Rust 选择将正确处理 String 数据作为所有 Rust 程序的默认行为,这意味着程序员必须预先花更多心思在处理 UTF-8 数据上。这种权衡暴露了比其他编程语言更明显的字符串复杂性,但它能防止你在开发周期的后期处理涉及非 ASCII 字符的错误。

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.

好消息是标准库提供了许多基于 String&str 类型构建的功能,以帮助正确处理这些复杂情况。请务必查看文档,了解有用的方法,如用于字符串搜索的 contains 和用于将字符串部分替换为另一个字符串的 replace

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.

让我们切换到稍微简单一些的东西:哈希映射 (hash maps)!

Let’s switch to something a bit less complex: hash maps!

在哈希映射中存储带有键的关联值 (Storing Keys with Associated Values in Hash Maps)


x-i18n: generated_at: “2026-03-01T13:59:53Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 2588825afb8c1fa18a4ab8b4b5ba6c49976fbda23e25d304ab916576c41b63d8 source_path: ch08-03-hash-maps.md workflow: 16

在哈希映射中存储键和关联值 (Storing Keys with Associated Values in Hash Maps)

Storing Keys with Associated Values in Hash Maps

我们要介绍的最后一种常用集合是哈希映射 (hash map)。类型 HashMap<K, V> 使用一个“哈希函数 (hashing function)”来存储 K 类型的键与 V 类型的值的映射,该函数决定了它如何将这些键和值放入内存中。许多编程语言都支持这种数据结构,但它们通常使用不同的名称,例如“哈希 (hash)”、“映射 (map)”、“对象 (object)”、“哈希表 (hash table)”、“字典 (dictionary)”或“关联数组 (associative array)”,仅举几例。

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.

当你不想像向量那样通过索引,而是想通过可以是任何类型的键来查找数据时,哈希映射非常有用。例如,在一个游戏中,你可以用哈希映射来跟踪每个队的得分,其中每个键是队名,值是每个队的得分。给定一个队名,你就可以检索到它的得分。

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.

在本节中,我们将介绍哈希映射的基本 API,但在标准库为 HashMap<K, V> 定义的函数中还隐藏着更多的好东西。一如既往,请查看标准库文档以获取更多信息。

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.

创建新哈希映射 (Creating a New Hash Map)

Creating a New Hash Map

创建一个空哈希映射的一种方法是使用 new 及其 insert 方法来添加元素。在示例 8-20 中,我们要跟踪两个队的得分,队名分别是“Blue”和“Yellow”。Blue 队开始时得 10 分,Yellow 队开始时得 50 分。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-20/src/main.rs:here}}
}

注意,我们需要首先从标准库的集合部分 use 这个 HashMap。在我们三种常用集合中,这一种是最不常用的,因此它没有包含在 prelude 中自动引入作用域的功能里。哈希映射得到的标准库支持也较少;例如,没有用于构造它们的内置宏。

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.

就像向量一样,哈希映射将其数据存储在堆上。这个 HashMap 的键类型为 String,值的类型为 i32。与向量一样,哈希映射是同质的:所有的键必须具有相同的类型,所有的值也必须具有相同的类型。

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.

访问哈希映射中的值 (Accessing Values in a Hash Map)

Accessing Values in a Hash Map

我们可以通过将键提供给 get 方法来从哈希映射中获取一个值,如示例 8-21 所示。

We can get a value out of the hash map by providing its key to the get method, as shown in Listing 8-21.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-21/src/main.rs:here}}
}

在这里,score 将获得与 Blue 队关联的值,结果将是 10get 方法返回一个 Option<&V>;如果哈希映射中没有该键的值,get 将返回 None。此程序通过调用 copied 来处理 Option,以获得一个 Option<i32> 而不是 Option<&i32>,然后使用 unwrap_or,如果 scores 中没有该键的条目,则将 score 设置为零。

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 rather than an Option<&i32>, then unwrap_or to set score to zero if scores doesn’t have an entry for the key.

我们可以像遍历向量那样,使用 for 循环遍历哈希映射中的每个键值对:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs:here}}
}

这段代码将以任意顺序打印每一对:

This code will print each pair in an arbitrary order:

Yellow: 50
Blue: 10

哈希映射中的所有权管理 (Managing Ownership in Hash Maps)

Managing Ownership in Hash Maps

对于像 i32 这样实现了 Copy 特征的类型,其值会被拷贝进哈希映射。对于像 String 这样的拥有所有权的值,其值将被移动,哈希映射将成为这些值的所有者,如示例 8-22 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-22/src/main.rs:here}}
}

在通过调用 insert 将变量 field_namefield_value 移动到哈希映射中之后,我们将无法再使用它们。

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.

如果我们向哈希映射插入值的引用,那么这些值将不会被移动。引用所指向的值必须在哈希映射有效期间保持有效。我们将在第 10 章的“使用生命周期验证引用”部分详细讨论这些问题。

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 “Validating References with Lifetimes” in Chapter 10.

更新哈希映射 (Updating a Hash Map)

Updating a Hash Map

尽管键值对的数量是可以增长的,但每个唯一的键在同一时间只能关联一个值(但反之则不然:例如,Blue 队和 Yellow 队都可以在 scores 哈希映射中存储值 10)。

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).

当你想要更改哈希映射中的数据时,必须决定如何处理键已经分配了值的情况。你可以用新值替换旧值,完全不顾旧值。你可以保留旧值并忽略新值,只有在键“还没有”关联值时才添加新值。或者你可以将旧值和新值结合起来。让我们看看如何执行这其中的每一种操作!

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)

Overwriting a Value

如果我们向哈希映射插入一个键和一个值,然后再次插入同一个键但带有一个不同的值,那么与该键关联的值将被替换。即使示例 8-23 中的代码调用了两次 insert,哈希映射也只会包含一个键值对,因为两次我们都是在为 Blue 队的键插入值。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-23/src/main.rs:here}}
}

这段代码将打印 {"Blue": 25}。原来的值 10 已经被覆盖了。

This code will print {"Blue": 25}. The original value of 10 has been overwritten.

仅在键不存在时添加键和值 (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.

哈希映射为此提供了一个名为 entry 的特殊 API,它接收你想要检查的键作为参数。entry 方法的返回值是一个名为 Entry 的枚举,代表可能存在也可能不存在的值。假设我们要检查 Yellow 队的键是否有关联值。如果没有,我们想插入值 50;Blue 队也是如此。使用 entry API,代码如示例 8-24 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-24/src/main.rs:here}}
}

Entry 上的 or_insert 方法被定义为:如果对应的 Entry 键存在,则返回该键值的可变引用;如果不存在,则将参数作为该键的新值插入,并返回新值的可变引用。这种技术比我们自己编写逻辑要整洁得多,此外,它与借用检查器配合得更好。

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.

运行示例 8-24 中的代码将打印 {"Yellow": 50, "Blue": 10}。对 entry 的第一次调用将为 Yellow 队插入键及其值 50,因为 Yellow 队目前还没有值。第二次对 entry 的调用不会更改哈希映射,因为 Blue 队已经有了值 10

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.

根据旧值更新值 (Updating a Value Based on the Old Value)

Updating a Value Based on the Old Value

哈希映射的另一个常见用例是查找一个键的值,然后根据其旧值对其进行更新。例如,示例 8-25 显示了统计某段文本中每个单词出现次数的代码。我们使用哈希映射,将单词作为键,并递增值来跟踪我们见过该单词的次数。如果是第一次见到某个单词,我们将首先插入值 0

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch08-common-collections/listing-08-25/src/main.rs:here}}
}

这段代码将打印 {"world": 2, "hello": 1, "wonderful": 1}。你可能会看到相同的键值对以不同的顺序打印出来:回想“访问哈希映射中的值”部分,遍历哈希映射是以任意顺序发生的。

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 “Accessing Values in a Hash Map” that iterating over a hash map happens in an arbitrary order.

split_whitespace 方法会在 text 的值上返回一个由空白字符分隔的子切片迭代器。or_insert 方法返回指向指定键值的可变引用 (&mut V)。在这里,我们将该可变引用存储在 count 变量中,因此为了给该值赋值,必须首先使用星号 (*) 对 count 进行解引用。可变引用在 for 循环结束时超出作用域,因此所有这些更改都是安全的,并且符合借用规则。

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.

哈希函数 (Hashing Functions)

Hashing Functions

默认情况下,HashMap 使用一种名为 SipHash 的哈希函数,它可以抵御涉及哈希表的拒绝服务 (DoS) 攻击1。这并不是目前最快的哈希算法,但其性能下降所换取的更好的安全性是值得的。如果你通过分析代码发现默认的哈希函数对你的用途来说太慢,你可以通过指定一个不同的 hasher 来切换到另一个函数。Hasher 是实现 BuildHasher 特征的类型。我们将在第 10 章讨论特征以及如何实现它们。你不必非得从头开始实现自己的 hasher;crates.io 上有其他 Rust 用户分享的库,提供了实现许多常见哈希算法的 hasher。

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.

总结 (Summary)

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:

  1. 给定一个整数列表,使用向量并返回列表的中位数(排序后位于中间位置的值)和众数(出现次数最多的值;哈希映射在这里会很有用)。
  2. 将字符串转换为 Pig Latin。每个单词的第一个辅音字母被移到单词末尾,并添加 ay,所以 first 变成 irst-fay。以元音字母开头的单词则在末尾添加 hayapple 变成 apple-hay)。请记住关于 UTF-8 编码的细节!
  3. 使用哈希映射和向量,创建一个文本界面,允许用户将员工姓名添加到公司的部门中;例如,“Add Sally to Engineering” 或 “Add Amir to Sales”。然后,让用户检索部门中所有人员的列表,或按部门排序的公司中所有人员的列表,按字母顺序排列。

标准库 API 文档描述了向量、字符串和哈希映射所拥有的方法,这些方法对这些练习很有帮助!

The standard library API documentation describes methods that vectors, strings, and hash maps have that will be helpful for these exercises!

我们正在进入更复杂的程序,在这些程序中操作可能会失败,所以现在是讨论错误处理的最佳时机。我们接下来就讨论它!

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!


  1. https://zh.wikipedia.org/wiki/SipHash ↩2

错误处理 (Error Handling)


x-i18n: generated_at: “2026-03-01T14:00:31Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 8c5d97ecf63d50fcb053197176dc31544d19add7df3c60e61791b95659890733 source_path: ch09-00-error-handling.md workflow: 16

错误处理 (Error Handling)

Error Handling

错误在软件开发中是无法避免的事实,因此 Rust 提供了许多功能来处理出现问题的情况。在许多情况下,Rust 要求你承认错误的可能性,并采取一些行动,然后你的代码才能编译。这一要求确保你在将代码部署到生产环境之前,能够发现并适当地处理错误,从而使你的程序更加健壮!

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 deploying your code to production!

Rust 将错误分为两大类:可恢复错误和不可恢复错误。对于“可恢复错误 (recoverable error)”,例如“找不到文件”错误,我们很可能只想向用户报告问题并重试操作。“不可恢复错误 (unrecoverable errors)”通常是 bug 的征兆,例如尝试访问数组末尾之外的位置,因此我们希望立即停止程序。

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.

大多数语言不区分这两类错误,并以相同的方式处理它们,使用诸如异常 (exceptions) 之类的机制。Rust 没有异常。相反,它为可恢复错误提供了 Result<T, E> 类型,并提供了 panic! 宏,当程序遇到不可恢复错误时停止执行。本章首先介绍调用 panic!,然后讨论返回 Result<T, E> 值。此外,我们将探讨在决定是尝试从错误中恢复还是停止执行时的考虑因素。

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.

使用 panic! 处理不可恢复的错误 (Unrecoverable Errors with panic!)


x-i18n: generated_at: “2026-03-01T14:01:46Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: edce46b44eee961106ca49be8b1ce306e400c767304e9005b8763c141a444d1d source_path: ch09-01-unrecoverable-errors-with-panic.md workflow: 16

使用 panic! 处理不可恢复的错误 (Unrecoverable Errors with panic!)

Unrecoverable Errors with panic!

有时代码中会发生一些糟糕的事情,而你对此无能为力。在这种情况下,Rust 提供了 panic! 宏。在实践中,有两种引发恐慌的方式:采取导致代码恐慌的行动(例如访问超出数组末尾的位置)或显式调用 panic! 宏。在这两种情况下,我们都会在程序中引发恐慌。默认情况下,这些恐慌将打印一条失败消息、展开(unwind)栈、清理栈并退出。通过环境变量,你还可以让 Rust 在发生恐慌时显示调用栈,以便更容易追踪恐慌的来源。

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.

针对恐慌展开栈或中止 (Unwinding the Stack or Aborting in Response to a Panic)

Unwinding the Stack or Aborting in Response to a Panic

默认情况下,当恐慌发生时,程序开始“展开 (unwinding)”,这意味着 Rust 会回溯栈并清理它遇到的每个函数中的数据。然而,这种回溯和清理工作量很大。因此,Rust 允许你选择另一种方案:立即“中止 (aborting)”,即不清理直接结束程序。

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.

程序当时使用的内存将需要由操作系统来清理。如果在你的项目中,你需要让生成的二进制文件尽可能小,你可以通过在 Cargo.toml 文件的适当 [profile] 部分添加 panic = 'abort',将发生恐慌时的行为从展开切换为中止。例如,如果你想在发布模式下发生恐慌时中止,请添加:

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:

[profile.release]
panic = 'abort'

让我们在一个简单的程序中尝试调用 panic!

Let’s try calling panic! in a simple program:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/no-listing-01-panic/src/main.rs}}
}

当你运行程序时,你会看到类似这样的内容:

When you run the program, you’ll see something like this:

{{#include ../listings/ch09-error-handling/no-listing-01-panic/output.txt}}

panic! 的调用导致了最后两行中包含的错误消息。第一行显示了我们的恐慌消息以及源代码中发生恐慌的位置:src/main.rs:2:5 表明它是 src/main.rs 文件的第二行第五个字符。

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! 宏调用。在其他情况下,panic! 调用可能位于我们的代码所调用的代码中,错误消息报告的文件名和行号将是调用 panic! 宏的他人的代码,而不是最终导致 panic! 调用的我们代码的那一行。

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! 调用源自的函数的“回溯 (backtrace)”来找出导致问题的代码部分。为了理解如何使用 panic! 回溯,让我们看另一个例子,看看当 panic! 调用由于我们代码中的 bug 而源自库(而不是由我们的代码直接调用宏)时是什么样子的。示例 9-1 中的代码尝试访问向量中超出有效索引范围的索引。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/listing-09-01/src/main.rs}}
}

在这里,我们尝试访问向量的第 100 个元素(位于索引 99 处,因为索引从零开始),但该向量只有三个元素。在这种情况下,Rust 会引发恐慌。使用 [] 应该返回一个元素,但如果你传递一个无效的索引,Rust 在这里无法返回任何正确的元素。

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.

在 C 语言中,尝试读取超出数据结构末尾的位置是未定义行为。你可能会得到该内存位置上的任何内容(尽管该内存并不属于该结构体),该位置对应于该数据结构中的那个元素。这被称为“缓冲区超读 (buffer overread)”,如果攻击者能够操纵索引从而读取存储在数据结构之后的他们不被允许访问的数据,可能会导致安全漏洞。

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.

为了保护你的程序免受此类漏洞的影响,如果你尝试读取不存在的索引处的元素,Rust 将停止执行并拒绝继续。让我们试一试:

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:

{{#include ../listings/ch09-error-handling/listing-09-01/output.txt}}

此错误指向了我们的 main.rs 的第 4 行,即我们尝试访问 v 中向量索引 99 的地方。

This error points at line 4 of our main.rs where we attempt to access index 99 of the vector in v.

note: 行告诉我们可以设置 RUST_BACKTRACE 环境变量来获取导致错误的确切情况的“回溯”。“回溯 (backtrace)”是到达这一点所调用的所有函数的列表。Rust 中的回溯与其他语言中的回溯工作方式相同:阅读回溯的关键是从顶部开始阅读,直到看到你编写的文件。那就是问题起源的地方。该位置上方的行是你的代码调用的代码;下方的行是调用你代码的代码。这些前后行可能包括 Rust 核心代码、标准库代码或你正在使用的 crate。让我们尝试通过将 RUST_BACKTRACE 环境变量设置为除 0 以外的任何值来获取回溯。示例 9-2 显示了你将看到的类似输出。

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 to get 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.

$ 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/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/std/src/panicking.rs:692:5
   1: core::panicking::panic_fmt
             at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/core/src/panicking.rs:75:14
   2: core::panicking::panic_bounds_check
             at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/core/src/panicking.rs:273:5
   3: <usize as core::slice::index::SliceIndex<[T]>>::index
             at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/slice/index.rs:274:10
   4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
             at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/slice/index.rs:16:9
   5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
             at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:3361:9
   6: panic::main
             at ./src/main.rs:4:6
   7: core::ops::function::FnOnce::call_once
             at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/ops/function.rs:250:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

内容真多!你看到的具体输出可能会根据你的操作系统和 Rust 版本而有所不同。为了获得包含此类信息的回溯,必须启用调试符号。当使用 cargo buildcargo run 而不带 --release 标志时,调试符号是默认启用的,就像我们这里所做的那样。

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.

在示例 9-2 的输出中,回溯的第 6 行指向了我们项目中导致问题的行:src/main.rs 的第 4 行。如果我们不想让程序恐慌,我们应该从提到我们编写的文件的第一行所指向的位置开始调查。在示例 9-1 中,我们故意编写了会恐慌的代码,修复恐慌的方法是不请求超出向量索引范围的元素。将来当你的代码发生恐慌时,你需要弄清楚代码正在对哪些值采取什么行动导致了恐慌,以及代码应该采取什么行动。

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.

我们将在本章稍后的“要 panic! 还是不要 panic!部分回到 panic! 以及我们何时应该或不应该使用 panic! 来处理错误条件。接下来,我们将看看如何使用 Result 从错误中恢复。

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.

使用 Result 处理可恢复的错误 (Recoverable Errors with Result)


x-i18n: generated_at: “2026-03-01T14:03:26Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: dab3e88d324cdde74cf96356c58a423747a5735ac6848d8d4592dc7c13637c62 source_path: ch09-02-recoverable-errors-with-result.md workflow: 16

使用 Result 处理可恢复的错误 (Recoverable Errors with Result)

Recoverable Errors with 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.

回想第 2 章“使用 Result 处理潜在的失败”中,Result 枚举被定义为具有两个变体,OkErr,如下所示:

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:

#![allow(unused)]
fn main() {
enum Result<T, E> {
    Ok(T),
    Err(E),
}
}

TE 是泛型类型参数:我们将在第 10 章更详细地讨论泛型。你现在需要知道的是,T 代表在 Ok 变体中成功情况下将返回的值的类型,而 E 代表在 Err 变体中失败情况下将返回的错误的类型。因为 Result 具有这些泛型类型参数,所以我们可以在许多不同的情况下使用 Result 类型及其定义的函数,其中我们要返回的成功值和错误值可能各不相同。

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.

让我们调用一个返回 Result 值的函数,因为该函数可能会失败。在示例 9-3 中,我们尝试打开一个文件。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/listing-09-03/src/main.rs}}
}

File::open 的返回类型是 Result<T, E>。泛型参数 T 已被 File::open 的实现填充为成功值的类型 std::fs::File,这是一个文件句柄。错误值中使用的 E 的类型是 std::io::Error。这种返回类型意味着调用 File::open 可能会成功并返回一个我们可以读取或写入的文件句柄。函数调用也可能会失败:例如,文件可能不存在,或者我们可能没有访问该文件的权限。File::open 函数需要有一种方式告诉我们它是成功还是失败,同时还要给我们文件句柄或错误信息。这些信息正是 Result 枚举所传达的。

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 成功的情况下,变量 greeting_file_result 中的值将是一个包含文件句柄的 Ok 实例。在失败的情况下,greeting_file_result 中的值将是一个包含有关所发生错误类型的更多信息的 Err 实例。

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.

我们需要在示例 9-3 的代码中添加内容,以便根据 File::open 返回的值采取不同的操作。示例 9-4 展示了使用我们在第 6 章中讨论过的基本工具 match 表达式来处理 Result 的一种方法。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/listing-09-04/src/main.rs}}
}

注意,就像 Option 枚举一样,Result 枚举及其变体已经由 prelude 引入作用域,所以我们不需要在 match 分支中的 OkErr 变体之前指定 Result::

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.

当结果为 Ok 时,这段代码将从 Ok 变体中返回内部的 file 值,然后我们将该文件句柄值分配给变量 greeting_file。在 match 之后,我们可以使用该文件句柄进行读取或写入。

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.

match 的另一个分支处理从 File::open 获得 Err 值的情况。在这个例子中,我们选择了调用 panic! 宏。如果我们的当前目录中没有名为 hello.txt 的文件,并且我们运行这段代码,我们将看到来自 panic! 宏的以下输出:

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:

{{#include ../listings/ch09-error-handling/listing-09-04/output.txt}}

照例,这个输出准确地告诉了我们哪里出了问题。

As usual, this output tells us exactly what has gone wrong.

匹配不同的错误 (Matching on Different Errors)

Matching on Different Errors

示例 9-4 中的代码无论 File::open 失败的原因是什么都会 panic!。然而,我们希望针对不同的失败原因采取不同的行动。如果 File::open 因为文件不存在而失败,我们希望创建该文件并返回新文件的句柄。如果 File::open 因为任何其他原因失败(例如,因为我们没有打开文件的权限),我们仍然希望代码以示例 9-4 中的方式 panic!。为此,我们添加了一个嵌套的 match 表达式,如示例 9-5 所示。

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.

{{#rustdoc_include ../listings/ch09-error-handling/listing-09-05/src/main.rs}}

File::openErr 变体内部返回的值的类型是 io::Error,这是一个由标准库提供的结构体。该结构体有一个 kind 方法,我们可以调用它来获得一个 io::ErrorKind 值。枚举 io::ErrorKind 由标准库提供,其中的变体代表了 io 操作可能产生的不同种类的错误。我们想要使用的是 ErrorKind::NotFound 变体,它表示我们尝试打开的文件尚不存在。因此,我们对 greeting_file_result 进行匹配,但在 Err 分支内还对 error.kind() 进行了一个嵌套匹配。

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().

我们在嵌套匹配中想要检查的条件是 error.kind() 返回的值是否是 ErrorKind 枚举的 NotFound 变体。如果是,我们尝试使用 File::create 创建该文件。然而,因为 File::create 也可能会失败,所以我们在嵌套的 match 表达式中需要第二个分支。当文件无法创建时,会打印一条不同的错误消息。外层 match 的第二个分支保持不变,因此除了文件缺失错误之外的任何错误都会导致程序恐慌。

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.

Result<T, E> 中使用 match 的替代方案

这里的 match 真多!match 表达式非常有用,但也是非常基础的。在第 13 章中,你将学习闭包(closures),它们与 Result<T, E> 上定义的许多方法配合使用。当在代码中处理 Result<T, E> 值时,这些方法可以比使用 match 更简洁。

例如,这里有另一种编写与示例 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:?}");
        }
    });
}

虽然这段代码的行为与示例 9-5 相同,但它不包含任何 match 表达式,而且读起来更清爽。在阅读完第 13 章后回到这个例子,并在标准库文档中查找 unwrap_or_else 方法。在处理错误时,还有更多此类方法可以清理庞大、嵌套的 match 表达式。

Alternatives to Using match with 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.

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:

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.

错误时引发恐慌的简写 (Shortcuts for Panic on Error)

Shortcuts for Panic on Error

使用 match 效果还不错,但可能有点冗长,而且并不总能很好地传达意图。Result<T, E> 类型定义了许多辅助方法来执行各种更具体的任务。unwrap 方法是一个简写方法,其实现就像我们在示例 9-4 中编写的 match 表达式一样。如果 Result 值是 Ok 变体,unwrap 将返回 Ok 内部的值。如果 ResultErr 变体,unwrap 将为我们调用 panic! 宏。下面是 unwrap 实际运行的一个例子:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs}}
}

如果我们运行这段代码且没有 hello.txt 文件,我们将看到来自 unwrap 方法所执行的 panic! 调用的错误消息:

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:

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" }

类似地,expect 方法还允许我们选择 panic! 错误消息。使用 expect 而不是 unwrap 并提供良好的错误消息可以传达你的意图,并使追踪恐慌源头变得更容易。expect 的语法看起来像这样:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/no-listing-05-expect/src/main.rs}}
}

我们以与 unwrap 相同的方式使用 expect:返回文件句柄或调用 panic! 宏。expect 在其 panic! 调用中使用的错误消息将是我们传递给 expect 的参数,而不是 unwrap 使用的默认 panic! 消息。它看起来像这样:

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:

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" }

在具有生产质量的代码中,大多数 Rustaceans 会选择 expect 而不是 unwrap,并提供更多关于操作为何预计总是成功的上下文。这样,如果你的假设被证明是错误的,你就有了更多可用于调试的信息。

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.

传播错误 (Propagating Errors)

Propagating Errors

当函数的实现调用了可能会失败的操作时,你可以在函数内部不处理错误,而是将错误返回给调用代码,以便由其决定如何操作。这被称为“传播 (propagating)”错误,它赋予了调用代码更多的控制权,因为调用代码可能拥有比你代码上下文更多的信息或逻辑来决定应该如何处理错误。

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.

例如,示例 9-6 显示了一个从文件中读取用户名的函数。如果文件不存在或无法读取,此函数会将这些错误返回给调用该函数的代码。

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.

#![allow(unused)]
fn main() {
{{#include ../listings/ch09-error-handling/listing-09-06/src/main.rs:here}}
}

这个函数可以写得简短得多,但为了探索错误处理,我们将先通过大量手动操作开始;最后,我们将展示简短的方法。让我们先看看函数的返回类型:Result<String, io::Error>。这意味着该函数返回一个 Result<T, E> 类型的值,其中泛型参数 T 已填充为具体类型 String,泛型类型 E 已填充为具体类型 io::Error

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.

如果此函数运行顺利没有任何问题,调用此函数的代码将接收到一个包含 StringOk 值——即此函数从文件中读取的 username。如果此函数遇到任何问题,调用代码将接收到一个包含 io::Error 实例的 Err 值,该实例包含有关问题的更多信息。我们选择 io::Error 作为此函数的返回类型,是因为在此函数体中我们调用的可能失败的两个操作恰好都返回此类型的错误值:File::open 函数和 read_to_string 方法。

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.

函数体从调用 File::open 函数开始。然后,我们使用类似于示例 9-4 中 match 的方式来处理 Result 值。如果 File::open 成功,模式变量 file 中的文件句柄就成为了可变变量 username_file 中的值,函数继续执行。在 Err 的情况下,我们不调用 panic!,而是使用 return 关键字从整个函数提前返回,并将 File::open 的错误值(现在在模式变量 e 中)传回给调用代码作为此函数的错误值。

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.

因此,如果我们 username_file 中有一个文件句柄,函数随后会在变量 username 中创建一个新 String,并调用 username_file 中文件句柄的 read_to_string 方法,将文件内容读取到 username 中。read_to_string 方法也会返回一个 Result,因为它可能会失败,即使 File::open 成功了。所以,我们需要另一个 match 来处理该 Result:如果 read_to_string 成功,那么我们的函数就成功了,我们返回文件中现在位于 username 中的用户名,并将其包裹在 Ok 中。如果 read_to_string 失败,我们返回错误值的方式与处理 File::open 返回值的 match 中返回错误值的方式相同。然而,我们不需要显式地说 return,因为这是函数的最后一个表达式。

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.

调用此代码的代码随后将处理获取包含用户名的 Ok 值或包含 io::ErrorErr 值。由调用代码来决定如何处理这些值。如果调用代码得到了 Err 值,例如,它可以调用 panic! 并使程序崩溃,使用一个默认用户名,或者从文件之外的其他地方查找用户名。我们没有关于调用代码实际尝试做什么的足够信息,因此我们将所有的成功或错误信息向上传播,由其进行适当处理。

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.

这种传播错误的模式在 Rust 中非常常见,以至于 Rust 提供了问号运算符 ? 来使之更容易。

This pattern of propagating errors is so common in Rust that Rust provides the question mark operator ? to make this easier.

传播错误的简写:? 运算符 (The ? Operator Shortcut)

The ? Operator Shortcut

示例 9-7 显示了 read_username_from_file 的一个实现,它具有与示例 9-6 相同的功能,但此实现使用了 ? 运算符。

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.

#![allow(unused)]
fn main() {
{{#include ../listings/ch09-error-handling/listing-09-07/src/main.rs:here}}
}

置于 Result 值之后的 ? 被定义为与我们在示例 9-6 中定义的处理 Result 值的 match 表达式以几乎相同的方式工作。如果 Result 的值是一个 OkOk 内部的值将从该表达式返回,程序继续运行。如果值是一个 ErrErr 将从整个函数返回,就好像我们使用了 return 关键字一样,从而将错误值传播给调用代码。

The ? placed after a Result value is defined to work in almost the same way as the match expressions that 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 that the error value gets propagated to the calling code.

示例 9-6 中的 match 表达式所做的和 ? 运算符所做的之间有一个区别:被调用 ? 运算符的错误值会经过 from 函数,该函数定义在标准库的 From 特征中,用于将值从一种类型转换为另一种类型。当 ? 运算符调用 from 函数时,接收到的错误类型会被转换为当前函数返回类型中定义的错误类型。当一个函数返回一个错误类型来代表该函数可能失败的所有方式时,这非常有用,即使各部分可能因为许多不同的原因而失败。

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-7 中的 read_username_from_file 函数,使其返回我们定义的一个名为 OurError 的自定义错误类型。如果我们还定义了 impl From<io::Error> for OurError 以从 io::Error 构造 OurError 实例,那么 read_username_from_file 体内的 ? 运算符调用将调用 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 的上下文中,File::open 调用末尾的 ? 将把 Ok 内部的值返回给变量 username_file。如果发生错误,? 运算符将从整个函数提前返回,并将任何 Err 值交给调用代码。同样的事情也适用于 read_to_string 调用末尾的 ?

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-8 所示。

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.

#![allow(unused)]
fn main() {
{{#include ../listings/ch09-error-handling/listing-09-08/src/main.rs:here}}
}

我们将 username 中新 String 的创建移动到了函数的开头;这部分没有改变。我们没有创建变量 username_file,而是将 read_to_string 的调用直接链到了 File::open("hello.txt")? 的结果上。我们在 read_to_string 调用的末尾仍然有一个 ?,当 File::openread_to_string 都成功时,我们仍然返回一个包含 usernameOk 值,而不是返回错误。其功能再次与示例 9-6 和示例 9-7 相同;这只是一种不同的、更符合人体工程学的编写方式。

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.

示例 9-9 展示了一种使用 fs::read_to_string 使其变得更短的方法。

Listing 9-9 shows a way to make this even shorter using fs::read_to_string.

#![allow(unused)]
fn main() {
{{#include ../listings/ch09-error-handling/listing-09-09/src/main.rs:here}}
}

将文件读入字符串是一个相当常见的操作,因此标准库提供了方便的 fs::read_to_string 函数,它可以打开文件、创建一个新 String、读取文件内容、将内容放入该 String 并返回它。当然,使用 fs::read_to_string 并没有给我们提供解释所有错误处理的机会,所以我们先用了较长的方法。

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.

可以在哪里使用 ? 运算符 (Where to Use the ? Operator)

Where to Use the ? Operator

? 运算符只能在返回类型与 ? 所使用的值兼容的函数中使用。这是因为 ? 运算符被定义为执行从函数中提前返回值的操作,其方式与我们在示例 9-6 中定义的 match 表达式相同。在示例 9-6 中,match 正在使用一个 Result 值,提前返回分支返回了一个 Err(e) 值。函数的返回类型必须是一个 Result,这样它才与此 return 兼容。

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-10 中,让我们看看如果在返回类型与我们使用 ? 的值类型不兼容的 main 函数中使用 ? 运算符,我们会得到什么错误。

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.

{{#rustdoc_include ../listings/ch09-error-handling/listing-09-10/src/main.rs}}

这段代码打开一个文件,这可能会失败。? 运算符跟在 File::open 返回的 Result 值后面,但这个 main 函数的返回类型是 (),而不是 Result。当我们编译这段代码时,会得到以下错误消息:

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:

{{#include ../listings/ch09-error-handling/listing-09-10/output.txt}}

该错误指出我们只被允许在返回 ResultOption 或另一个实现了 FromResidual 的类型的函数中使用 ? 运算符。

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.

要修复该错误,你有两个选择。一个选择是更改函数的返回类型,使其与你使用 ? 运算符的值兼容,前提是你没有任何限制阻止这样做。另一个选择是使用 matchResult<T, E> 的方法之一,以任何合适的方式处理 Result<T, E>

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.

错误消息还提到 ? 也可以用于 Option<T> 值。与在 Result 上使用 ? 一样,你只能在返回 Option 的函数中对 Option 使用 ?。在 Option<T> 上调用 ? 运算符时的行为与其在 Result<T, E> 上调用时的行为类似:如果值是 None,则 None 将在此时从函数中提前返回。如果值是 Some,则 Some 内部的值就是表达式的结果值,函数继续执行。示例 9-11 有一个寻找给定文本第一行最后一个字符的函数。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/listing-09-11/src/main.rs:here}}
}

该函数返回 Option<char>,因为那里可能有一个字符,但也可能没有。这段代码接收 text 字符串切片参数并对其调用 lines 方法,该方法返回字符串中各行的迭代器。因为此函数想要检查第一行,所以它对迭代器调用 next 以获取迭代器的第一个值。如果 text 是空字符串,此次 next 调用将返回 None,在这种情况下我们使用 ? 停止并从 last_char_of_first_line 返回 None。如果 text 不是空字符串,next 将返回一个包含 text 第一行字符串切片的 Some 值。

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.

? 提取出了字符串切片,我们可以对该字符串切片调用 chars 来获得其字符的迭代器。我们对这第一行的最后一个字符感兴趣,所以我们调用 last 来返回迭代器中的最后一项。这是一个 Option,因为第一行可能是空字符串;例如,如果 text 以空行开头但在其他行有字符,如 "\nhi"。然而,如果第一行有最后一个字符,它将在 Some 变体中返回。中间的 ? 运算符为我们提供了一种简洁的方式来表达此逻辑,允许我们在单行内实现该函数。如果我们不能对 Option 使用 ? 运算符,我们将不得不使用更多的方法调用或 match 表达式来实现此逻辑。

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.

注意,你可以在返回 Result 的函数中对 Result 使用 ? 运算符,也可以在返回 Option 的函数中对 Option 使用 ? 运算符,但不能混用。? 运算符不会自动将 Result 转换为 Option 或反之;在这些情况下,你可以使用 Result 上的 ok 方法或 Option 上的 ok_or 方法显式执行转换。

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.

到目前为止,我们使用的所有 main 函数都返回 ()main 函数很特殊,因为它是可执行程序的入口点和出口点,为了使程序的行为符合预期,对其返回类型有一定的限制。

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 也可以返回 Result<(), E>。示例 9-12 包含了来自示例 9-10 的代码,但我们已将 main 的返回类型更改为 Result<(), Box<dyn Error>> 并在末尾添加了返回值 Ok(())。这段代码现在可以编译了。

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.

{{#rustdoc_include ../listings/ch09-error-handling/listing-09-12/src/main.rs}}

Box<dyn Error> 类型是一个特征对象,我们将在第 18 章的“使用特征对象实现不同类型间的抽象行为”中讨论。目前,你可以将 Box<dyn Error> 理解为“任何类型的错误”。在返回类型为 Box<dyn Error>main 函数中对 Result 值使用 ? 是被允许的,因为它允许任何 Err 值被提前返回。尽管此 main 函数的主体只会返回 std::io::Error 类型的错误,但通过指定 Box<dyn Error>,即使向 main 主体添加了更多返回其他错误的代码,此签名也将继续保持正确。

The Box<dyn Error> type is a trait object, which we’ll talk about in “Using Trait Objects to Abstract over Shared Behavior” in Chapter 18. 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.

main 函数返回 Result<(), E> 时,如果 main 返回 Ok(()),可执行文件将以 0 值退出;如果 main 返回 Err 值,可执行文件将以非零值退出。用 C 编写的可执行文件在退出时返回整数:成功退出的程序返回整数 0,报错的程序返回某些非 0 的整数。Rust 也从可执行文件返回整数以兼容此惯例。

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 函数可以返回任何实现了 标准库 std::process::Termination 特征 的类型,该特征包含一个返回 ExitCodereport 函数。关于为自定义类型实现 Termination 特征的更多信息,请查阅标准库文档。

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.

既然我们已经讨论了调用 panic! 或返回 Result 的细节,让我们回到如何决定在哪些情况下使用哪种方式是合适的话题。

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! (To panic! or Not to panic!)


x-i18n: generated_at: “2026-03-01T14:04:03Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: a3f14104d56462a27c3d2b3a0cdb19eb7aaa4176ad1d80b82b0d6d667304d54e source_path: ch09-03-to-panic-or-not-to-panic.md workflow: 16

panic! 还是不要 panic! (To panic! or Not to panic!)

To panic! or Not to panic!

那么,你如何决定什么时候该调用 panic!,什么时候该返回 Result?当代码恐慌时,就无法恢复了。你可以为任何错误情况调用 panic!,无论是否有恢复的可能,但那样你就是在代表调用代码决定该情况是不可恢复的。当你选择返回一个 Result 值时,你就给了调用代码选择的余地。调用代码可以选择尝试以适合其情况的方式进行恢复,也可以决定在这种情况下 Err 值是不可恢复的,因此它可以调用 panic! 并将你的可恢复错误转变为不可恢复的错误。因此,在定义一个可能会失败的函数时,返回 Result 是一个很好的默认选择。

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.

在示例、原型代码和测试等情况下,编写会恐慌的代码而不是返回 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.

示例、原型代码和测试 (Examples, Prototype Code, and Tests)

Examples, Prototype Code, and Tests

当你正在编写一个示例来说明某个概念时,包含健壮的错误处理代码可能会使示例变得不那么清晰。在示例中,人们理解对像 unwrap 这样可能引发恐慌的方法的调用,其意图是作为你希望应用程序处理错误方式的一个占位符,处理方式可以根据你的其余代码正在做的事情而有所不同。

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.

类似地,当你正在开发原型且尚未准备好决定如何处理错误时,unwrapexpect 方法非常方便。它们在你的代码中留下了清晰的标记,以便在你准备好让程序更健壮时使用。

Similarly, the unwrap and expect methods are very handy when you’re prototyping and you’re not yet 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.

如果测试中的某个方法调用失败,你会希望整个测试都失败,即使该方法不是被测试的功能。因为 panic! 是测试被标记为失败的方式,所以调用 unwrapexpect 正是应该发生的事情。

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.

当你拥有比编译器更多信息时 (When You Have More Information Than the Compiler)

When You Have More Information Than the Compiler

当你拥有一些其他逻辑能确保 Result 肯定拥有 Ok 值,但该逻辑不是编译器能理解的东西时,调用 expect 也是合适的。你仍然需要处理一个 Result 值:无论你调用的是什么操作,通常仍有失败的可能性,尽管在你特定的情况下逻辑上是不可能的。如果你可以通过手动检查代码来确保永远不会得到 Err 变体,那么调用 expect 并在参数文本中记录你认为永远不会得到 Err 变体的原因是完全可以接受的。这里有一个例子:

It would also be appropriate to call expect when you have some other logic that ensures that 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 expect and document the reason you think you’ll never have an Err variant in the argument text. Here’s an example:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs:here}}
}

我们正在通过解析一个硬编码字符串来创建一个 IpAddr 实例。我们可以看到 127.0.0.1 是一个有效的 IP 地址,因此在这里使用 expect 是可以接受的。然而,拥有一个硬编码的、有效的字符串并不会改变 parse 方法的返回类型:我们仍然得到一个 Result 值,并且编译器仍然会要求我们像 Err 变体可能存在一样处理 Result,因为编译器不够聪明,无法看出这个字符串始终是一个有效的 IP 地址。如果 IP 地址字符串来自用户而不是硬编码在程序中,因此“确实”有失败的可能性,我们肯定会希望以一种更健壮的方式来处理 Result。提到这个 IP 地址是硬编码的假设,将促使我们在将来如果需要从其他来源获取 IP 地址时,将 expect 更改为更好的错误处理代码。

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.

错误处理指南 (Guidelines for Error Handling)

Guidelines for Error Handling

建议在你的代码可能最终陷入糟糕状态时,让代码引发恐慌。在这种语境下,“糟糕状态 (bad state)”是指某些假设、保证、合同或不变式被破坏的情况,例如当无效值、矛盾值或缺失值被传递给你的代码时——加上以下一种或多种情况:

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:

  • 糟糕状态是某种意料之外的事情,而不是像用户以错误格式输入数据这样可能偶尔发生的事情。

  • 在此之后,你的代码需要依赖于“不”处于这种糟糕状态,而不是在每一步都检查问题。

  • 在你使用的类型中没有好的方式来编码这些信息。我们将在第 18 章的“将状态和行为编码为类型”中演示我们的意思。

  • 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 “Encoding States and Behavior as Types” in Chapter 18.

如果有人调用你的代码并传入了不合理的值,如果可以的话,最好返回一个错误,以便库的使用者可以在那种情况下决定他们想做什么。然而,在继续运行可能不安全或有害的情况下,最好的选择可能是调用 panic! 并提醒使用你的库的人他们的代码中存在 bug,以便他们在开发期间修复它。同样,如果你正在调用不受你控制的外部代码,并且它返回了一个你无法修复的无效状态,那么 panic! 通常是合适的。

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 that 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 that they can fix it during development. Similarly, panic! is often appropriate if you’re calling external code that is out of your control and returns an invalid state that you have no way of fixing.

然而,当失败是预期之中的,返回一个 Result 比调用 panic! 更合适。例子包括解析器被给定了格式错误的数据,或者 HTTP 请求返回了一个指示你已达到速率限制的状态。在这些情况下,返回一个 Result 表明失败是一个预期的可能性,调用代码必须决定如何处理。

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.

当你的代码执行一个如果使用无效值调用可能会让用户面临风险的操作时,你的代码应该首先验证这些值是否有效,如果无效则引发恐慌。这主要是出于安全原因:尝试操作无效数据可能会使你的代码暴露在漏洞之下。这是标准库在你尝试越界内存访问时会调用 panic! 的主要原因:尝试访问不属于当前数据结构的内存是一个常见的安全问题。函数通常有“合同 (contracts)”:只有在输入满足特定要求时,它们的行为才能得到保证。在违反合同时引发恐慌是有道理的,因为违反合同总是意味着调用方存在 bug,而且这不是你希望调用代码必须显式处理的那种错误。事实上,调用代码没有合理的恢复方式;调用方的“程序员”需要修复代码。函数的合同,特别是违反合同时会引起恐慌的情况,应该在函数的 API 文档中解释。

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.

然而,在所有函数中进行大量的错误检查会很冗长且令人厌烦。幸运的是,你可以使用 Rust 的类型系统(以及编译器进行的类型检查)来为你完成许多检查。如果你的函数有一个特定类型作为参数,你可以继续编写代码逻辑,因为知道编译器已经确保了你拥有一个有效值。例如,如果你有一个类型而不是 Option,那么你的程序期望得到“某个东西”而不是“无”。这样你的代码就不必处理 SomeNone 变体的两种情况:它只会有一种肯定拥有值的情况。尝试向你的函数传递“无”的代码甚至无法通过编译,因此你的函数不必在运行时检查该情况。另一个例子是使用无符号整数类型(如 u32),这确保了参数永远不会是负数。

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 that 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 that the parameter is never negative.

用于验证的自定义类型 (Custom Types for Validation)

Custom Types for Validation

让我们更进一步,利用 Rust 类型系统确保我们拥有一个有效值的想法,并看看如何创建一个用于验证的自定义类型。回想一下第 2 章中的猜谜游戏,我们的代码要求用户猜一个 1 到 100 之间的数字。在将其与我们的秘密数字进行核对之前,我们从未验证用户的猜测是否在这些数字之间;我们只验证了猜测是正数。在这种情况下,后果并不是非常严重:我们输出的“太高”或“太低”仍然是正确的。但是,引导用户进行有效的猜测,并在用户猜出一个超出范围的数字与用户键入(例如)字母时产生不同的行为,将是一个有用的增强。

Let’s take the idea of using Rust’s type system to ensure that 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.

一种方法是将猜测解析为 i32 而不仅仅是 u32 以允许潜在的负数,然后添加一个检查数字是否在范围内的判断,如下所示:

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:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs:here}}

if 表达式检查我们的值是否超出范围,将问题告知用户,并调用 continue 开始循环的下一次迭代并请求另一个猜测。在 if 表达式之后,我们可以继续进行 guess 和秘密数字之间的比较,因为知道 guess 在 1 到 100 之间。

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.

然而,这并不是一个理想的解决方案:如果程序只在 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).

相反,我们可以建立一个新类型并在一个专门的模块中将验证放在一个函数中以创建该类型的实例,而不是到处重复验证。这样,函数在签名中使用新类型并放心地使用它们接收到的值就是安全的。示例 9-13 展示了定义 Guess 类型的一种方法,只有当 new 函数接收到 1 到 100 之间的值时,它才会创建一个 Guess 实例。

Instead, we can make a new type in a dedicated module 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/listing-09-13/src/guessing_game.rs}}
}

注意 src/guessing_game.rs 中的这段代码依赖于在 src/lib.rs 中添加一个模块声明 mod guessing_game;,我们在这里没有展示。在这个新模块的文件中,我们定义了一个名为 Guess 的结构体,它有一个名为 value 的字段,持有一个 i32。这就是存储数字的地方。

Note that this code in src/guessing_game.rs depends on adding a module declaration mod guessing_game; in src/lib.rs that we haven’t shown here. Within this new module’s file, 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 上实现了一个名为 new 的关联函数,用于创建 Guess 值的实例。new 函数被定义为具有一个名为 valuei32 类型的参数,并返回一个 Guessnew 函数体内的代码测试 value 以确保其在 1 到 100 之间。如果 value 未通过此测试,我们发起一个 panic! 调用,这将提醒编写调用代码的程序员他们有一个需要修复的 bug,因为创建一个 value 在此范围之外的 Guess 会违反 Guess::new 所依赖的合同。Guess::new 可能发生恐慌的条件应该在其面向公众的 API 文档中讨论;我们将在第 14 章介绍 API 文档中指示 panic! 可能性的文档惯例。如果 value 确实通过了测试,我们创建一个新的 Guess,其 value 字段设置为 value 参数的值,并返回该 Guess

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.

接下来,我们实现一个名为 value 的方法,它借用 self,没有其他参数,并返回一个 i32。这种方法有时被称为 getter,因为它的目的是从字段中获取某些数据并返回它。这个公有方法是必要的,因为 Guess 结构体的 value 字段是私有的。value 字段必须是私有的,这一点很重要,这样使用 Guess 结构体的代码就不被允许直接设置 valueguessing_game 模块之外的代码“必须”使用 Guess::new 函数来创建一个 Guess 实例,从而确保没有办法让 Guess 拥有一个未经 Guess::new 函数中条件检查的 value

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 that code using the Guess struct is not allowed to set value directly: Code outside the guessing_game module must use the Guess::new function to create an instance of Guess, thereby ensuring that there’s no way for a Guess to have a value that hasn’t been checked by the conditions in the Guess::new function.

具有参数或仅返回 1 到 100 之间数字的函数,随后可以在其签名中声明它接收或返回的是一个 Guess 而不是一个 i32,并且在其主体中不需要进行任何额外的检查。

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.

总结 (Summary)

Summary

Rust 的错误处理功能旨在帮助你编写更健壮的代码。panic! 宏发出信号,表明你的程序处于它无法处理的状态,并允许你告诉进程停止运行,而不是尝试继续使用无效或不正确的值。Result 枚举利用 Rust 的类型系统来指示操作可能会以你的代码可以恢复的方式失败。你可以使用 Result 来告诉调用你代码的代码,它也需要处理潜在的成功或失败。在适当的情况下使用 panic!Result 将使你的代码在面对不可避免的问题时更加可靠。

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.

既然你已经看到了标准库在 OptionResult 枚举中使用泛型的有用方式,我们将讨论泛型是如何工作的,以及你如何在代码中使用它们。

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.

泛型、Traits 和生命周期 (Generic Types, Traits, and Lifetimes)


x-i18n: generated_at: “2026-03-01T14:04:40Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: d020e896ebc0b986fcddcbab0511462ebb9e4ca4b6ebdb456b2993041f2614af source_path: ch10-00-generics.md workflow: 16

泛型、特征与生命周期 (Generic Types, Traits, and Lifetimes)

Generic Types, Traits, and Lifetimes

每种编程语言都有能有效处理重复概念的工具。在 Rust 中,这种工具之一就是“泛型 (generics)”:它是具体类型或其他属性的抽象替身。我们可以表达泛型的行为或它们与其他泛型之间的关系,而无需在编译和运行代码时知道它们的具体内容。

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.

函数可以接收某种泛型类型的参数,而不是像 i32String 这样的具体类型,这就像它们接收具有未知值的参数以便在多个具体值上运行相同的代码一样。事实上,我们已经在第 6 章的 Option<T>、第 8 章的 Vec<T>HashMap<K, V>,以及第 9 章的 Result<T, E> 中使用过泛型了。在本章中,你将探索如何使用泛型定义自己的类型、函数和方法!

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 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!

首先,我们将回顾如何通过提取函数来减少代码重复。然后,我们将使用相同的技术,从两个仅在参数类型上有所不同的函数中创建一个泛型函数。我们还将解释如何在结构体和枚举定义中使用泛型类型。

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.

接着,你将学习如何使用“特征 (traits)”以泛型的方式定义行为。你可以将特征与泛型类型结合使用,以约束泛型类型仅接受那些具有特定行为的类型,而不仅仅是任何类型。

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.

最后,我们将讨论“生命周期 (lifetimes)”:这是一种特殊的泛型,它为编译器提供有关引用如何相互关联的信息。生命周期允许我们向编译器提供有关借用值的足够信息,以便它能在更多的情况下确保引用是有效的,而这在没有我们帮助的情况下它是做不到的。

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 that references will be valid in more situations than it could without our help.

通过提取函数消除重复 (Removing Duplication by Extracting a Function)

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.

我们将从示例 10-1 中的简短程序开始,该程序寻找列表中的最大数字。

We’ll begin with the short program in Listing 10-1 that finds the largest number in a list.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs:here}}
}

我们在变量 number_list 中存储一个整数列表,并将该列表中第一个数字的引用放在名为 largest 的变量中。然后我们遍历列表中的所有数字,如果当前数字大于存储在 largest 中的数字,我们就替换该变量中的引用。然而,如果当前数字小于或等于目前看到的最大数字,变量就不会改变,代码继续处理列表中的下一个数字。在考虑了列表中的所有数字后,largest 应该引用最大的数字,在此例中为 100。

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.

现在我们的任务是寻找两个不同数字列表中的最大数字。为此,我们可以选择复制示例 10-1 中的代码,并在程序的两个不同地方使用相同的逻辑,如示例 10-2 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs}}
}

虽然这段代码可以工作,但复制代码是乏味且容易出错的。当我们想要更改代码时,我们还必须记得在多个地方更新它。

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 as a parameter. This solution makes our code clearer and lets us express the concept of finding the largest number in a list abstractly.

在示例 10-3 中,我们将寻找最大数字的代码提取到一个名为 largest 的函数中。然后,我们调用该函数来寻找示例 10-2 中两个列表中的最大数字。我们也可以在将来可能拥有的任何其他 i32 值列表上使用该函数。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs:here}}
}

largest 函数有一个名为 list 的参数,它代表我们可能传递给函数的任何具体的 i32 值切片。因此,当我们调用该函数时,代码会在我们传入的具体值上运行。

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.

总而言之,以下是我们将代码从示例 10-2 更改为示例 10-3 所采取的步骤:

In summary, here are the steps we took to change the code from Listing 10-2 to Listing 10-3:

  1. 识别重复代码。

  2. 将重复代码提取到函数体中,并在函数签名中指定该代码的输入和返回值。

  3. 更新重复代码的两个实例以改为调用该函数。

  4. Identify duplicate code.

  5. Extract the duplicate code into the body of the function, and specify the inputs and return values of that code in the function signature.

  6. Update the two instances of duplicated code to call the function instead.

接下来,我们将使用同样的步骤配合泛型来减少代码重复。就像函数体可以在抽象的 list 上而不是具体的值上操作一样,泛型允许代码在抽象类型上操作。

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.

例如,假设我们有两个函数:一个寻找 i32 值切片中的最大项,另一个寻找 char 值切片中的最大项。我们该如何消除这种重复呢?让我们一探究竟!

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!

泛型数据类型 (Generic Data Types)


x-i18n: generated_at: “2026-03-01T14:06:00Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: c88e9d9404ce16c820b4f4f84af73f40b4eb4978020dc3a1cead90ba0ac2569a source_path: ch10-01-syntax.md workflow: 16

泛型数据类型 (Generic Data Types)

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)

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.

继续我们的 largest 函数,示例 10-4 展示了两个函数,它们都寻找切片中的最大值。然后我们将这些函数合并为一个使用泛型的单一函数。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs:here}}
}

largest_i32 函数是我们在示例 10-3 中提取的,用于寻找切片中的最大 i32largest_char 函数寻找切片中的最大 char。函数体具有相同的代码,所以让我们通过在单个函数中引入一个泛型类型参数来消除重复。

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.

要在新的单一函数中对类型进行参数化,我们需要为类型参数命名,就像我们为函数的数值参数命名一样。你可以使用任何标识符作为类型参数名称。但我们将使用 T,因为按照惯例,Rust 中的类型参数名称很短,通常只有一个字母,而且 Rust 的类型命名约定是 UpperCamelCase。作为 type 的缩写,T 是大多数 Rust 程序员的默认选择。

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.

当我们在函数体中使用参数时,我们必须在签名中声明该参数名,以便编译器知道该名称的含义。同样,当我们在函数签名中使用类型参数名时,我们必须在使用它之前声明该类型参数名。为了定义泛型 largest 函数,我们将类型名声明放在尖括号 <> 内,放在函数名和参数列表之间,如下所示:

When we use a parameter in the body of the function, we have to declare the parameter name in the signature so that 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:

fn largest<T>(list: &[T]) -> &T {

我们将此定义读作:“函数 largest 在某种类型 T 上是泛型的。”该函数有一个名为 list 的参数,它是一个 T 类型值的切片。largest 函数将返回一个指向相同类型 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.

示例 10-5 展示了在签名中使用泛型数据类型的合并后的 largest 函数定义。该示例还展示了我们如何使用 i32 值切片或 char 值切片来调用该函数。请注意,这段代码目前还无法编译。

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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs}}

如果我们现在编译这段代码,我们会得到这个错误:

If we compile this code right now, we’ll get this error:

{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt}}

帮助文本提到了 std::cmp::PartialOrd,这是一个“特征 (trait)”,我们将在下一节讨论特征。目前,只需知道此错误指出 largest 的主体并不适用于 T 可能具有的所有类型。因为我们想在主体中比较 T 类型的值,所以我们只能使用其值可以排序的类型。为了启用比较,标准库提供了 std::cmp::PartialOrd 特征,你可以在类型上实现该特征(有关此特征的更多信息,请参阅附录 C)。要修复示例 10-5,我们可以遵循帮助文本的建议,将对 T 有效的类型限制为仅那些实现了 PartialOrd 的类型。这样示例就可以编译了,因为标准库在 i32char 上都实现了 PartialOrd

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). To fix Listing 10-5, we can follow the help text’s suggestion and restrict the types valid for T to only those that implement PartialOrd. The listing will then compile, because the standard library implements PartialOrd on both i32 and char.

在结构体定义中 (In Struct Definitions)

In Struct Definitions

我们也可以使用 <> 语法定义结构体,以便在一个或多个字段中使用泛型类型参数。示例 10-6 定义了一个 Point<T> 结构体,用于持有任何类型的 xy 坐标值。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs}}
}

在结构体定义中使用泛型的语法与函数定义中使用的语法类似。首先,我们在紧跟结构体名称后的尖括号内声明类型参数的名称。然后,我们在通常指定具体数据类型的结构体定义中使用该泛型类型。

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.

请注意,因为我们只使用了一种泛型类型来定义 Point<T>,所以这个定义说明 Point<T> 结构体在某种类型 T 上是泛型的,并且字段 xy “都是”该相同类型,无论该类型是什么。如果我们创建一个具有不同类型值的 Point<T> 实例,如示例 10-7 所示,我们的代码将无法编译。

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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs}}

在这个例子中,当我们把整数值 5 分配给 x 时,我们让编译器知道对于 Point<T> 的这个实例,泛型类型 T 将是一个整数。然后,当我们为 y 指定 4.0 时(我们已将其定义为与 x 具有相同的类型),我们将得到一个如下所示的类型不匹配错误:

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:

{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt}}

要定义一个 xy 都是泛型但可以具有不同类型的 Point 结构体,我们可以使用多个泛型类型参数。例如,在示例 10-8 中,我们将 Point 的定义更改为在类型 TU 上是泛型的,其中 x 的类型为 Ty 的类型为 U

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs}}
}

现在显示的所有 Point 实例都是允许的!你可以在定义中使用任意数量的泛型类型参数,但使用超过几个会使你的代码难以阅读。如果你发现代码中需要大量的泛型类型,这可能表明你的代码需要重构成更小的部分。

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.

在枚举定义中 (In Enum Definitions)

In Enum Definitions

就像我们对结构体所做的那样,我们可以定义枚举以便在其变体中持有泛型数据类型。让我们再看看我们在第 6 章中使用的标准库提供的 Option<T> 枚举:

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:

#![allow(unused)]
fn main() {
enum Option<T> {
    Some(T),
    None,
}
}

现在这个定义对你来说应该更有意义了。如你所见,Option<T> 枚举在类型 T 上是泛型的,具有两个变体:Some(持有一个 T 类型的值)和不持有任何值的 None 变体。通过使用 Option<T> 枚举,我们可以表达可选值这一抽象概念,并且由于 Option<T> 是泛型的,无论可选值的类型是什么,我们都可以使用这种抽象。

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.

枚举也可以使用多种泛型类型。我们在第 9 章中使用的 Result 枚举的定义就是一个例子:

Enums can use multiple generic types as well. The definition of the Result enum that we used in Chapter 9 is one example:

#![allow(unused)]
fn main() {
enum Result<T, E> {
    Ok(T),
    Err(E),
}
}

Result 枚举在两种类型 TE 上是泛型的,具有两个变体:Ok(持有 T 类型的值)和 Err(持有 E 类型的值)。这个定义使得在任何操作可能成功(返回某种类型 T 的值)或失败(返回某种类型 E 的错误)的地方,使用 Result 枚举都很方便。事实上,这就是我们在示例 9-3 中用于打开文件的内容,其中当文件成功打开时,T 被填充为类型 std::fs::File;当打开文件出现问题时,E 被填充为类型 std::io::Error

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.

当你发现代码中存在多个仅在所持有值的类型上有所不同的结构体或枚举定义时,你可以通过使用泛型类型来避免重复。

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)

In Method Definitions

我们可以在结构体和枚举上实现方法(正如我们在第 5 章中所做的),并且也可以在它们的定义中使用泛型类型。示例 10-9 展示了我们在示例 10-6 中定义的 Point<T> 结构体,并在其上实现了一个名为 x 的方法。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs}}
}

在这里,我们在 Point<T> 上定义了一个名为 x 的方法,它返回一个指向字段 x 中数据的引用。

Here, we’ve defined a method named x on Point<T> that returns a reference to the data in the field x.

请注意,我们必须在 impl 之后立即声明 T,以便我们可以使用 T 来指定我们是在类型 Point<T> 上实现方法。通过在 impl 之后将 T 声明为泛型类型,Rust 可以识别出 Point 尖括号内的类型是一个泛型类型,而不是一个具体类型。我们可以为这个泛型参数选择一个与结构体定义中声明的泛型参数不同的名称,但使用相同的名称是惯例。如果你在一个声明了泛型类型的 impl 块中编写方法,该方法将在该类型的任何实例上定义,而不管最终替代泛型类型的是哪种具体类型。

Note that we have to declare T just after impl so that 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. If you write a method within an impl that declares a generic type, that method will be defined on any instance of the type, no matter what concrete type ends up substituting for the generic type.

我们也可以在为类型定义方法时指定对泛型类型的约束。例如,我们可以仅在 Point<f32> 实例上实现方法,而不是在具有任何泛型类型的 Point<T> 实例上实现。在示例 10-10 中,我们使用了具体类型 f32,这意味着我们不在 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs:here}}
}

这段代码意味着类型 Point<f32> 将拥有一个 distance_from_origin 方法;而 T 不是 f32 类型的其他 Point<T> 实例将不会定义此方法。该方法测量我们的点与坐标 (0.0, 0.0) 处的点之间的距离,并使用了仅对浮点类型可用的数学运算。

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.

结构体定义中的泛型类型参数并不总是与你在该相同结构体的方法签名中使用的参数相同。示例 10-11 为 Point 结构体使用了泛型类型 X1Y1,并为 mixup 方法签名使用了 X2Y2,以使示例更清晰。该方法创建一个新的 Point 实例,其 x 值来自 selfPoint(类型为 X1),而 y 值来自传入的 Point(类型为 Y2)。

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 and 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).

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs}}
}

main 中,我们定义了一个 Point,其 xi32(值为 5),yf64(值为 10.4)。变量 p2 是一个 Point 结构体,其 x 为字符串切片(值为 "Hello"),ychar(值为 c)。在 p1 上调用 mixup 并传入参数 p2 得到了 p3,它将拥有一个 i32 类型的 x,因为 x 来自 p1。变量 p3 将拥有一个 char 类型的 y,因为 y 来自 p2println! 宏调用将打印 p3.x = 5, p3.y = c

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.

这个例子的目的是演示一种情况,其中一些泛型参数是在 impl 处声明的,而另一些是在方法定义处声明的。在这里,泛型参数 X1Y1impl 之后声明,因为它们与结构体定义相对应。泛型参数 X2Y2fn mixup 之后声明,因为它们仅与该方法相关。

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.

使用泛型的代码的性能 (Performance of Code Using Generics)

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 通过在编译时对使用泛型的代码执行单态化来实现这一点。“单态化 (Monomorphization)”是通过填充编译时使用的具体类型来将泛型代码转换为特定代码的过程。在此过程中,编译器执行的操作与我们在示例 10-5 中创建泛型函数所采取的步骤相反:编译器查找所有调用泛型代码的地方,并为调用泛型代码时使用的具体类型生成代码。

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.

让我们通过使用标准库的泛型 Option<T> 枚举来看看这是如何工作的:

Let’s look at how this works by using the standard library’s generic Option<T> enum:

#![allow(unused)]
fn main() {
let integer = Some(5);
let float = Some(5.0);
}

当 Rust 编译这段代码时,它会执行单态化。在此过程中,编译器读取已在 Option<T> 实例中使用的值,并识别出两种 Option<T>:一种是 i32,另一种是 f64。因此,它将 Option<T> 的泛型定义展开为针对 i32f64 特化的两个定义,从而用特定的定义替换泛型定义。

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.

代码的单态化版本看起来类似于以下内容(为了说明,编译器使用了与我们这里使用的不同的名称):

The monomorphized version of the code looks similar to the following (the compiler uses different names than what we’re using here for illustration):

文件名: 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);
}

泛型 Option<T> 被编译器创建的特定定义所取代。因为 Rust 将泛型代码编译为在每个实例中指定类型的代码,所以我们不需要为使用泛型支付任何运行时开销。当代码运行时,它的表现就像我们手工复制了每个定义一样。单态化的过程使得 Rust 的泛型在运行时极其高效。

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.

使用 Traits 定义共享行为 (Defining Shared Behavior with Traits)


x-i18n: generated_at: “2026-03-01T14:07:14Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 705ae11758c687175e47104a302a9b5f694d04d683bffc28dcc61ffe9a0dc80e source_path: ch10-02-traits.md workflow: 16

使用特征定义共享行为 (Defining Shared Behavior with Traits)

Defining Shared Behavior with Traits

“特征 (trait)” 定义了特定类型具有并可以与其他类型共享的功能。我们可以使用特征以抽象的方式定义共享行为。我们可以使用“特征约束 (trait bounds)”来指定泛型类型可以是任何具有某些行为的类型。

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.

注意:特征类似于其他语言中通常称为“接口 (interfaces)”的功能,尽管有一些区别。

Note: Traits are similar to a feature often called interfaces in other languages, although with some differences.

定义特征 (Defining a Trait)

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.

例如,假设我们有多个持有各种种类和数量文本的结构体:一个持有在特定地点提交的新闻报道的 NewsArticle 结构体,以及一个最多可包含 280 个字符的 SocialPost,连同指示它是新发布、转发还是对另一发布的回复的元数据。

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 SocialPost that can have, at most, 280 characters along with metadata that indicates whether it was a new post, a repost, or a reply to another post.

我们想制作一个名为 aggregator 的媒体聚合库 crate,它可以显示可能存储在 NewsArticleSocialPost 实例中的数据摘要。为此,我们需要每个类型的摘要,我们将通过在实例上调用 summarize 方法来请求该摘要。示例 10-12 展示了表达这种行为的公共 Summary 特征的定义。

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 SocialPost 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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs}}

在这里,我们使用 trait 关键字声明一个特征,然后是特征的名称,在此例中为 Summary。我们还将该特征声明为 pub,以便依赖此 crate 的 crate 也可以使用此特征,正如我们将在几个示例中看到的那样。在花括号内,我们声明了方法签名,这些签名描述了实现此特征的类型的行为,在此例中是 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.

在方法签名之后,我们不是在花括号内提供实现,而是使用分号。每个实现此特征的类型必须为方法体提供自己的自定义行为。编译器将强制要求任何具有 Summary 特征的类型都必须精确地定义具有此签名的方法 summarize

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.

一个特征在其主体中可以有多个方法:方法签名每行罗列一个,且每行以分号结尾。

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)

既然我们已经定义了 Summary 特征所需的方法签名,我们就可以在媒体聚合器中的类型上实现它。示例 10-13 展示了在 NewsArticle 结构体上实现 Summary 特征,它使用标题、作者和地点来创建 summarize 的返回值。对于 SocialPost 结构体,我们将 summarize 定义为用户名后跟帖子的全部文本,假设帖子内容已被限制在 280 个字符以内。

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 SocialPost struct, we define summarize as the username followed by the entire text of the post, assuming that the post content is already limited to 280 characters.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs:here}}

在类型上实现特征与实现常规方法类似。区别在于在 impl 之后,我们放入想要实现的特征名称,然后使用 for 关键字,接着指定我们想要为其实现特征的类型的名称。在 impl 块内,我们放入特征定义中定义的方法签名。我们不是在每个签名后添加分号,而是使用花括号,并在其中填充特征的方法针对该特定类型所应具有的具体行为。

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.

现在库已经在 NewsArticleSocialPost 上实现了 Summary 特征,crate 的使用者可以像我们调用常规方法一样,在 NewsArticleSocialPost 的实例上调用特征方法。唯一的区别是使用者必须将特征以及类型都引入作用域。这里有一个二进制 crate 如何使用我们的 aggregator 库 crate 的例子:

Now that the library has implemented the Summary trait on NewsArticle and SocialPost, users of the crate can call the trait methods on instances of NewsArticle and SocialPost 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:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs}}

这段代码会打印 1 new post: horse_ebooks: of course, as you probably already know, people

This code prints 1 new post: horse_ebooks: of course, as you probably already know, people.

依赖 aggregator crate 的其他 crate 也可以将 Summary 特征引入作用域,以便在它们自己的类型上实现 Summary。需要注意的一个限制是,只有当特征或类型(或两者)对我们的 crate 是本地的时,我们才能在类型上实现该特征。例如,我们可以将标准库特征(如 Display)实现在自定义类型(如 SocialPost)上,作为我们 aggregator crate 功能的一部分,因为类型 SocialPost 对于我们的 aggregator crate 是本地的。我们也可以在我们的 aggregator crate 中为 Vec<T> 实现 Summary ,因为特征 Summary 对于我们的 aggregator crate 是本地的。

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 SocialPost as part of our aggregator crate functionality because the type SocialPost 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 中为 Vec<T> 实现 Display 特征,因为 DisplayVec<T> 都定义在标准库中,且对我们的 aggregator crate 不是本地的。此限制是被称为“相干性 (coherence)”属性的一部分,更具体地说是“孤儿规则 (orphan rule)”,之所以这样命名是因为父类型不存在。此规则确保他人的代码不会破坏你的代码,反之亦然。如果没有这条规则,两个 crate 可能会为同一个类型实现相同的特征,而 Rust 将不知道该使用哪个实现。

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.

使用默认实现 (Using Default Implementations)

Using 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.

在示例 10-14 中,我们为 Summary 特征的 summarize 方法指定了一个默认字符串,而不是像在示例 10-12 中那样仅定义方法签名。

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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs:here}}

要使用默认实现来对 NewsArticle 实例进行摘要,我们指定一个空的 impl 块:impl Summary for NewsArticle {}

To use a default implementation to summarize instances of NewsArticle, we specify an empty impl block with impl Summary for NewsArticle {}.

尽管我们不再直接在 NewsArticle 上定义 summarize 方法,但我们提供了一个默认实现,并指定了 NewsArticle 实现了 Summary 特征。因此,我们仍然可以在 NewsArticle 实例上调用 summarize 方法,如下所示:

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:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs:here}}

这段代码会打印 New article available! (Read more...)

This code prints New article available! (Read more...).

创建默认实现并不需要我们更改示例 10-13 中 SocialPostSummary 的实现。原因是覆盖默认实现的语法与实现没有默认实现的特征方法的语法相同。

Creating a default implementation doesn’t require us to change anything about the implementation of Summary on SocialPost 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.

默认实现可以调用同一特征中的其他方法,即使那些其他方法没有默认实现。通过这种方式,特征可以提供许多有用的功能,并且只要求实现者指定其中的一小部分。例如,我们可以将 Summary 特征定义为具有一个必须实现的 summarize_author 方法,然后定义一个具有调用 summarize_author 方法的默认实现的 summarize 方法:

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:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs:here}}

要使用这个版本的 Summary ,我们只需要在为类型实现特征时定义 summarize_author

To use this version of Summary, we only need to define summarize_author when we implement the trait on a type:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs:impl}}

在我们定义了 summarize_author 之后,我们就可以在 SocialPost 结构体的实例上调用 summarize,并且 summarize 的默认实现将调用我们提供的 summarize_author 定义。因为我们实现了 summarize_authorSummary 特征就给了我们 summarize 方法的行为,而不需要我们再编写任何代码。它看起来是这样的:

After we define summarize_author, we can call summarize on instances of the SocialPost 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:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs:here}}

这段代码会打印 1 new post: (Read more from @horse_ebooks...)

This code prints 1 new post: (Read more from @horse_ebooks...).

请注意,无法从同一方法的覆盖实现中调用默认实现。

Note that it isn’t possible to call the default implementation from an overriding implementation of that same method.

特征作为参数 (Using Traits as Parameters)

Using Traits as Parameters

既然你知道了如何定义和实现特征,我们可以探索如何使用特征来定义接受许多不同类型的函数。我们将使用在示例 10-13 中为 NewsArticleSocialPost 类型实现的 Summary 特征,来定义一个 notify 函数,该函数对其 item 参数调用 summarize 方法,该参数属于实现了 Summary 特征的某种类型。为此,我们使用 impl Trait 语法,如下所示:

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 SocialPost 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:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs:here}}

我们不是为 item 参数指定具体类型,而是指定 impl 关键字和特征名称。此参数接受实现了指定特征的任何类型。在 notify 主体内,我们可以对 item 调用任何来自 Summary 特征的方法,例如 summarize。我们可以调用 notify 并传入 NewsArticleSocialPost 的任何实例。使用任何其他类型(例如 Stringi32)调用该函数的代码将无法通过编译,因为这些类型没有实现 Summary

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 SocialPost. 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.

特征约束语法 (Trait Bound Syntax)

Trait Bound Syntax

impl Trait 语法适用于简单情况,但实际上它是被称为“特征约束 (trait bound)”的较长形式的语法糖;它看起来像这样:

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.

impl Trait 语法在简单情况下很方便且能使代码更简洁,而更完整的特征约束语法可以在其他情况下表达更多的复杂性。例如,我们可以有两个实现了 Summary 的参数。使用 impl Trait 语法如下所示:

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:

pub fn notify(item1: &impl Summary, item2: &impl Summary) {

如果我们希望此函数允许 item1item2 具有不同的类型(只要两种类型都实现了 Summary),使用 impl Trait 是合适的。然而,如果我们想强制两个参数具有相同的类型,我们必须使用特征约束,如下所示:

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:

pub fn notify<T: Summary>(item1: &T, item2: &T) {

泛型类型 T 被指定为 item1item2 参数的类型,它约束了该函数,使得作为 item1item2 的实参传入的值的具体类型必须相同。

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.

使用 + 语法指定多个特征约束 (Multiple Trait Bounds with the + Syntax)

Multiple Trait Bounds with the + Syntax

我们也可以指定多个特征约束。假设我们希望 notifyitem 上使用显示格式化以及 summarize:我们在 notify 定义中指定 item 必须同时实现 DisplaySummary。我们可以使用 + 语法来做到这一点:

pub fn notify(item: &(impl Summary + Display)) {

+ 语法也适用于泛型类型的特征约束:

pub fn notify<T: Summary + Display>(item: &T) {

通过指定这两个特征约束,notify 的主体就可以调用 summarize 并使用 {} 来格式化 item

With the two trait bounds specified, the body of notify can call summarize and use {} to format item.

使用 where 子句实现更清晰的特征约束 (Clearer Trait Bounds with where Clauses)

Clearer Trait Bounds with where Clauses

使用过多的特征约束也有其缺点。每个泛型都有其自己的特征约束,因此具有多个泛型类型参数的函数可能在函数名和参数列表之间包含大量的特征约束信息,使得函数签名难以阅读。出于这个原因,Rust 有另一种语法,用于在函数签名之后的 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:

fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {

我们可以使用 where 子句,如下所示:

we can use a where clause, like this:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-where-clause/src/lib.rs:here}}

这个函数的签名不那么拥挤了:函数名、参数列表和返回类型都靠得很近,类似于一个没有大量特征约束的函数。

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)

Returning Types That Implement Traits

我们也可以在返回位置使用 impl Trait 语法来返回实现了某个特征的某种类型的值,如下所示:

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:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs:here}}

通过在返回类型中使用 impl Summary ,我们指定 returns_summarizable 函数返回某种实现了 Summary 特征的类型,而不必指明具体类型。在这种情况下,returns_summarizable 返回一个 SocialPost ,但调用该函数的代码不需要知道这一点。

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 SocialPost, but the code calling this function doesn’t need to know that.

仅通过其实现的特征来指定返回类型的能力,在闭包和迭代器的语境中特别有用,我们将在第 13 章介绍。闭包和迭代器创建了只有编译器知道的类型,或者是指定起来非常长的类型。impl Trait 语法让你能简洁地指定一个函数返回某种实现了 Iterator 特征的类型,而无需写出非常长的类型名称。

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.

然而,只有当你返回单一类型时,才能使用 impl Trait。例如,这段返回 NewsArticleSocialPost 的代码,如果其返回类型被指定为 impl Summary ,将无法工作:

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 SocialPost with the return type specified as impl Summary wouldn’t work:

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs:here}}

由于编译器中关于 impl Trait 语法实现方式的限制,不允许返回 NewsArticleSocialPost。我们将在第 18 章的“使用特征对象实现不同类型间的抽象行为”部分介绍如何编写具有此行为的函数。

Returning either a NewsArticle or a SocialPost 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 to Abstract over Shared Behavior” section of Chapter 18.

使用特征约束有条件地实现方法 (Using Trait Bounds to Conditionally Implement Methods)

Using Trait Bounds to Conditionally Implement Methods

通过在带有泛型类型参数的 impl 块中使用特征约束,我们可以为实现了指定特征的类型有条件地实现方法。例如,示例 10-15 中的 Pair<T> 类型总是实现 new 函数以返回 Pair<T> 的新实例(回想第 5 章“方法语法”部分,Selfimpl 块类型的类型别名,在此例中为 Pair<T>)。但在下一个 impl 块中,Pair<T> 只有在其内部类型 T 实现了支持比较的 PartialOrd 特征“以及”支持打印的 Display 特征时,才会实现 cmp_display 方法。

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 “Method Syntax” 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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/lib.rs}}

我们也可以为实现了另一个特征的任何类型有条件地实现一个特征。对满足特征约束的任何类型实现的特征被称为“覆盖实现 (blanket implementations)”,这在 Rust 标准库中被广泛使用。例如,标准库为任何实现了 Display 特征的类型实现了 ToString 特征。标准库中的 impl 块看起来类似于这段代码:

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:

impl<T: Display> ToString for T {
    // --snip--
}

因为标准库有这种覆盖实现,所以我们可以在任何实现了 Display 特征的类型上调用由 ToString 特征定义的 to_string 方法。例如,我们可以像这样将整数转换为它们对应的 String 值,因为整数实现了 Display

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:

#![allow(unused)]
fn main() {
let s = 3.to_string();
}

覆盖实现出现在特征文档的 “Implementors” 部分。

Blanket implementations appear in the documentation for the trait in the “Implementors” section.

特征和特征约束让我们能编写使用泛型类型参数来减少重复的代码,同时也向编译器指定我们希望泛型类型具有特定的行为。编译器随后可以使用特征约束信息来检查与我们代码一起使用的所有具体类型是否都提供了正确的行为。在动态类型语言中,如果我们对一个没有定义该方法的类型调用方法,我们会在运行时得到一个错误。但 Rust 将这些错误移至编译时,因此我们被迫在代码甚至能够运行之前就修复问题。此外,我们不必编写在运行时检查行为的代码,因为我们已经在编译时检查过了。这样做在提高性能的同时,也不必放弃泛型的灵活性。

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 that didn’t define the method. But Rust moves these errors to compile time so that 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.

使用生命周期验证引用 (Validating References with Lifetimes)


x-i18n: generated_at: “2026-03-01T14:08:28Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 8660fe043e6ca70645f6734f357dc61224ecd4e3454ebde7b696f89d6a0d6e91 source_path: ch10-03-lifetime-syntax.md workflow: 16

使用生命周期验证引用 (Validating References with Lifetimes)

Validating References with Lifetimes

生命周期 (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.

我们在第 4 章“引用与借用”部分未讨论的一个细节是,Rust 中的每个引用都有一个生命周期,即该引用有效的范围。大多数时候,生命周期是隐式且推断出来的,就像大多数时候类型也是推断出来的一样。只有当多种类型可能时,我们才需要标注类型。类似地,当引用的生命周期可能以几种不同的方式相关联时,我们必须标注生命周期。Rust 要求我们使用泛型生命周期参数来标注这些关系,以确保运行时使用的实际引用肯定有效。

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 are only required to annotate types 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 that the actual references used at runtime will definitely be valid.

标注生命周期甚至不是大多数其他编程语言所具有的概念,因此这会让人感到陌生。虽然我们不会在本章涵盖生命周期的全部内容,但我们将讨论你可能遇到的常见生命周期语法,以便你熟悉这个概念。

Annotating lifetimes is not even 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 that you can get comfortable with the concept.

悬垂引用 (Dangling References)

Dangling References

生命周期的主要目的是防止“悬垂引用 (dangling references)”,如果允许它们存在,会导致程序引用非预期的内容。考虑示例 10-16 中的程序,它有一个外部作用域和一个内部作用域。

The main aim of lifetimes is to prevent dangling references, which, if they were allowed to exist, would 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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/main.rs}}

注意:示例 10-16、10-17 和 10-23 声明了变量但未赋予初始值,因此变量名存在于外部作用域中。乍一看,这似乎与 Rust 没有 null 值相冲突。然而,如果我们尝试在给变量赋值之前使用它,我们会得到一个编译时错误,这表明 Rust 确实不允许 null 值。

Note: The examples in Listings 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 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 indeed Rust does not allow null values.

外部作用域声明了一个名为 r 的变量且没有初始值,内部作用域声明了一个名为 x 的变量且初始值为 5。在内部作用域中,我们尝试将 r 的值设置为对 x 的引用。然后内部作用域结束,我们尝试打印 r 中的值。这段代码无法编译,因为 r 所引用的值在我们尝试使用它之前就已经超出了作用域。以下是错误消息:

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:

{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/output.txt}}

错误消息说变量 x “活得不够久 (does not live long enough)”。原因是当内部作用域在第 7 行结束时,x 将超出作用域。但 r 对外部作用域仍然有效;因为它的作用域更大,我们说它“活得更久”。如果 Rust 允许这段代码运行,r 将引用在 x 超出作用域时已被释放的内存,我们尝试对 r 做的任何事情都无法正常工作。那么,Rust 是如何确定这段代码无效的呢?它使用了借用检查器。

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.

借用检查器 (The Borrow Checker)

The Borrow Checker

Rust 编译器有一个“借用检查器 (borrow checker)”,它通过比较作用域来确定所有的借用是否有效。示例 10-17 显示了与示例 10-16 相同的代码,但带有显示变量生命周期的标注。

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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs}}

在这里,我们将 r 的生命周期标注为 'a,将 x 的生命周期标注为 'b。如你所见,内部的 'b 块比外部的 'a 生命周期块小得多。在编译时,Rust 比较这两个生命周期的大小,发现 r 具有 'a 的生命周期,但它引用了具有 'b 生命周期的内存。程序被拒绝了,因为 'b'a 短:引用的对象没有引用活得长。

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.

示例 10-18 修复了代码,使其不再具有悬垂引用,并且可以无错编译。

Listing 10-18 fixes the code so that it doesn’t have a dangling reference and it compiles without any errors.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs}}
}

在这里,x 具有生命周期 'b,在此例中它比 'a 大。这意味着 r 可以引用 x,因为 Rust 知道只要 x 有效,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.

既然你已经知道了引用的生命周期在哪里,以及 Rust 如何分析生命周期以确保引用始终有效,让我们来探索函数参数和返回值中的泛型生命周期。

Now that you know where the lifetimes of references are and how Rust analyzes lifetimes to ensure that references will always be valid, let’s explore generic lifetimes in function parameters and return values.

函数中的泛型生命周期 (Generic Lifetimes in Functions)

Generic Lifetimes in Functions

我们将编写一个函数,返回两个字符串切片中较长的一个。该函数将接收两个字符串切片并返回一个字符串切片。在我们实现了 longest 函数后,示例 10-19 中的代码应该打印 The longest string is abcd

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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs}}

请注意,我们希望该函数接收字符串切片(即引用)而不是字符串,因为我们不希望 longest 函数获取其参数的所有权。关于为什么我们在示例 10-19 中使用的参数是我们想要的,请参阅第 4 章中的“字符串切片作为参数”进行更多讨论。

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 “String Slices as Parameters” in Chapter 4 for more discussion about why the parameters we use in Listing 10-19 are the ones we want.

如果我们尝试按照示例 10-20 所示实现 longest 函数,它将无法通过编译。

If we try to implement the longest function as shown in Listing 10-20, it won’t compile.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs:here}}

相反,我们得到了以下涉及生命周期的错误:

Instead, we get the following error that talks about lifetimes:

{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/output.txt}}

帮助文本揭示了返回类型需要一个泛型生命周期参数,因为 Rust 无法判断返回的引用是引用自 x 还是 y。实际上,我们也不知道,因为该函数体内的 if 块返回了对 x 的引用,而 else 块返回了对 y 的引用!

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!

当我们定义此函数时,我们不知道将传入该函数的具体值,因此我们不知道是 if 情况还是 else 情况会执行。我们也不知道传入的引用的具体生命周期,因此我们不能像在示例 10-17 和 10-18 中那样查看作用域来确定我们返回的引用是否始终有效。借用检查器也无法确定这一点,因为它不知道 xy 的生命周期如何与返回值的生命周期相关联。为了修复此错误,我们将添加定义引用之间关系的泛型生命周期参数,以便借用检查器可以执行其分析。

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 that the borrow checker can perform its analysis.

生命周期标注语法 (Lifetime Annotation Syntax)

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.

生命周期标注有一种稍微不寻常的语法:生命周期参数的名称必须以单引号 (') 开头,并且通常全小写且非常短,类似于泛型类型。大多数人使用名称 'a 作为第一个生命周期标注。我们将生命周期参数标注放在引用的 & 之后,使用空格将标注与引用的类型隔开。

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.

这里有一些例子:一个没有生命周期参数的 i32 引用,一个具有名为 'a 的生命周期参数的 i32 引用,以及一个同样具有生命周期 'a 的可变 i32 引用:

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 mut i32 // 带有显式生命周期的可变引用

单个生命周期标注本身并没有太大的意义,因为标注是为了告诉 Rust 多个引用的泛型生命周期参数如何相互关联。让我们在 longest 函数的背景下检查生命周期标注是如何相互关联的。

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.

在函数签名中 (In Function Signatures)

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.

我们希望签名能表达以下约束:返回的引用只要两个参数都有效,它就有效。这是参数和返回值生命周期之间的关系。我们将生命周期命名为 'a,然后将其添加到每个引用中,如示例 10-21 所示。

We want the signature to express the following constraint: The returned reference will be valid as long as both of 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs:here}}
}

这段代码应该可以编译,并且在与示例 10-19 中的 main 函数一起使用时产生我们想要的结果。

This code should compile and produce the result we want when we use it with the main function in Listing 10-19.

现在的函数签名告诉 Rust:对于某种生命周期 'a,该函数接收两个参数,它们都是至少与生命周期 'a 活得一样长的字符串切片。函数签名还告诉 Rust,该函数返回的字符串切片也将至少与生命周期 'a 活得一样长。在实践中,这意味着由 longest 函数返回的引用的生命周期与函数参数所引用的值的生命周期中较小的一个相同。这些关系正是我们希望 Rust 在分析此代码时使用的。

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.

请记住,当我们在此函数签名中指定生命周期参数时,我们并没有改变任何传入或返回值的生命周期。相反,我们是在指定借用检查器应该拒绝任何不遵守这些约束的值。请注意,longest 函数不需要知道 xy 到底会活多久,只需要知道可以将某个作用域代入 'a 且能满足此签名即可。

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.

在为函数标注生命周期时,标注位于函数签名中,而不是函数体中。生命周期标注成为了函数合同的一部分,就像签名中的类型一样。让函数签名包含生命周期合同意味着 Rust 编译器所做的分析可以更简单。如果函数标注的方式或其调用的方式存在问题,编译器错误可以更精确地指向我们的代码部分和约束。相反,如果 Rust 编译器对我们预期的生命周期关系进行了更多推断,编译器可能只能指向距离问题原因许多步之外的我们的代码使用处。

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.

当我们向 longest 传递具体的引用时,代入 'a 的具体生命周期是 x 的作用域中与 y 的作用域重叠的部分。换句话说,泛型生命周期 'a 将获得等于 xy 生命周期中较小者的具体生命周期。因为我们为返回的引用标注了相同的生命周期参数 'a,所以返回的引用在 xy 生命周期中较小者的长度内也将是有效的。

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 函数的。示例 10-22 是一个直观的例子。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs:here}}
}

在这个例子中,string1 在外部作用域结束前有效,string2 在内部作用域结束前有效,而 result 引用了在内部作用域结束前有效的东西。运行此代码,你会看到借用检查器批准了它;它将编译并打印 The longest string is long string is long

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.

接下来,让我们尝试一个例子,展示 result 中引用的生命周期必须是两个参数中较小的那个生命周期。我们将 result 变量的声明移动到内部作用域之外,但保持在内部作用域中对 result 变量进行 string2 值的赋值。然后,我们将使用 resultprintln! 移动到内部作用域之外,即内部作用域结束之后。示例 10-23 中的代码将无法编译。

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.

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs:here}}

当我们尝试编译这段代码时,我们得到了这个错误:

When we try to compile this code, we get this error:

{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/output.txt}}

错误表明为了使 resultprintln! 语句中有效,string2 需要一直有效直到外部作用域结束。Rust 知道这一点,因为我们使用相同的生命周期参数 'a 标注了函数参数和返回值的生命周期。

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.

作为人类,我们可以观察这段代码并看到 string1string2 长,因此 result 将包含一个指向 string1 的引用。由于 string1 尚未超出作用域,对 string1 的引用在 println! 语句中仍将有效。然而,编译器在这种情况下无法看到引用是有效的。我们告诉 Rust,由 longest 函数返回的引用的生命周期与传入引用的生命周期中较小的一个相同。因此,借用检查器不允许示例 10-23 中的代码,认为它可能具有无效引用。

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.

尝试设计更多实验,改变传递给 longest 函数的引用的值和生命周期,以及如何使用返回的引用。在编译之前,先假设你的实验是否能通过借用检查器;然后检查你是否正确!

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!

关系 (Relationships)

Relationships

指定生命周期参数的方式取决于你的函数在做什么。例如,如果我们更改 longest 函数的实现,使其始终返回第一个参数而不是最长的字符串切片,我们就不需要在 y 参数上指定生命周期。以下代码将可以编译:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs:here}}
}

我们为参数 x 和返回类型指定了生命周期参数 'a,但没有为参数 y 指定,因为 y 的生命周期与 x 的生命周期或返回值没有任何关系。

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.

从函数返回引用时,返回类型的生命周期参数需要与其中一个参数的生命周期参数匹配。如果返回的引用“不”引用其中的一个参数,那么它必须引用在此函数内部创建的一个值。然而,这将是一个悬垂引用,因为该值在函数结束时将超出作用域。考虑这个尝试实现 longest 函数但无法编译的例子:

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:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs:here}}

在这里,即使我们为返回类型指定了生命周期参数 'a,这个实现也会编译失败,因为返回值的生命周期与参数的生命周期完全没有关系。这是我们得到的错误消息:

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:

{{#include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt}}

问题在于 resultlongest 函数结束时超出作用域并被清理。而我们还尝试从函数中返回 result 的引用。我们没有办法指定能够改变悬垂引用的生命周期参数,而且 Rust 不允许我们创建悬垂引用。在这种情况下,最好的修复方法是返回一个拥有所有权的数据类型而不是引用,这样调用函数就负责清理该值。

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 that the calling function is then responsible for cleaning up the value.

归根结底,生命周期语法是关于连接函数的各个参数和返回值的生命周期的。一旦它们连接起来,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.

在结构体定义中 (In Struct Definitions)

In Struct Definitions

到目前为止,我们定义的结构体都持有拥有所有权的类型。我们可以定义持有引用的结构体,但在这种情况下,我们需要在结构体定义的每个引用上添加生命周期标注。示例 10-24 有一个名为 ImportantExcerpt 的结构体,它持有一个字符串切片。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs}}
}

该结构体只有一个 part 字段,它持有一个字符串切片,这是一个引用。与泛型数据类型一样,我们在结构体名称后的尖括号内声明泛型生命周期参数的名称,以便我们可以在结构体定义的主体中使用该生命周期参数。此标注意味着 ImportantExcerpt 实例的存活时间不能超过它在 part 字段中持有的引用。

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 that 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.

这里的 main 函数创建了一个 ImportantExcerpt 结构体的实例,它持有一个指向变量 novel 所有的 String 第一句的引用。novel 中的数据在 ImportantExcerpt 实例创建之前就存在了。此外,novel 直到 ImportantExcerpt 超出作用域后才超出作用域,因此 ImportantExcerpt 实例中的引用是有效的。

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.

生命周期省略 (Lifetime Elision)

Lifetime Elision

你已经了解到每个引用都有一个生命周期,并且你需要为使用引用的函数或结构体指定生命周期参数。然而,我们在示例 4-9 中有一个函数(示例 10-25 中再次显示),它在没有生命周期标注的情况下通过了编译。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs:here}}
}

此函数在没有生命周期标注的情况下可以编译的原因是历史性的:在 Rust 的早期版本(1.0 之前)中,这段代码无法编译,因为每个引用都需要一个显式的生命周期。当时,函数签名会这样写:

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:

fn first_word<'a>(s: &'a str) -> &'a str {

在编写了大量 Rust 代码后,Rust 团队发现 Rust 程序员在特定情况下会反复输入相同的生命周期标注。这些情况是可以预见的,并且遵循一些确定的模式。开发人员将这些模式编入编译器代码中,以便借用检查器在这些情况下可以推断生命周期,而不需要显式的标注。

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 that the borrow checker could infer the lifetimes in these situations and wouldn’t need explicit annotations.

这段 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 对引用分析的模式被称为“生命周期省略规则 (lifetime elision rules)”。这些不是程序员要遵循的规则;它们是编译器会考虑的一组特定情况,如果你的代码符合这些情况,你就不需要显式地写出生命周期。

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 about 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.

函数或方法参数上的生命周期被称为“输入生命周期 (input lifetimes)”,而返回值上的生命周期被称为“输出生命周期 (output lifetimes)”。

Lifetimes on function or method parameters are called input lifetimes, and lifetimes on return values are called output lifetimes.

编译器使用三条规则来在没有显式标注时确定引用的生命周期。第一条规则适用于输入生命周期,第二条和第三条规则适用于输出生命周期。如果编译器在应用完这三条规则后,仍有无法确定生命周期的引用,编译器将报错停止。这些规则适用于 fn 定义以及 impl 块。

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 foo<'a>(x: &'a i32);具有两个参数的函数获得两个独立的生命周期参数:fn foo<'a, 'b>(x: &'a i32, y: &'b i32);依此类推。

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) -> &'a 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.

第三条规则是,如果有多个输入生命周期参数,但其中一个是 &self&mut self(因为这是个方法),则 self 的生命周期被分配给所有输出生命周期参数。这第三条规则使得方法读写起来更加舒心,因为需要的符号更少。

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.

让我们假装自己是编译器。我们将应用这些规则来确定示例 10-25 中 first_word 函数签名中的引用生命周期。签名最初没有任何与引用关联的生命周期:

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:

fn first_word(s: &str) -> &str {

然后编译器应用第一条规则,该规则指定每个参数获得其自己的生命周期。像往常一样,我们称之为 'a ,所以现在签名是这样的:

fn first_word<'a>(s: &'a str) -> &str {

第二条规则适用,因为恰好有一个输入生命周期。第二条规则指定那一个输入参数的生命周期被分配给输出生命周期,所以现在签名是这样的:

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.

让我们看另一个例子,这次使用示例 10-20 中我们在开始处理它时没有生命周期参数的 longest 函数:

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:

fn longest(x: &str, y: &str) -> &str {

让我们应用第一条规则:每个参数获得其自己的生命周期。这一次我们有两个参数而不是一个,所以我们有两个生命周期:

fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str {

你可以看到第二条规则不适用,因为输入生命周期不止一个。第三条规则也不适用,因为 longest 是一个函数而不是一个方法,所以参数中没有 self。在处理完所有三条规则后,我们仍然没有弄清楚返回类型的生命周期是什么。这就是为什么我们在尝试编译示例 10-20 中的代码时得到了错误:编译器处理了生命周期省略规则,但仍然无法确定签名中引用的所有生命周期。

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.

因为第三条规则实际上只适用于方法签名,接下来我们将看看该语境下的生命周期,以了解为什么第三条规则意味着我们不需要经常在方法签名中标注生命周期。

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.

在方法定义中 (In Method Definitions)

In Method Definitions

当我们在带有生命周期的结构体上实现方法时,我们使用与泛型类型参数相同的语法,如示例 10-11 所示。我们在何处声明和使用生命周期参数取决于它们是与结构体字段相关,还是与方法参数和返回值相关。

When we implement methods on a struct with lifetimes, we use the same syntax as that of generic type parameters, as 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.

结构体字段的生命周期名称始终需要在 impl 关键字之后声明,然后在结构体名称之后使用,因为这些生命周期是结构体类型的一部分。

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 块内部的方法签名中,引用可能与结构体字段中引用的生命周期绑定,也可能是独立的。此外,生命周期省略规则经常使得方法签名中不需要生命周期标注。让我们看一些使用我们在示例 10-24 中定义的名为 ImportantExcerpt 的结构体的例子。

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.

首先,我们将使用一个名为 level 的方法,其唯一参数是对 self 的引用,其返回值是一个 i32,它不是对任何东西的引用:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs:1st}}
}

impl 之后的生命周期参数声明及其在类型名称之后的引用是必需的,但由于第一条省略规则,我们不被要求标注 self 引用的生命周期。

The lifetime parameter declaration after impl and its use after the type name are required, but because of the first elision rule, we’re not required to annotate the lifetime of the reference to self.

这是一个适用第三条生命周期省略规则的例子:

Here is an example where the third lifetime elision rule applies:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs:3rd}}
}

有两个输入生命周期,因此 Rust 应用第一条生命周期省略规则,并为 &selfannouncement 都分配它们自己的生命周期。然后,因为其中一个参数是 &self ,返回类型就获得了 &self 的生命周期,所有的生命周期都得到了解决。

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.

静态生命周期 (The Static Lifetime)

The Static Lifetime

我们需要讨论的一个特殊生命周期是 'static,它表示受影响的引用“可以”在程序的整个持续时间内有效。所有的字符串字面量都具有 'static 生命周期,我们可以按如下方式标注:

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:

#![allow(unused)]
fn main() {
let s: &'static str = "I have a static lifetime.";
}

该字符串的文本直接存储在程序的可执行文件中,它是始终可用的。因此,所有字符串字面量的生命周期都是 '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 生命周期的建议。但在将 'static 指定为引用的生命周期之前,请思考你拥有的引用是否真的存活于程序的整个生命周期,以及你是否希望它如此。大多数时候,建议使用 'static 生命周期的错误消息是源于尝试创建悬垂引用或可用生命周期不匹配。在这些情况下,解决方案是修复这些问题,而不是指定 'static 生命周期。

You might see suggestions in error messages to use the 'static lifetime. But before specifying 'static as the lifetime for a reference, think about whether or not the reference you have actually lives the entire lifetime of your program, 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.

泛型类型参数、特征约束与生命周期 (Generic Type Parameters, Trait Bounds, and Lifetimes)

Generic Type Parameters, Trait Bounds, and Lifetimes

让我们简要地看一下在一个函数中同时指定泛型类型参数、特征约束和生命周期的语法!

Let’s briefly look at the syntax of specifying generic type parameters, trait bounds, and lifetimes all in one function!

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs:here}}
}

这是示例 10-21 中的 longest 函数,它返回两个字符串切片中较长的一个。但现在它多了一个名为 ann 的泛型类型 T 参数,它可以由满足 where 子句指定的 Display 特征的任何类型填充。这个额外的参数将使用 {} 打印,这就是为什么需要 Display 特征约束的原因。因为生命周期也是一种泛型,所以生命周期参数 'a 和泛型类型参数 T 的声明放在函数名后尖括号内的同一个列表中。

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.

总结 (Summary)

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!

信不信由你,关于我们在本章讨论的主题还有很多需要学习的内容:第 18 章讨论了特征对象,这是使用特征的另一种方式。还有涉及生命周期标注的更复杂场景,你只会在非常高级的场景中需要它们;对于这些,你应该阅读 Rust 参考手册。但接下来,你将学习如何在 Rust 中编写测试,以便确保你的代码正在按其应有的方式工作。

Believe it or not, there is much more to learn on the topics we discussed in this chapter: Chapter 18 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 that you can make sure your code is working the way it should.

编写自动化测试 (Writing Automated Tests)


x-i18n: generated_at: “2026-03-01T14:08:36Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: c65a2080c43a9f3d83a351779e059c6203b2c48285835c9fd277f7465fbd5192 source_path: ch11-00-testing.md workflow: 16

编写自动化测试 (Writing Automated Tests)

Writing Automated Tests

艾兹赫尔·韦伯·戴克斯特拉 (Edsger W. Dijkstra) 在其 1972 年的文章《谦卑的程序员》(The Humble Programmer) 中提到:“程序测试是证明存在漏洞的一种非常有效的方法,但对于证明不存在漏洞却显得无可奈何。”这并不意味着我们不应该尽力去测试!

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!

程序的“正确性 (Correctness)”是指我们的代码在多大程度上符合我们的意图。Rust 在设计时就高度关注程序的正确性,但正确性极其复杂且不易证明。Rust 的类型系统承担了这一重担的大部分,但类型系统无法捕获所有问题。因此,Rust 包含了对编写自动化软件测试的支持。

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.

假设我们编写了一个函数 add_two,它在传入的任何数字上加 2。该函数的签名接收一个整数作为参数并返回一个整数作为结果。当我们实现并编译该函数时,Rust 会执行你目前学到的所有类型检查和借用检查,以确保我们不会向该函数传递一个 String 值或一个无效引用。但 Rust “无法”检查这个函数是否完全符合我们的意图,即返回参数加 2,而不是参数加 10 或参数减 50!这就是测试派上用场的地方。

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 函数传递 3 时,返回值是 5。每当我们更改代码时,我们都可以运行这些测试,以确保现有的正确行为没有发生变化。

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.

测试是一项复杂的技能:虽然我们无法在一章中涵盖编写优秀测试的所有细节,但在本章中我们将讨论 Rust 测试设施的机制。我们将讨论你在编写测试时可用的注解和宏,运行测试时提供的默认行为和选项,以及如何将测试组织成单元测试和集成测试。

Testing is a complex skill: Although we can’t cover in one chapter every detail about how to write good tests, in this chapter we will 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.

如何编写测试 (How to Write Tests)


x-i18n: generated_at: “2026-03-01T14:10:26Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 03cec10df505d25d37717447f906d392506c18f4af1ba7ef9cc32f05cfc15359 source_path: ch11-01-writing-tests.md workflow: 16

如何编写测试 (How to Write Tests)

How to Write Tests

“测试 (Tests)”是 Rust 函数,用于验证非测试代码是否按预期方式运行。测试函数的主体通常执行以下三个操作:

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:

  • 设置所需的任何数据或状态。

  • 运行你想要测试的代码。

  • 断言结果是你所期望的。

  • Set up any needed data or state.

  • Run the code you want to test.

  • Assert that the results are what you expect.

让我们看看 Rust 专门为执行这些操作的测试提供的功能,包括 test 属性、几个宏以及 should_panic 属性。

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.

测试函数的结构 (Structuring Test Functions)

Structuring Test Functions

最简单的情况下,Rust 中的测试是一个标注了 test 属性的函数。属性(Attributes)是关于 Rust 代码片段的元数据;第 5 章中我们在结构体上使用的 derive 属性就是一个例子。要将函数更改为测试函数,请在 fn 之前的行中添加 #[test]。当你使用 cargo test 命令运行测试时,Rust 会构建一个测试运行器二进制文件,该文件会运行被标注的函数,并报告每个测试函数是成功还是失败。

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.

每当我们使用 Cargo 创建一个新的库项目时,都会自动为我们生成一个包含测试函数的测试模块。这个模块为你编写测试提供了一个模板,这样你就不用每次开始新项目时都要去查找确切的结构和语法。你可以根据需要添加任意数量的附加测试函数和测试模块!

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 that 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!

在实际测试任何代码之前,我们将通过试验模板测试来探索测试工作原理的某些方面。然后,我们将编写一些实际测试,调用我们编写的代码并断言其行为是否正确。

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.

让我们创建一个名为 adder 的新库项目,它将把两个数字相加:

Let’s create a new library project called adder that will add two numbers:

$ cargo new adder --lib
     Created library `adder` project
$ cd adder

你的 adder 库中的 src/lib.rs 文件内容应该如示例 11-1 所示。

The contents of the src/lib.rs file in your adder library should look like Listing 11-1.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs}}

文件以一个示例 add 函数开始,这样我们就有了可以测试的东西。

The file starts with an example add function so that we have something to test.

现在,让我们仅关注 it_works 函数。请注意 #[test] 标注:此属性表明这是一个测试函数,因此测试运行器知道将此函数视为测试。在 tests 模块中,我们也可能有非测试函数来帮助设置常见场景或执行通用操作,因此我们总是需要指明哪些函数是测试。

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.

示例函数体使用 assert_eq! 宏来断言 result(包含调用 add 传入 2 和 2 的结果)等于 4。这个断言是典型测试格式的一个示例。让我们运行它,看看这个测试是否通过。

The example function body uses the assert_eq! macro to assert that result, which contains the result of calling add with 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.

cargo test 命令运行项目中所有的测试,如示例 11-2 所示。

The cargo test command runs all tests in our project, as shown in Listing 11-2.

{{#include ../listings/ch11-writing-automated-tests/listing-11-01/output.txt}}

Cargo 编译并运行了测试。我们看到行 running 1 test。下一行显示生成的测试函数的名称,称为 tests::it_works,以及运行该测试的结果为 ok。总体摘要 test result: ok. 意味着所有测试都通过了,而 1 passed; 0 failed 部分统计了通过或失败的测试数量。

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 tests::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.

可以将测试标记为被忽略,这样它在特定实例中就不会运行;我们将在本章稍后的“除非特别请求,否则忽略测试”部分进行介绍。因为我们在这里没有这样做,所以摘要显示 0 ignored。我们还可以向 cargo test 命令传递一个参数,以仅运行名称与字符串匹配的测试;这被称为“过滤 (filtering)”,我们将在“按名称运行测试子集”部分进行介绍。在这里,我们没有过滤正在运行的测试,因此摘要末尾显示 0 filtered out

It’s possible to mark a test as ignored so that it doesn’t run in a particular instance; we’ll cover that in the “Ignoring 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 it in the “Running a Subset of Tests by Name” section. Here, we haven’t filtered the tests being run, so the end of the summary shows 0 filtered out.

0 measured 统计数据用于衡量性能的基准测试(benchmark tests)。截至撰写本文时,基准测试仅在 nightly 版 Rust 中可用。请参阅关于基准测试的文档以了解更多信息。

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.

测试输出中以 Doc-tests adder 开始的下一部分是针对任何文档测试(documentation tests)的结果。我们目前还没有任何文档测试,但 Rust 可以编译 API 文档中出现的任何代码示例。此功能有助于保持你的文档与代码同步!我们将在第 14 章的“作为测试的文档注释”部分讨论如何编写文档测试。现在,我们将忽略 Doc-tests 输出。

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.

让我们开始根据自己的需求定制测试。首先,将 it_works 函数的名称更改为不同的名称,例如 exploration,如下所示:

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:

文件名: src/lib.rs

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs}}

然后,再次运行 cargo test。输出现在显示 exploration 而不是 it_works

Then, run cargo test again. The output now shows exploration instead of it_works:

{{#include ../listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt}}

现在我们将添加另一个测试,但这次我们要创建一个会失败的测试!当测试函数中的某些内容引发恐慌时,测试就会失败。每个测试都在一个新线程中运行,当主线程看到测试线程已死亡时,该测试就会被标记为失败。在第 9 章中,我们讨论了引发恐慌最简单的方法是调用 panic! 宏。输入名为 another 的新测试函数,使你的 src/lib.rs 文件如示例 11-3 所示。

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.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs}}

再次使用 cargo test 运行测试。输出应如示例 11-4 所示,它显示我们的 exploration 测试通过了,而 another 失败了。

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.

{{#include ../listings/ch11-writing-automated-tests/listing-11-03/output.txt}}

test tests::another 显示的是 FAILED 而不是 ok。在单独的结果和摘要之间出现了两个新部分:第一个部分显示了每个测试失败的详细原因。在这种情况下,我们得到的细节是 tests::another 失败了,因为它在 src/lib.rs 文件的第 17 行发生了恐慌,消息为 Make this test fail。下一部分仅列出所有失败测试的名称,这在有很多测试和很多详细的失败测试输出时非常有用。我们可以使用失败测试的名称来仅运行该测试,以便更轻松地对其进行调试;我们将在“控制测试如何运行”部分讨论更多运行测试的方法。

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 tests::another failed because it panicked with the message Make this test fail on line 17 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 debug it more easily; we’ll talk more about ways to run tests in the “Controlling How Tests Are Run” section.

摘要行显示在最后:总体而言,我们的测试结果是 FAILED。我们有一个测试通过,一个测试失败。

The summary line displays at the end: Overall, our test result is FAILED. We had one test pass and one test fail.

既然你已经看到了不同情况下测试结果的样子,让我们看看除了 panic! 之外,在测试中还有哪些有用的宏。

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.

使用 assert! 宏检查结果 (Checking Results with assert!)

Checking Results with assert!

标准库提供的 assert! 宏非常有用,它可以确保测试中的某些条件求值为 true。我们给 assert! 宏提供一个求值为布尔值的参数。如果值为 true,则什么也不会发生,测试通过。如果值为 false,则 assert! 宏会调用 panic! 导致测试失败。使用 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.

在第 5 章示例 5-15 中,我们使用了一个 Rectangle 结构体和一个 can_hold 方法,它们在示例 11-5 中再次列出。让我们将这些代码放入 src/lib.rs 文件,然后使用 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.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs}}

can_hold 方法返回一个布尔值,这意味着它是 assert! 宏的一个完美用例。在示例 11-6 中,我们编写了一个测试来练习 can_hold 方法,方法是创建一个宽度为 8、高度为 7 的 Rectangle 实例,并断言它可以持有另一个宽度为 5、高度为 1 的 Rectangle 实例。

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.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs:here}}

请注意 tests 模块内部的 use super::*; 行。tests 模块是一个常规模块,遵循我们在第 7 章“在模块树中引用项的路径”部分介绍的通常可见性规则。因为 tests 模块是一个内部模块,我们需要将被测代码从外部模块引入到内部模块的作用域。我们在这里使用了 glob 通配符,因此我们在外部模块中定义的任何内容都对这个 tests 模块可用。

Note the use super::*; line inside the tests module. 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.

我们将测试命名为 larger_can_hold_smaller,并创建了所需的两个 Rectangle 实例。然后,我们调用了 assert! 宏并传递给它调用 larger.can_hold(&smaller) 的结果。该表达式应该返回 true,所以我们的测试应该通过。让我们拭目以待!

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!

{{#include ../listings/ch11-writing-automated-tests/listing-11-06/output.txt}}

它确实通过了!让我们再添加一个测试,这次断言较小的矩形无法持有较大的矩形:

It does pass! Let’s add another test, this time asserting that a smaller rectangle cannot hold a larger rectangle:

文件名: src/lib.rs

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs:here}}

因为在这种情况下 can_hold 函数的正确结果是 false ,我们需要在将其传递给 assert! 宏之前对该结果取反。结果是,如果 can_hold 返回 false ,我们的测试将通过:

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:

{{#include ../listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt}}

两个测试都通过了!现在让我们看看当我们代码中引入一个 bug 时,我们的测试结果会发生什么。我们将更改 can_hold 方法的实现,在比较宽度时将大于号 (>) 替换为小于号 (<):

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:

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs:here}}

现在运行测试会产生如下结果:

Running the tests now produces the following:

{{#include ../listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt}}

我们的测试抓住了 bug!因为 larger.width8smaller.width5,现在 can_hold 中宽度的比较返回 false:8 不小于 5。

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.

使用 assert_eq!assert_ne! 宏测试相等性 (Testing Equality with assert_eq! and assert_ne!)

Testing Equality with assert_eq! and assert_ne!

验证功能的一种常见方法是测试被测代码的结果与你期望代码返回的值之间的相等性。你可以通过使用 assert! 宏并传递一个使用 == 运算符的表达式来实现这一点。然而,由于这是一种非常常见的测试,标准库提供了一对宏——assert_eq!assert_ne!——来更方便地执行此测试。这些宏分别比较两个参数的相等或不等。如果断言失败,它们还会打印这两个值,这使得更容易看到测试失败的“原因”;相反,assert! 宏仅指示对于 == 表达式它得到了一个 false 值,而不会打印导致 false 值的值。

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 by 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.

在示例 11-7 中,我们编写了一个名为 add_two 的函数,它在其参数上加 2,然后使用 assert_eq! 宏测试此函数。

In Listing 11-7, we write a function named add_two that adds 2 to its parameter, and then we test this function using the assert_eq! macro.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs}}

让我们检查它是否通过!

Let’s check that it passes!

{{#include ../listings/ch11-writing-automated-tests/listing-11-07/output.txt}}

我们创建了一个名为 result 的变量,它持有调用 add_two(2) 的结果。然后,我们将 result4 作为参数传递给 assert_eq! 宏。此测试的输出行为 test tests::it_adds_two ... okok 文本表明我们的测试通过了!

We create a variable named result that holds the result of calling add_two(2). Then, we pass result and 4 as the arguments to the assert_eq! macro. The output line for this test is test tests::it_adds_two ... ok, and the ok text indicates that our test passed!

让我们在代码中引入一个 bug,看看 assert_eq! 失败时的样子。将 add_two 函数的实现改为加 3

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:

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs:here}}

再次运行测试:

Run the tests again:

{{#include ../listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt}}

我们的测试抓住了 bug!tests::it_adds_two 测试失败了,消息告诉我们失败的断言是 left == right,以及 leftright 的值分别是什么。此消息帮助我们开始调试:left 参数(即我们调用 add_two(2) 的结果)是 5 ,但 right 参数是 4 。你可以想象,当我们有很多测试在运行时,这会特别有帮助。

Our test caught the bug! The tests::it_adds_two test failed, and the message tells us that the assertion that failed was left == right and what the left and right values are. This message helps us start debugging: The left argument, where we had the result of calling add_two(2), was 5, but the right argument was 4. You can imagine that this would be especially helpful when we have a lot of tests going on.

请注意,在某些语言和测试框架中,相等断言函数的参数被称为 expectedactual ,并且我们指定参数的顺序很重要。然而,在 Rust 中,它们被称为 leftright ,我们指定期望值和代码产生值的顺序并不重要。我们可以将此测试中的断言写成 assert_eq!(4, result) ,这会导致相同的失败消息显示 assertion `left == right` failed

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!(4, result), which would result in the same failure message that displays assertion `left == right` failed.

如果我们给 assert_ne! 宏的两个值不相等,它就会通过;如果它们相等,它就会失败。这个宏在以下情况最有用:当我们不确定一个值“会”是什么,但我们知道该值肯定“不应该”是什么。例如,如果我们正在测试一个保证会以某种方式更改其输入的函数,但输入被更改的方式取决于我们运行测试的日期,那么最好的断言方式可能是断言函数的输出不等于其输入。

The assert_ne! macro will pass if the two values we give it are not equal and will fail if they are 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_eq!assert_ne! 宏分别使用运算符 ==!= 。当断言失败时,这些宏会使用调试格式打印它们的参数,这意味着被比较的值必须实现 PartialEqDebug 特征。所有原始类型和大多数标准库类型都实现了这些特征。对于你自己定义的结构体和枚举,你需要实现 PartialEq 才能断言这些类型的相等性。你还需要实现 Debug 才能在断言失败时打印这些值。因为这两个特征都是可派生特征,如第 5 章示例 5-12 中所述,这通常就像在你的结构体或枚举定义中添加 #[derive(PartialEq, Debug)] 标注一样简单。有关这些和其他可派生特征的更多细节,请参阅附录 C “可派生特征”

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.

添加自定义失败消息 (Adding Custom Failure Messages)

Adding Custom Failure Messages

你还可以作为可选参数向 assert!assert_eq!assert_ne! 宏添加要与失败消息一起打印的自定义消息。在必需参数之后指定的任何参数都会被传递给 format! 宏(在第 8 章“使用 +format! 拼接”中讨论),因此你可以传递一个包含 {} 占位符的格式字符串以及要放入这些占位符中的值。自定义消息对于记录断言的含义很有用;当测试失败时,你会更清楚地了解代码出了什么问题。

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 “Concatenating with + or format! in Chapter 8), 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.

例如,假设我们有一个通过名称问候他人的函数,并且我们想要测试传入该函数的名称是否出现在输出中:

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:

文件名: src/lib.rs

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs}}

该程序的要求尚未达成一致,而且我们非常确定问候语开头的 Hello 文本会发生变化。我们决定不希望在要求更改时更新测试,因此与其检查是否与 greeting 函数返回的值完全相等,我们只断言输出包含输入参数的文本。

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.

现在让我们通过更改 greeting 以排除 name 来在代码中引入一个 bug,看看默认的测试失败是什么样子的:

Now let’s introduce a bug into this code by changing greeting to exclude name to see what the default test failure looks like:

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs:here}}

运行此测试会产生如下结果:

Running this test produces the following:

{{#include ../listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt}}

此结果仅指出断言失败以及断言在哪一行。一个更有用的失败消息会打印出 greeting 函数的值。让我们添加一个自定义失败消息,它由一个格式字符串组成,其中的占位符填充了我们从 greeting 函数得到的实际值:

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:

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs:here}}

现在当我们运行测试时,我们将得到一个更有用的错误消息:

Now when we run the test, we’ll get a more informative error message:

{{#include ../listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt}}

我们可以在测试输出中看到我们实际得到的值,这将帮助我们调试发生了什么,而不是我们期望发生什么。

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.

使用 should_panic 检查恐慌 (Checking for Panics with should_panic)

Checking for Panics with should_panic

除了检查返回值之外,检查我们的代码是否按预期处理错误条件也很重要。例如,考虑我们在第 9 章示例 9-13 中创建的 Guess 类型。使用 Guess 的其他代码依赖于 Guess 实例仅包含 1 到 100 之间数值的保证。我们可以编写一个测试,确保尝试使用该范围之外的值创建 Guess 实例会引发恐慌。

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.

我们通过在测试函数中添加属性 should_panic 来实现这一点。如果函数内的代码引发恐慌,测试就通过;如果函数内的代码不引发恐慌,测试就失败。

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.

示例 11-8 显示了一个检查 Guess::new 的错误条件是否在我们期望时发生的测试。

Listing 11-8 shows a test that checks that the error conditions of Guess::new happen when we expect them to.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs}}

我们将 #[should_panic] 属性放在 #[test] 属性之后,以及它所应用的测试函数之前。让我们看看当这个测试通过时的结果:

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:

{{#include ../listings/ch11-writing-automated-tests/listing-11-08/output.txt}}

看起来不错!现在让我们通过移除 new 函数在值大于 100 时会引发恐慌的条件,在代码中引入一个 bug:

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:

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs:here}}

当我们运行示例 11-8 中的测试时,它将失败:

When we run the test in Listing 11-8, it will fail:

{{#include ../listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt}}

在这种情况下我们没有得到非常有用的消息,但当我们查看测试函数时,我们看到它标注了 #[should_panic] 。我们得到的失败意味着测试函数中的代码没有导致恐慌。

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 的测试可能会不够精确。即使测试因为与我们预期不同的原因而引发恐慌,should_panic 测试也会通过。为了使 should_panic 测试更精确,我们可以向 should_panic 属性添加一个可选的 expected 参数。测试工具将确保失败消息包含提供的文本。例如,考虑示例 11-9 中修改后的 Guess 代码,其中 new 函数根据值是太小还是太大引发带有不同消息的恐慌。

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.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs:here}}

这个测试会通过,因为我们放入 should_panic 属性的 expected 参数中的值是 Guess::new 函数恐慌消息的一个子字符串。我们可以指定我们期望的完整恐慌消息,在此例中为 Guess value must be less than or equal to 100, got 200 。你选择指定多少取决于恐慌消息中有多少是唯一或动态的,以及你希望测试有多精确。在这种情况下,恐慌消息的子字符串足以确保测试函数中的代码执行了 else if value > 100 的情况。

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.

为了看看当带有 expected 消息的 should_panic 测试失败时会发生什么,让我们再次在代码中引入一个 bug,交换 if value < 1else 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:

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs:here}}

这一次当我们运行 should_panic 测试时,它将失败:

This time when we run the should_panic test, it will fail:

{{#include ../listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt}}

失败消息指出该测试确实如我们预期的那样引发了恐慌,但恐慌消息不包含预期的字符串 less than or equal to 100 。我们在这种情况下得到的恐慌消息是 Guess value must be greater than or equal to 1, got 200 。现在我们可以开始弄清楚我们的 bug 在哪里了!

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!

在测试中使用 Result<T, E> (Using Result<T, E> in Tests)

Using Result<T, E> in Tests

到目前为止,我们所有的测试在失败时都会引发恐慌。我们也可以编写使用 Result<T, E> 的测试!这里是来自示例 11-1 的测试,被重写为使用 Result<T, E> 并在失败时返回 Err 而不是恐慌:

All of our tests so far 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:

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs:here}}

it_works 函数现在的返回类型为 Result<(), String> 。在函数体中,我们不再调用 assert_eq! 宏,而是在测试通过时返回 Ok(()),在测试失败时返回一个包含 StringErr

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.

将测试编写为返回 Result<T, E> 使你能够在测试主体中使用问号运算符,这可以是编写在其中任何操作返回 Err 变体时都应该失败的测试的便捷方式。

Writing tests so that 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> 的测试上使用 #[should_panic] 标注。要断言一个操作返回 Err 变体,“不要”在 Result<T, E> 值上使用问号运算符。相反,使用 assert!(value.is_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()).

既然你已经知道了编写测试的几种方法,让我们看看运行测试时发生了什么,并探索可以与 cargo test 一起使用的不同选项。

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.

控制测试如何运行 (Controlling How Tests Are Run)


x-i18n: generated_at: “2026-03-01T14:10:47Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 4c2cbb5c746e0c91c91d40b178025135bf126175c957110f0fa4368613388960 source_path: ch11-02-running-tests.md workflow: 16

控制测试如何运行 (Controlling How Tests Are Run)

Controlling How Tests Are Run

正如 cargo run 编译代码并运行生成的二进制文件一样,cargo test 在测试模式下编译代码并运行生成的测试二进制文件。cargo test 生成的二进制文件的默认行为是并行运行所有测试,并捕获测试运行期间生成的输出,防止输出被显示,从而更容易阅读与测试结果相关的输出。然而,你可以指定命令行选项来更改这种默认行为。

Just as cargo run compiles your code and then runs the resultant binary, cargo test compiles your code in test mode and runs the resultant 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 test,一些用于生成的测试二进制文件。为了区分这两类参数,你先列出用于 cargo test 的参数,后跟分隔符 --,然后是用于测试二进制文件的参数。运行 cargo test --help 会显示你可以与 cargo test 一起使用的选项,运行 cargo test -- --help 会显示你可以在分隔符之后使用的选项。这些选项在 rustc 手册的“Tests”部分中也有记载。

Some command line options go to cargo test, and some go to the resultant 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. These options are also documented in the “Tests” section of The rustc Book.

并行或连续运行测试 (Running Tests in Parallel or Consecutively)

Running Tests in Parallel or Consecutively

当你运行多个测试时,默认情况下它们使用线程并行运行,这意味着它们能更快地完成运行,你也能更快地得到反馈。因为测试是同时运行的,你必须确保你的测试不相互依赖,也不依赖于任何共享状态,包括共享环境,如当前工作目录或环境变量。

When you run multiple tests, by default they run in parallel using threads, meaning they finish running more quickly and you get feedback sooner. 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.

例如,假设你的每个测试都运行一些代码,在磁盘上创建一个名为 test-output.txt 的文件并向该文件写入一些数据。然后,每个测试读取该文件中的数据并断言该文件包含一个特定的值,而这个值在每个测试中都是不同的。因为测试同时运行,一个测试可能会在另一个测试写入和读取该文件的间隙重写该文件。第二个测试随后会失败,不是因为代码不正确,而是因为测试在并行运行时相互干扰了。一种解决方案是确保每个测试写入不同的文件;另一种解决方案是每次只运行一个测试。

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 when another test is 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-threads 标志和你想使用的线程数。请看以下示例:

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:

$ cargo test -- --test-threads=1

我们将测试线程数设置为 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.

显示函数输出 (Showing Function Output)

Showing Function Output

默认情况下,如果测试通过,Rust 的测试库会捕获任何打印到标准输出的内容。例如,如果我们如果在测试中调用 println! 且测试通过了,我们不会在终端看到 println! 的输出;我们只会看到指示测试通过的行。如果测试失败,我们将看到打印到标准输出的内容以及其余的失败消息。

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.

举个例子,示例 11-10 有一个无聊的函数,它打印参数的值并返回 10,还有一个通过的测试和一个失败的测试。

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.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs}}

当我们使用 cargo test 运行这些测试时,我们将看到以下输出:

When we run these tests with cargo test, we’ll see the following output:

{{#include ../listings/ch11-writing-automated-tests/listing-11-10/output.txt}}

请注意,在此输出的任何地方我们都没有看到 I got the value 4 ,它是通过的测试运行时打印的。该输出已被捕获。来自失败测试的输出 I got the value 8 出现在测试摘要输出的部分,该部分还显示了测试失败的原因。

Note that nowhere in this output do we see I got the value 4, which 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.

如果我们也想看到通过测试的打印值,我们可以告诉 Rust 也显示成功测试的输出,使用 --show-output

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:

$ cargo test -- --show-output

当我们再次使用 --show-output 标志运行示例 11-10 中的测试时,我们看到以下输出:

When we run the tests in Listing 11-10 again with the --show-output flag, we see the following output:

{{#include ../listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt}}

按名称运行测试子集 (Running a Subset of Tests by Name)

Running a Subset of Tests by Name

运行完整的测试套件有时会花费很长时间。如果你正在处理特定区域的代码,你可能只想运行与该代码相关的测试。你可以通过将你想要运行的测试的一个或多个名称作为参数传递给 cargo test 来选择要运行的测试。

Running a full test suite can sometimes 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.

为了演示如何运行测试子集,我们将首先为我们的 add_two 函数创建三个测试,如示例 11-11 所示,并选择运行哪些测试。

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.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs}}

如果我们不传递任何参数运行测试,正如我们之前看到的,所有测试都将并行运行:

If we run the tests without passing any arguments, as we saw earlier, all the tests will run in parallel:

{{#include ../listings/ch11-writing-automated-tests/listing-11-11/output.txt}}

运行单个测试 (Running Single Tests)

Running Single Tests

我们可以将任何测试函数的名称传递给 cargo test 以仅运行该测试:

We can pass the name of any test function to cargo test to run only that test:

{{#include ../listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt}}

只有名为 one_hundred 的测试运行了;其他两个测试与该名称不匹配。测试输出通过在末尾显示 2 filtered out 来让我们知道我们有更多未运行的测试。

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.

我们不能以这种方式指定多个测试的名称;只有给 cargo test 的第一个值会被使用。但是有一种运行多个测试的方法。

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.

过滤以运行多个测试 (Filtering to Run Multiple Tests)

Filtering to Run Multiple Tests

我们可以指定测试名称的一部分,任何名称匹配该值的测试都将被运行。例如,因为我们有两个测试的名称包含 add ,我们可以通过运行 cargo test add 来运行这两个测试:

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:

{{#include ../listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt}}

此命令运行了名称中包含 add 的所有测试,并过滤掉了名为 one_hundred 的测试。还要注意,测试所在的模块变成了测试名称的一部分,所以我们可以通过过滤模块名称来运行模块中的所有测试。

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.

除非特别请求,否则忽略测试 (Ignoring Tests Unless Specifically Requested)

Ignoring Tests Unless Specifically Requested

有时一些特定的测试执行起来会非常耗时,所以你可能希望在大多数 cargo test 运行期间排除它们。与其将所有你“确实”想运行的测试列为参数,不如使用 ignore 属性标注耗时的测试以排除它们,如下所示:

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:

文件名: src/lib.rs

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs:here}}

#[test] 之后,我们将 #[ignore] 行添加到想要排除的测试中。现在当我们运行测试时,it_works 运行了,但 expensive_test 没有:

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:

{{#include ../listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt}}

expensive_test 函数被列为 ignored(被忽略)。如果我们只想运行被忽略的测试,可以使用 cargo test -- --ignored

The expensive_test function is listed as ignored. If we want to run only the ignored tests, we can use cargo test -- --ignored:

{{#include ../listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt}}

通过控制运行哪些测试,你可以确保你的 cargo test 结果能够快速返回。当你觉得检查 ignored 测试的结果有意义且你有时间等待结果时,可以运行 cargo test -- --ignored。如果你想运行所有测试,无论它们是否被忽略,你可以运行 cargo test -- --include-ignored

By controlling which tests run, you can make sure your cargo test results will be returned quickly. 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.

测试组织 (Test Organization)


x-i18n: generated_at: “2026-03-01T14:11:58Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: b6131ddfce33ee37534fde3116a1bc7dd191747a645e2a0272faf7c18a9f8942 source_path: ch11-03-test-organization.md workflow: 16

测试组织 (Test Organization)

Test Organization

正如本章开头所述,测试是一门复杂的学科,不同的人使用不同的术语和组织方式。Rust 社区将测试分为两大类:单元测试和集成测试。“单元测试 (Unit tests)”规模较小且更集中,一次隔离地测试一个模块,并且可以测试私有接口。“集成测试 (Integration tests)”则完全位于你的库之外,它们以与其他外部代码相同的方式使用你的代码,仅使用公有接口,并且每个测试可能行使多个模块的功能。

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.

编写这两类测试对于确保你的库的各个部分分别及共同按预期工作非常重要。

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)

Unit Tests

单元测试的目的是将每个代码单元与其余代码隔离,以便快速定位代码在哪些地方运行正常或不正常。你会将单元测试放在 src 目录下的每个文件中,并与它们正在测试的代码放在一起。惯例是在每个文件中创建一个名为 tests 的模块来包含测试函数,并为该模块标注 cfg(test)

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).

tests 模块与 #[cfg(test)] (The tests Module and #[cfg(test)])

The tests Module and #[cfg(test)]

tests 模块上的 #[cfg(test)] 标注告诉 Rust 仅当你运行 cargo test 时才编译和运行测试代码,而不是运行 cargo build 时。当你只想构建库时,这可以节省编译时间,并由于未包含测试而节省生成的编译产物的空间。你会看到集成测试位于不同的目录中,因此它们不需要 #[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 resultant 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.

回想本章第一节我们生成新的 adder 项目时,Cargo 为我们生成的代码:

Recall that when we generated the new adder project in the first section of this chapter, Cargo generated this code for us:

文件名: src/lib.rs

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs}}

在自动生成的 tests 模块上,属性 cfg 代表“配置 (configuration)”,它告诉 Rust 仅在给定特定配置选项时才包含以下项。在这种情况下,配置选项是 test,这是由 Rust 提供的用于编译和运行测试的选项。通过使用 cfg 属性,Cargo 仅在我们主动使用 cargo test 运行测试时才会编译我们的测试代码。这包括此模块内可能存在的任何辅助函数,以及标注了 #[test] 的函数。

On the automatically generated tests 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].

私有函数测试 (Private Function Tests)

Private Function Tests

在测试界对于是否应该直接测试私有函数存在争论,其他语言使得测试私有函数变得困难或不可能。无论你坚持哪种测试意识形态,Rust 的私有性规则都允许你测试私有函数。考虑示例 11-12 中带有私有函数 internal_adder 的代码。

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.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs}}

请注意,internal_adder 函数未被标记为 pub。测试仅仅是 Rust 代码,而 tests 模块也只是另一个模块。正如我们在“在模块树中引用项的路径”中讨论的那样,子模块中的项可以使用其祖先模块中的项。在这个测试中,我们使用 use super::* 将属于 tests 模块父模块的所有项引入作用域,然后测试就可以调用 internal_adder 了。如果你认为不应该测试私有函数,Rust 中没有任何机制会强迫你这样做。

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 “Paths for Referring to an Item in the Module Tree”, items in child modules can use the items in their ancestor modules. In this test, we bring all of the items belonging to the tests module’s parent 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.

集成测试 (Integration Tests)

Integration Tests

在 Rust 中,集成测试完全位于你的库之外。它们以与任何其他代码相同的方式使用你的库,这意味着它们只能调用作为你库公有 API 一部分的函数。它们的目的是测试你的库的许多部分是否能正确地协同工作。单独工作正常的代码单元在集成时可能会出现问题,因此集成代码的测试覆盖率也非常重要。要创建集成测试,你首先需要一个 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.

tests 目录 (The tests Directory)

The tests Directory

我们在项目目录的顶层,即 src 旁边创建一个 tests 目录。Cargo 知道在这个目录中查找集成测试文件。然后我们可以创建任意数量的测试文件,Cargo 会将每个文件编译为一个独立的 crate。

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.

让我们创建一个集成测试。保持示例 11-12 中的代码仍在 src/lib.rs 文件中,创建一个 tests 目录,并创建一个名为 tests/integration_test.rs 的新文件。你的目录结构应该像这样:

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:

adder
├── Cargo.lock
├── Cargo.toml
├── src
│   └── lib.rs
└── tests
    └── integration_test.rs

将示例 11-13 中的代码输入到 tests/integration_test.rs 文件中。

Enter the code in Listing 11-13 into the tests/integration_test.rs file.

{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs}}

tests 目录中的每个文件都是一个独立的 crate,所以我们需要将我们的库引入每个测试 crate 的作用域。因此,我们在代码顶部添加了 use adder::add_two; ,这在单元测试中是不需要的。

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/integration_test.rs 中的任何代码标注 #[cfg(test)] 。Cargo 对 tests 目录进行了特殊处理,仅当我们运行 cargo test 时才编译该目录下的文件。现在运行 cargo test

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:

{{#include ../listings/ch11-writing-automated-tests/listing-11-13/output.txt}}

输出的三个部分包括单元测试、集成测试和文档测试。请注意,如果一个部分中的任何测试失败,接下来的部分将不会运行。例如,如果单元测试失败,集成测试和文档测试将不会有任何输出,因为只有在所有单元测试都通过时才会运行这些测试。

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.

关于单元测试的第一部分与我们一直看到的一样:每个单元测试一行(示例 11-12 中添加的一个名为 internal 的测试),然后是单元测试的摘要行。

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.

集成测试部分以行 Running tests/integration_test.rs 开始。接下来,在该集成测试中的每个测试函数都有一行,以及在 Doc-tests adder 部分开始之前显示的集成测试结果摘要行。

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.

每个集成测试文件都有自己的部分,所以如果我们在 tests 目录中添加更多文件,就会有更多的集成测试部分。

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.

我们仍然可以通过指定测试函数的名称作为 cargo test 的参数来运行特定的集成测试函数。要运行特定集成测试文件中的所有测试,请使用 cargo test--test 参数后跟文件名:

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:

{{#include ../listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt}}

此命令仅运行 tests/integration_test.rs 文件中的测试。

This command runs only the tests in the tests/integration_test.rs file.

集成测试中的子模块 (Submodules in Integration Tests)

Submodules in Integration Tests

随着你添加更多的集成测试,你可能想在 tests 目录下创建更多文件来帮助组织它们;例如,你可以按测试的功能对测试函数进行分组。如前所述,tests 目录中的每个文件都会被编译为各自独立的 crate,这对于创建独立作用域以更贴近地模拟终端用户使用你的 crate 的方式很有用。然而,这意味着 tests 目录中的文件不共享你在第 7 章中学到的关于如何将代码拆分为模块和文件的 src 文件的相同行为。

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.

当你有一组要在多个集成测试文件中使用的辅助函数,并尝试遵循第 7 章“将模块拆分为不同的文件”部分中的步骤将它们提取到公共模块中时,tests 目录文件行为的不同最为明显。例如,如果我们创建了 tests/common.rs 并在其中放入了一个名为 setup 的函数,我们可以向 setup 添加一些我们想要从多个测试文件中的多个测试函数调用的代码:

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:

文件名: tests/common.rs

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs}}

当我们再次运行测试时,我们会看到测试输出中为 common.rs 文件新增了一个部分,即使该文件不包含任何测试函数,我们也没有从任何地方调用 setup 函数:

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:

{{#include ../listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt}}

common 出现在测试结果中并显示 running 0 tests 并不是我们想要的。我们只是想与其他集成测试文件共享一些代码。为了避免 common 出现在测试输出中,我们将不创建 tests/common.rs ,而是创建 tests/common/mod.rs 。项目目录现在看起来像这样:

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. 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:

├── Cargo.lock
├── Cargo.toml
├── src
│   └── lib.rs
└── tests
    ├── common
    │   └── mod.rs
    └── integration_test.rs

这是我们在第 7 章“备选文件路径”中提到的 Rust 也能理解的旧命名约定。以此方式命名文件告诉 Rust 不要将 common 模块视为集成测试文件。当我们将 setup 函数代码移动到 tests/common/mod.rs 并删除 tests/common.rs 文件时,测试输出中的该部分将不再出现。tests 目录子目录中的文件不会被编译为独立的 crate,也不会在测试输出中拥有单独的部分。

This is the older naming convention that Rust also understands that we mentioned in “Alternate File Paths” in 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.

创建 tests/common/mod.rs 后,我们就可以在任何集成测试文件中将其作为一个模块来使用。这里有一个从 tests/integration_test.rs 中的 it_adds_two 测试调用 setup 函数的例子:

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:

文件名: tests/integration_test.rs

{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs}}

请注意,mod common; 声明与我们在示例 7-21 中演示的模块声明相同。然后,在测试函数中,我们可以调用 common::setup() 函数。

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.

二进制 crate 的集成测试 (Integration Tests for Binary Crates)

Integration Tests for Binary Crates

如果我们的项目是一个仅包含 src/main.rs 文件而不包含 src/lib.rs 文件的二进制 crate,我们就无法在 tests 目录中创建集成测试,也无法使用 use 语句将 src/main.rs 文件中定义的函数引入作用域。只有库 crate 会公开其他 crate 可以使用的函数;二进制 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.

这也是为什么提供二进制文件的 Rust 项目通常都有一个简单的 src/main.rs 文件,用于调用位于 src/lib.rs 文件中的逻辑。使用这种结构,集成测试“可以”通过 use 来测试库 crate,从而使重要功能可用。如果重要功能正常工作,src/main.rs 文件中的少量代码也将正常工作,且该少量代码无需测试。

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.

总结 (Summary)

Summary

Rust 的测试功能提供了一种指定代码应如何运行的方式,以确保即便你进行了更改,它仍能按你预期工作。单元测试分别行使库的不同部分,并可以测试私有实现细节。集成测试检查库的许多部分是否能正确地协同工作,并使用库的公有 API 以外部代码相同的方式测试代码。尽管 Rust 的类型系统和所有权规则有助于防止某些种类的 bug,测试对于减少与代码预期行为相关的逻辑 bug 仍然很重要。

Rust’s testing features provide a way to specify how code should function to ensure that 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.

让我们结合你在本章及前几章学到的知识来开展一个项目吧!

Let’s combine the knowledge you learned in this chapter and in previous chapters to work on a project!

一个 I/O 项目:构建命令行程序 (An I/O Project: Building a Command Line Program)


x-i18n: generated_at: “2026-03-01T14:12:42Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 0558d29b101abf718e8944d8ac3687282579dbdc1e3626c3eb2c18f9badf1495 source_path: ch12-00-an-io-project.md workflow: 16

I/O 项目:构建命令行程序 (An I/O Project: Building a Command Line Program)

An I/O Project: Building a Command Line Program

本章是对你目前所学技能的回顾,也是对一些标准库功能的探索。我们将构建一个与文件和命令行输入/输出交互的命令行工具,以练习你已经掌握的一些 Rust 概念。

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 的速度、安全性、单一二进制输出以及跨平台支持使其成为创建命令行工具的理想语言,因此在我们的项目中,我们将制作我们自己的经典命令行搜索工具 grep (globally search a regular expression and print) 版本。在最简单的使用案例中,grep 在指定文件中搜索指定的字符串。为此,grep 将文件路径和字符串作为其参数。然后,它读取文件,查找该文件中包含字符串参数的行,并打印这些行。

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.

在此过程中,我们将展示如何让我们的命令行工具使用许多其他命令行工具使用的终端功能。我们将读取环境变量的值,以允许用户配置我们工具的行为。我们还将把错误消息打印到标准错误控制台流 (stderr) 而不是标准输出 (stdout),以便用户可以将成功输出重定向到文件,同时仍能在屏幕上看到错误消息。

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 that, for example, the user can redirect successful output to a file while still seeing error messages onscreen.

Rust 社区成员 Andrew Gallant 已经创建了一个功能齐全、速度极快的 grep 版本,称为 ripgrep。相比之下,我们的版本将相当简单,但本章将为你提供理解 ripgrep 等实际项目所需的一些背景知识。

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.

我们的 grep 项目将结合你目前学到的一系列概念:

Our grep project will combine a number of concepts you’ve learned so far:

我们还将简要介绍闭包 (closures)、迭代器 (iterators) 和特征对象 (trait objects),第 13 章第 18 章 将对这些内容进行详细介绍。

We’ll also briefly introduce closures, iterators, and trait objects, which Chapter 13 and Chapter 18 will cover in detail.

接受命令行参数 (Accepting Command Line Arguments)


x-i18n: generated_at: “2026-03-01T14:13:42Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 79feeecffe1076f3555c8459e5bec4db9b257a0d7f471bb55fd7a2cfa3414dfc source_path: ch12-01-accepting-command-line-arguments.md workflow: 16

接收命令行参数 (Accepting Command Line Arguments)

Accepting Command Line Arguments

让我们像往常一样使用 cargo new 创建一个新项目。我们将项目命名为 minigrep,以便将其与你系统中可能已经存在的 grep 工具区分开来:

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
     Created binary (application) `minigrep` project
$ cd minigrep

第一个任务是让 minigrep 接收它的两个命令行参数:文件路径和要搜索的字符串。也就是说,我们希望能够用 cargo run 运行我们的程序,用两个连字符表示后面的参数是给我们的程序而不是给 cargo 的,接着是要搜索的字符串和要搜索的文件路径,如下所示:

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:

$ cargo run -- searchstring example-filename.txt

目前,由 cargo new 生成的程序无法处理我们给它的参数。一些存在于 crates.io 上的库可以帮助编写接收命令行参数的程序,但由于你才刚刚学习这个概念,让我们自己实现这个功能。

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.

读取参数值 (Reading the Argument Values)

Reading the Argument Values

为了使 minigrep 能够读取我们传递给它的命令行参数的值,我们需要 Rust 标准库提供的 std::env::args 函数。此函数返回传递给 minigrep 的命令行参数的迭代器。我们将在第 13 章中全面介绍迭代器。目前,你只需要了解关于迭代器的两个细节:迭代器产生一系列值,我们可以对迭代器调用 collect 方法将其转换为集合(例如向量),其中包含迭代器产生的所有元素。

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, which contains all the elements the iterator produces.

示例 12-1 中的代码允许你的 minigrep 程序读取任何传递给它的命令行参数,然后将这些值收集到一个向量中。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-01/src/main.rs}}
}

首先,我们通过 use 语句将 std::env 模块引入作用域,以便我们可以使用它的 args 函数。注意 std::env::args 函数嵌套在两层模块中。正如我们在第 7 章中讨论的那样,在所需的函数嵌套在多层模块中的情况下,我们选择将父模块引入作用域而不是函数本身。通过这样做,我们可以轻松地使用 std::env 中的其他函数。这也比添加 use std::env::args 然后仅使用 args 调用函数更不容易产生歧义,因为 args 很容易被误认为是当前模块中定义的函数。

First, we bring the std::env module into scope with a use statement so that 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.

args 函数与无效 Unicode

The args Function and Invalid Unicode

注意,如果任何参数包含无效的 Unicode,std::env::args 将引发恐慌。如果你的程序需要接受包含无效 Unicode 的参数,请改用 std::env::args_os。该函数返回一个迭代器,产生 OsString 值而不是 String 值。为了简单起见,我们在这里选择使用 std::env::args,因为 OsString 值因平台而异,处理起来比 String 值更复杂。

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.

main 的第一行,我们调用 env::args ,并立即使用 collect 将迭代器转换为包含迭代器产生的所有值的向量。我们可以使用 collect 函数创建多种集合,因此我们显式标注 args 的类型,指定我们需要一个字符串向量。虽然在 Rust 中你很少需要标注类型,但 collect 是你经常需要标注的一个函数,因为 Rust 无法推断出你想要的集合种类。

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 you 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.

最后,我们使用调试宏打印该向量。让我们先尝试不带参数运行代码,然后带两个参数运行:

Finally, we print the vector using the debug macro. Let’s try running the code first with no arguments and then with two arguments:

{{#include ../listings/ch12-an-io-project/listing-12-01/output.txt}}
{{#include ../listings/ch12-an-io-project/output-only-01-with-args/output.txt}}

请注意,向量中的第一个值是 "target/debug/minigrep",这是我们二进制文件的名称。这与 C 语言中参数列表的行为一致,允许程序在执行中使用被调用的名称。如果你想在消息中打印程序名称或根据用于调用程序的命令行别名更改程序的行为,能够访问程序名称通常很方便。但就本章而言,我们将忽略它,只保存我们需要的两个参数。

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 the 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.

在变量中保存参数值 (Saving the Argument Values in Variables)

Saving the Argument Values in Variables

程序目前能够访问指定为命令行参数的值。现在我们需要将这两个参数的值保存到变量中,以便在程序的其余部分使用这些值。我们在示例 12-2 中这样做。

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 that we can use the values throughout the rest of the program. We do that in Listing 12-2.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-02/src/main.rs}}

正如我们在打印向量时看到的,程序的名称占据了向量中 args[0] 的第一个值,所以我们从索引 1 开始参数。minigrep 接收的第一个参数是我们要搜索的字符串,所以我们将第一个参数的引用放入变量 query 中。第二个参数将是文件路径,所以我们将第二个参数的引用放入变量 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.

我们临时打印这些变量的值,以证明代码按我们的意图运行。让我们再次使用参数 testsample.txt 运行此程序:

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:

{{#include ../listings/ch12-an-io-project/listing-12-02/output.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)


x-i18n: generated_at: “2026-03-01T14:14:40Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 43a390d84480ff0f5ae94b422cc07a131b97784d6a0b9943f8401a235090b39c source_path: ch12-02-reading-a-file.md workflow: 16

读取文件 (Reading a File)

Reading a File

现在我们将添加读取 file_path 参数中指定的文件功能。首先,我们需要一个示例文件来测试它:我们将使用一个包含少量文本、分布在多行且有一些重复单词的文件。示例 12-3 中 Emily Dickinson 的一首诗会非常合适!在项目根目录下创建一个名为 poem.txt 的文件,并输入这首诗 “I’m Nobody! Who are you?”。

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?”

{{#include ../listings/ch12-an-io-project/listing-12-03/poem.txt}}

文本准备好后,编辑 src/main.rs 并添加读取文件的代码,如示例 12-4 所示。

With the text in place, edit src/main.rs and add code to read the file, as shown in Listing 12-4.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-04/src/main.rs:here}}

首先,我们通过 use 语句引入标准库的相关部分:我们需要 std::fs 来处理文件。

First, we bring in a relevant part of the standard library with a use statement: We need std::fs to handle files.

main 中,新语句 fs::read_to_string 接收 file_path ,打开该文件,并返回一个包含文件内容的 std::io::Result<String> 类型的值。

In main, the new statement fs::read_to_string takes the file_path, opens that file, and returns a value of type std::io::Result<String> that contains the file’s contents.

之后,我们再次添加了一条临时的 println! 语句,用于在文件读取后打印 contents 的值,以便检查程序目前的工作情况。

After that, we again add a temporary println! statement that prints the value of contents after the file is read so that we can check that the program is working so far.

让我们使用任意字符串作为第一个命令行参数(因为我们还没有实现搜索部分),并将 poem.txt 文件作为第二个参数来运行这段代码:

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:

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-04/output.txt}}

太棒了!代码读取并打印了文件内容。但代码有一些缺陷。目前,main 函数承担了多重职责:通常情况下,如果每个函数只负责一个概念,函数会更清晰且更易于维护。另一个问题是我们对错误的处理不够完善。程序目前还很小,所以这些缺陷不是大问题,但随着程序的增长,要干净地修复它们会变得更加困难。在开发程序时尽早开始重构是一个好习惯,因为重构少量代码要容易得多。接下来我们将进行重构。

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 a 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.

重构以改进模块化和错误处理 (Refactoring to Improve Modularity and Error Handling)


x-i18n: generated_at: “2026-03-01T14:16:27Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 51b686ec16b974ffef5494fbaaaf84342322f080cfe28764df78f682f13c6a9f source_path: ch12-03-improving-error-handling-and-modularity.md workflow: 16

重构以提高模块化和错误处理能力 (Refactoring to Improve Modularity and Error Handling)

Refactoring to Improve Modularity and Error Handling

为了改进我们的程序,我们将修复四个与程序结构及其处理潜在错误方式有关的问题。首先,我们的 main 函数现在执行两个任务:解析参数和读取文件。随着程序的增长,main 函数处理的独立任务数量将会增加。随着一个函数承担更多职责,它会变得更难以推理,更难以测试,并且更难在不破坏其中一部分的情况下进行更改。最好分离功能,使每个函数只负责一项任务。

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 that each function is responsible for one task.

这个问题也与第二个问题有关:虽然 queryfile_path 是程序的配置变量,但像 contents 这样的变量是用来执行程序逻辑的。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.

第三个问题是,我们使用了 expect 来在读取文件失败时打印错误消息,但错误消息只打印 Should have been able to read the file。读取文件可能以多种方式失败:例如,文件可能缺失,或者我们可能没有权限打开它。目前,无论情况如何,我们都会为所有事情打印相同的错误消息,这不会给用户任何信息!

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 来处理错误,如果用户在运行我们的程序时没有指定足够的参数,他们将从 Rust 得到一个 index out of bounds(索引越界)错误,这并不能清晰地解释问题。最好将所有的错误处理代码放在一个地方,这样如果错误处理逻辑需要更改,未来的维护者只需咨询一处代码。将所有的错误处理代码放在一个地方也将确保我们打印的消息对最终用户是有意义的。

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 that 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.

让我们通过重构我们的项目来解决这四个问题。

Let’s address these four problems by refactoring our project.

二进制项目中的关注点分离 (Separating Concerns in Binary Projects)

Separating Concerns in Binary Projects

把多个任务的责任分配给 main 函数的组织问题在许多二进制项目中都很常见。因此,许多 Rust 程序员发现在 main 函数开始变大时拆分二进制程序的独立关注点很有用。这个过程包含以下步骤:

The organizational problem of allocating responsibility for multiple tasks to the main function is common to many binary projects. As a result, many Rust programmers find it useful to split up the separate concerns of a binary program when the main function starts getting large. This process has the following steps:

  • 将你的程序拆分为一个 main.rs 文件和一个 lib.rs 文件,并将程序的逻辑移动到 lib.rs 中。

  • 只要你的命令行解析逻辑很小,它就可以留在 main 函数中。

  • 当命令行解析逻辑开始变得复杂时,将其从 main 函数中提取到其他函数或类型中。

  • Split your program into a main.rs file and a lib.rs file and move your program’s logic to lib.rs.

  • As long as your command line parsing logic is small, it can remain in the main function.

  • When the command line parsing logic starts getting complicated, extract it from the main function into other functions or types.

在此过程之后留在 main 函数中的职责应仅限于以下内容:

The responsibilities that remain in the main function after this process should be limited to the following:

  • 使用参数值调用命令行解析逻辑

  • 设置任何其他配置

  • 调用 lib.rs 中的 run 函数

  • 如果 run 返回错误,则处理错误

  • Calling the command line parsing logic with the argument values

  • Setting up any other configuration

  • Calling a run function in lib.rs

  • Handling the error if run returns an error

这种模式是关于关注点分离的:main.rs 处理运行程序,而 lib.rs 处理手头任务的所有逻辑。因为你不能直接测试 main 函数,所以这种结构让你通过将其移出 main 函数来测试程序的所有逻辑。留在 main 函数中的代码将足够小,可以通过阅读来验证其正确性。让我们按照这个过程重做我们的程序。

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 out of the main function. The code that remains in the main function will be small enough to verify its correctness by reading it. Let’s rework our program by following this process.

提取参数解析器 (Extracting the Argument Parser)

Extracting the Argument Parser

我们将把解析参数的功能提取到一个由 main 调用的函数中。示例 12-5 显示了 main 函数的新开头,它调用了一个新函数 parse_config,我们将在 src/main.rs 中定义该函数。

We’ll extract the functionality for parsing arguments into a function that main will call. Listing 12-5 shows the new start of the main function that calls a new function parse_config, which we’ll define in src/main.rs.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-05/src/main.rs:here}}

我们仍然将命令行参数收集到一个向量中,但不再是在 main 函数中将索引 1 处的参数值分配给变量 query 且将索引 2 处的参数值分配给变量 file_path,而是将整个向量传递给 parse_config 函数。parse_config 函数随后持有确定哪个参数对应哪个变量并传回给 main 的逻辑。我们仍在 main 中创建 queryfile_path 变量,但 main 不再负责确定命令行参数和变量如何对应。

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.

这种重做对于我们这个小程序来说可能看起来有些大材小用,但我们是在以小的、增量式的步骤进行重构。做出此更改后,再次运行程序以验证参数解析是否仍然正常工作。经常检查进度很有好处,有助于在问题发生时识别原因。

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)

Grouping Configuration Values

我们可以再迈出一小步来进一步改进 parse_config 函数。目前,我们返回的是一个元组,但随后我们立即再次将该元组分解为各个部分。这是一个迹象,表明我们可能还没有得到正确的抽象。

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_configconfig 部分,它暗示我们返回的两个值是相关的,并且都是一个配置值的一部分。目前,除了通过将两个值组合成一个元组之外,我们并没有在数据结构中传达这种含义;相反,我们将把这两个值放入一个结构体中,并给每个结构体字段起一个有意义的名称。这样做将使未来的代码维护者更容易理解不同值之间的关系以及它们的用途。

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.

示例 12-6 显示了对 parse_config 函数的改进。

Listing 12-6 shows the improvements to the parse_config function.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-06/src/main.rs:here}}

我们添加了一个名为 Config 的结构体,定义了名为 queryfile_path 的字段。parse_config 的签名现在表明它返回一个 Config 值。在 parse_config 的函数体中,我们以前返回引用 argsString 值的字符串切片,现在我们将 Config 定义为包含拥有的 String 值。main 中的 args 变量是参数值的所有者,并且仅允许 parse_config 函数借用它们,这意味着如果 Config 尝试获取 args 中值的所有权,我们将违反 Rust 的借用规则。

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.

我们可以通过多种方式管理 String 数据;最简单(虽然有些低效)的方法是在值上调用 clone 方法。这将为 Config 实例制作一份完整的数据副本以归其所有,这比存储对字符串数据的引用需要更多的时间和内存。然而,克隆数据也使我们的代码非常直观,因为我们不必管理引用的生命周期;在这种情况下,牺牲一点性能来换取简洁是值得的。

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.

使用 clone 的权衡

The Trade-Offs of Using clone

许多 Rustaceans 倾向于避免使用 clone 来修复所有权问题,因为它有运行时开销。在第 13 章中,你将学习在此类情况下如何使用更高效的方法。但现在,为了继续取得进展,复制几个字符串是可以的,因为你只需复制一次,而且你的文件路径和查询字符串都非常短。与其在第一次尝试时就过度优化代码,不如先得到一个虽然有点低效但可以工作的程序。随着你对 Rust 变得更有经验,开始使用最有效的解决方案会更容易,但目前,调用 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.

我们更新了 main ,使其将 parse_config 返回的 Config 实例放入名为 config 的变量中,并更新了以前使用单独的 queryfile_path 变量的代码,使其现在改为使用 Config 结构体上的字段。

We’ve updated main so that 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 that it now uses the fields on the Config struct instead.

现在我们的代码更清晰地传达了 queryfile_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.

Config 创建构造函数 (Creating a Constructor for Config)

Creating a Constructor for Config

到目前为止,我们已经从 main 中提取了负责解析命令行参数的逻辑,并将其放入了 parse_config 函数中。这样做帮助我们看到 queryfile_path 值是相关的,并且这种关系应该在我们的代码中体现出来。然后,我们添加了一个 Config 结构体来命名 queryfile_path 的相关用途,并能够从 parse_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 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.

既然 parse_config 函数的目的是创建一个 Config 实例,我们就可以将 parse_config 从一个普通的函数更改为一个名为 new 的与 Config 结构体关联的函数。做出此更改将使代码更符合惯例。我们可以通过调用 String::new 来创建标准库中类型(如 String)的实例。类似地,通过将 parse_config 更改为与 Config 关联的 new 函数,我们将能够通过调用 Config::new 来创建 Config 的实例。示例 12-7 显示了我们需要做的更改。

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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-07/src/main.rs:here}}

我们更新了 main 中以前调用 parse_config 的地方,改为调用 Config::new。我们将 parse_config 的名称更改为 new ,并将其移动到 impl 块中,该块将 new 函数与 Config 关联。尝试再次编译此代码以确保它能正常工作。

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.

修复错误处理 (Fixing the Error Handling)

Fixing the Error Handling

现在我们将致力于修复我们的错误处理。回想一下,如果向量包含的项少于三项,尝试访问 args 向量中索引 1 或索引 2 处的值将导致程序恐慌。尝试在没有任何参数的情况下运行该程序;它将看起来像这样:

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:

{{#include ../listings/ch12-an-io-project/listing-12-07/output.txt}}

index out of bounds: the len is 1 but the index is 1 是面向程序员的错误消息。它无法帮助我们的最终用户理解他们应该做些什么。让我们现在修复它。

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.

改进错误消息 (Improving the Error Message)

Improving the Error Message

在示例 12-8 中,我们在 new 函数中添加了一个检查,以便在访问索引 1 和索引 2 之前验证切片是否足够长。如果切片不够长,程序会引发恐慌并显示更好的错误消息。

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 index 2. If the slice isn’t long enough, the program panics and displays a better error message.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-08/src/main.rs:here}}

这段代码类似于我们在示例 9-13 中编写的 Guess::new 函数,我们在那里当 value 参数超出有效值范围时调用了 panic!。这里我们不是检查值的范围,而是检查 args 的长度是否至少为 3,并且函数的其余部分可以在此条件已满足的假设下运行。如果 args 少于三项,此条件将为 true,我们调用 panic! 宏立即结束程序。

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.

new 中增加了这几行代码后,让我们再次在没有任何参数的情况下运行该程序,看看现在的错误是什么样子的:

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:

{{#include ../listings/ch12-an-io-project/listing-12-08/output.txt}}

这个输出更好:我们现在有了一个合理的错误消息。但是,我们也有一些不希望提供给用户多余信息。也许我们在示例 9-13 中使用的技术并不是这里最好的选择:正如在第 9 章中讨论的,调用 panic! 对于编程问题比对于用法问题更合适。相反,我们将使用你在第 9 章中学到的另一种技术——返回一个 Result,它指示成功或错误。

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 the technique we used in Listing 9-13 isn’t the best one 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.

返回 Result 而不是调用 panic! (Returning a Result Instead of Calling panic!)

Returning a Result Instead of Calling panic!

我们可以转而返回一个 Result 值,该值在成功的情况下包含一个 Config 实例,在错误的情况下描述问题。我们还要将函数名从 new 更改为 build ,因为许多程序员期望 new 函数永远不会失败。当 Config::buildmain 通信时,我们可以使用 Result 类型来发出出现问题的信号。然后,我们可以更改 main ,将 Err 变体转换为对我们的用户更实用的错误,而不会有调用 panic! 所导致的关于 thread 'main'RUST_BACKTRACE 的环绕文本。

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.

示例 12-9 显示了我们需要对现在调用的函数 Config::build 的返回值所做的更改,以及返回 Result 所需的函数体。注意,在我们也更新 main 之前(我们将在下一个列表中完成),这段代码将无法编译。

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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-09/src/main.rs:here}}

我们的 build 函数在成功的情况下返回带有 Config 实例的 Result ,在错误的情况下返回字符串字面量。我们的错误值始终是具有 'static 生命周期的字符串字面量。

Our build function returns a Result with a Config instance in the success case and a string literal in the error case. Our error values will always be string literals that have the 'static lifetime.

我们在函数体中做了两处更改:当用户没有传递足够的参数时,我们现在返回一个 Err 值而不是调用 panic!,并且我们将 Config 返回值包裹在了 Ok 中。这些更改使该函数符合其新的类型签名。

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.

Config::build 返回 Err 值允许 main 函数处理从 build 函数返回的 Result 值,并在错误的情况下更干净地退出进程。

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 并处理错误 (Calling Config::build and Handling Errors)

Calling Config::build and Handling Errors

为了处理错误情况并打印用户友好的消息,我们需要更新 main 以处理由 Config::build 返回的 Result,如示例 12-10 所示。我们还将承担起使用非零错误代码退出命令行工具的职责,将其从 panic! 中拿走并改为手动实现。非零退出状态是向调用我们程序的进程发出信号的惯例,表明程序以错误状态退出。

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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-10/src/main.rs:here}}

在此列表中,我们使用了一个尚未详细介绍的方法:unwrap_or_else,它由标准库在 Result<T, E> 上定义。使用 unwrap_or_else 允许我们定义一些自定义的、非 panic! 的错误处理。如果 Result 是一个 Ok 值,此方法的行为类似于 unwrap:它返回 Ok 包裹的内部值。然而,如果值是一个 Err 值,此方法将调用闭包(closure)中的代码,闭包是我们定义并作为参数传递给 unwrap_or_else 的匿名函数。我们将在第 13 章中更详细地介绍闭包。目前,你只需要知道 unwrap_or_else 会将 Err 的内部值(在此例中是我们在示例 12-9 中添加的静态字符串 "not enough arguments")传递给出现在垂直线之间的参数 err 所代表的闭包。闭包中的代码随后可以在运行时使用 err 值。

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 that 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.

我们添加了一条新的 use 行,将标准库中的 process 引入作用域。在错误情况下将运行的闭包中的代码只有两行:我们打印 err 值,然后调用 process::exitprocess::exit 函数将立即停止程序并返回传递给它的数字作为退出状态代码。这类似于我们在示例 12-8 中使用的基于 panic! 的处理,但我们不再获得所有额外的输出。让我们试一试:

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:

{{#include ../listings/ch12-an-io-project/listing-12-10/output.txt}}

太棒了!这个输出对我们的用户友好得多。

Great! This output is much friendlier for our users.

main 函数中提取逻辑 (Extracting Logic from main)

Extracting Logic from main

既然我们已经完成了对配置解析的重构,现在让我们转向程序的逻辑。正如我们在“二进制项目中的关注点分离”中所述,我们将提取一个名为 run 的函数,该函数将持有目前 main 函数中除配置设置或处理错误之外的所有逻辑。完成后,main 函数将简洁且易于通过检查进行验证,并且我们将能够为所有其他逻辑编写测试。

Now that we’ve finished refactoring the configuration parsing, let’s turn to the program’s logic. As we stated in “Separating Concerns in 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, the main function will be concise and easy to verify by inspection, and we’ll be able to write tests for all the other logic.

示例 12-11 显示了提取 run 函数这一小的、增量式的改进。

Listing 12-11 shows the small, incremental improvement of extracting a run function.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-11/src/main.rs:here}}

run 函数现在包含 main 中从读取文件开始的所有剩余逻辑。run 函数接收 Config 实例作为参数。

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 函数返回错误 (Returning Errors from run)

Returning Errors from run

随着剩余的程序逻辑被分离到 run 函数中,我们可以改进错误处理,就像我们在示例 12-9 中对 Config::build 所做的那样。run 函数将在出现问题时返回 Result<T, E>,而不是通过调用 expect 允许程序恐慌。这将让我们能进一步以用户友好的方式将处理错误的逻辑合并到 main 中。示例 12-12 显示了我们需要对 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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-12/src/main.rs:here}}

我们在这里做了三处重大更改。首先,我们将 run 函数的返回类型更改为 Result<(), Box<dyn Error>>。此函数以前返回单元类型 (),我们将其保留为 Ok 情况下返回的值。

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.

对于错误类型,我们使用了特征对象 Box<dyn Error>(并在顶部通过 use 语句将 std::error::Error 引入了作用域)。我们将在第 18 章介绍特征对象。目前,只需知道 Box<dyn Error> 意味着函数将返回一个实现了 Error 特征的类型,但我们不必指定具体的返回值的类型。这使我们能灵活地在不同的错误情况下返回可能属于不同类型的错误值。关键字 dyndynamic 的缩写。

For the error type, we used the trait object Box<dyn Error> (and we brought std::error::Error into scope with a use statement at the top). We’ll cover trait objects in Chapter 18. 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.

其次,我们删除了对 expect 的调用,转而使用 ? 运算符,正如我们在第 9 章中讨论的那样。? 不会在错误时引发 panic!,而是将错误值从当前函数返回,供调用者处理。

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.

第三,run 函数现在在成功的情况下返回一个 Ok 值。我们在签名中将 run 函数的成功类型声明为 (),这意味着我们需要将单元类型值包裹在 Ok 值中。这种 Ok(()) 语法起初看起来可能有点奇怪。但像这样使用 () 是指示我们仅因其副作用而调用 run 的惯用方式;它不会返回我们需要的值。

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.

当你运行这段代码时,它将可以编译但会显示一个警告:

When you run this code, it will compile but will display a warning:

{{#include ../listings/ch12-an-io-project/listing-12-12/output.txt}}

Rust 告诉我们,我们的代码忽略了 Result 值,而 Result 值可能表明发生了错误。但我们没有检查是否有错误,编译器提醒我们大概的意思是应该在这里有一些错误处理代码!现在让我们纠正这个问题。

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.

处理 main 中从 run 返回的错误 (Handling Errors Returned from run in main)

Handling Errors Returned from run in main

我们将检查错误并使用与示例 12-10 中 Config::build 使用的技术类似的方法来处理它们,但有一点细微的区别:

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:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs:here}}

我们使用 if let 而不是 unwrap_or_else 来检查 run 是否返回 Err 值,如果是则调用 process::exit(1)run 函数并不像 Config::build 返回 Config 实例那样返回一个我们想要 unwrap 的值。因为 run 在成功的情况下返回 (),我们只关心检测错误,所以我们不需要 unwrap_or_else 返回解包后的值,因为那只会是 ()

We use if let rather than unwrap_or_else to check whether run returns an Err value and to 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 函数体在两种情况下都是相同的:我们打印错误并退出。

The bodies of the if let and the unwrap_or_else functions are the same in both cases: We print the error and exit.

将代码拆分为库 crate (Splitting Code into a Library Crate)

Splitting Code into a Library Crate

我们的 minigrep 项目目前看起来不错!现在我们将拆分 src/main.rs 文件并将一些代码放入 src/lib.rs 文件中。这样,我们就可以测试代码,并让 src/main.rs 文件承担更少的责任。

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.

让我们在 src/lib.rs 而不是 src/main.rs 中定义负责搜索文本的代码,这将让我们(或任何其他使用我们的 minigrep 库的人)能够比从我们的 minigrep 二进制文件中在更多上下文中调用搜索函数。

Let’s define the code responsible for searching text in src/lib.rs rather than in src/main.rs, which will let us (or anyone else using our minigrep library) call the searching function from more contexts than our minigrep binary.

首先,让我们在 src/lib.rs 中定义 search 函数签名,如示例 12-13 所示,其函数体调用 unimplemented! 宏。当我们填充实现时,我们将更详细地解释该签名。

First, let’s define the search function signature in src/lib.rs as shown in Listing 12-13, with a body that calls the unimplemented! macro. We’ll explain the signature in more detail when we fill in the implementation.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-13/src/lib.rs}}

我们在函数定义上使用了 pub 关键字,将 search 指定为我们库 crate 公有 API 的一部分。现在我们有了一个可以在二进制 crate 中使用并可以测试的库 crate!

We’ve used the pub keyword on the function definition to designate search as part of our library crate’s public API. We now have a library crate that we can use from our binary crate and that we can test!

现在我们需要将在 src/lib.rs 中定义的代码引入 src/main.rs 中二进制 crate 的作用域,并调用它,如示例 12-14 所示。

Now we need to bring the code defined in src/lib.rs into the scope of the binary crate in src/main.rs and call it, as shown in Listing 12-14.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-14/src/main.rs:here}}

我们添加了一行 use minigrep::search ,将搜索函数从库 crate 引入二进制 crate 的作用域。然后,在 run 函数中,我们不再打印文件的内容,而是调用 search 函数并将 config.query 值和 contents 作为参数传递。然后,run 将使用 for 循环打印从 search 返回的与查询匹配的每一行。现在也是删除 main 函数中显示查询和文件路径的 println! 调用的好时机,这样我们的程序就只打印搜索结果(如果未发生错误)。

We add a use minigrep::search line to bring the search function from the library crate into the binary crate’s scope. Then, in the run function, rather than printing out the contents of the file, we call the search function and pass the config.query value and contents as arguments. Then, run will use a for loop to print each line returned from search that matched the query. This is also a good time to remove the println! calls in the main function that displayed the query and the file path so that our program only prints the search results (if no errors occur).

请注意,搜索函数将在进行任何打印之前将其返回的所有结果收集到一个向量中。搜索大文件时,此实现可能导致显示结果的速度很慢,因为结果不是在找到时就打印出来的;我们将在第 13 章讨论使用迭代器修复此问题的可能方法。

Note that the search function will be collecting all the results into a vector it returns before any printing happens. This implementation could be slow to display results when searching large files, because results aren’t printed as they’re found; we’ll discuss a possible way to fix this using iterators in Chapter 13.

呼!做了很多工作,但我们已经为将来的成功奠定了基础。现在处理错误要容易得多,而且我们使代码更具模块化。从现在开始,几乎我们所有的工作都将在 src/lib.rs 中完成。

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.

让我们利用这种新获得的模块化,做一些在旧代码中很难但在新代码中很容易的事情:我们将编写一些测试!

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!

通过测试驱动开发添加功能 (Adding Functionality with Test Driven Development)


x-i18n: generated_at: “2026-03-01T14:16:54Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 82cdffa0023c7c3a3a8a8f5658cf305e09f123c1e5b08713d1a19ebda80a3582 source_path: ch12-04-testing-the-librarys-functionality.md workflow: 16

使用测试驱动开发添加功能 (Adding Functionality with Test-Driven Development)

Adding Functionality with Test-Driven Development

既然我们将 src/lib.rs 中的搜索逻辑与 main 函数分开了,为我们代码的核心功能编写测试就容易得多了。我们可以直接使用各种参数调用函数并检查返回值,而不必从命令行调用我们的二进制文件。

Now that we have the search logic in src/lib.rs separate from the main function, 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.

在本节中,我们将使用测试驱动开发 (TDD) 过程为 minigrep 程序添加搜索逻辑,步骤如下:

In this section, we’ll add the searching logic to the minigrep program using the test-driven development (TDD) process with the following steps:

  1. 编写一个失败的测试并运行它,以确保它因你预期的原因而失败。

  2. 编写或修改刚好足够让新测试通过的代码。

  3. 重构你刚刚添加或更改的代码,并确保测试继续通过。

  4. 从第 1 步重复!

  5. Write a test that fails and run it to make sure it fails for the reason you expect.

  6. Write or modify just enough code to make the new test pass.

  7. Refactor the code you just added or changed and make sure the tests continue to pass.

  8. Repeat from step 1!

虽然 TDD 只是众多编写软件的方法之一,但它有助于推动代码设计。在编写让测试通过的代码之前编写测试,有助于在整个过程中保持高测试覆盖率。

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 maintain high test coverage throughout the process.

我们将通过测试驱动来实现真正执行在文件内容中搜索查询字符串并生成匹配查询的行列表的功能。我们将在一个名为 search 的函数中添加此功能。

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.

编写一个失败的测试 (Writing a Failing Test)

Writing a Failing Test

src/lib.rs 中,我们将添加一个带有测试函数的 tests 模块,就像我们在第 11 章中所做的那样。测试函数指定了我们希望 search 函数具有的行为:它将接收一个查询和要搜索的文本,并仅返回文本中包含该查询的行。示例 12-15 展示了这个测试。

In src/lib.rs, we’ll 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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-15/src/lib.rs:here}}

此测试搜索字符串 "duct" 。我们要搜索的文本有三行,其中只有一行包含 "duct"(注意开头的双引号后的反斜杠告诉 Rust 不要在这个字符串字面量内容的开头放入换行符)。我们断言从 search 函数返回的值仅包含我们期望的那一行。

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.

如果我们运行此测试,它目前会失败,因为 unimplemented! 宏会引发带有 “not implemented” 消息的恐慌。根据 TDD 原则,我们将采取一小步,通过将 search 函数定义为始终返回一个空向量,来添加刚好足够的代码使调用该函数时测试不引发恐慌,如示例 12-16 所示。然后,测试应该能够编译,并且由于空向量不匹配包含行 "safe, fast, productive." 的向量而失败。

If we run this test, it will currently fail because the unimplemented! macro panics with the message “not implemented”. In accordance with TDD principles, we’ll take a small step of adding just enough code to get the test to not panic when calling the function by defining the search function to always return 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.".

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-16/src/lib.rs:here}}

现在让我们讨论为什么我们需要在 search 的签名中定义显式生命周期 'a ,并将该生命周期用于 contents 参数和返回值。回想第 10 章,生命周期参数指定哪个参数的生命周期与返回值的生命周期相连。在这种情况下,我们指出返回的向量应包含引用参数 contents 切片(而不是参数 query)的字符串切片。

Now let’s discuss why 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).

换句话说,我们告诉 Rust,由 search 函数返回的数据将与通过 contents 参数传递给 search 函数的数据活得一样长。这很重要!由切片引用的数据需要有效,引用才有效;如果编译器假设我们制作的是 query 而不是 contents 的字符串切片,它将错误地执行其安全检查。

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.

如果我们忘记了生命周期标注并尝试编译此函数,我们将得到此错误:

If we forget the lifetime annotations and try to compile this function, we’ll get this error:

{{#include ../listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt}}

Rust 无法知道输出需要两个参数中的哪一个,所以我们需要显式告诉它。请注意,帮助文本建议为所有参数和输出类型指定相同的生命周期参数,这是不正确的!因为 contents 是包含我们所有文本的参数,并且我们想返回该文本中匹配的部分,所以我们知道 contents 是唯一应该使用生命周期语法连接到返回值的参数。

Rust can’t know which of the two parameters we need for the output, so we need to tell it explicitly. Note that the help text suggests specifying the same lifetime parameter for all the parameters and the output type, which is incorrect! Because contents is the parameter that contains all of our text and we want to return the parts of that text that match, we know contents is the only parameter that should be connected to the return value using the lifetime syntax.

其他编程语言不要求你在签名中将参数连接到返回值,但这种实践会随着时间的推移变得容易。你可能想将此示例与第 10 章“使用生命周期验证引用”部分中的示例进行比较。

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 examples in the “Validating References with Lifetimes” section in Chapter 10.

编写代码以通过测试 (Writing Code to Pass the Test)

Writing Code to Pass the Test

目前,我们的测试失败是因为我们始终返回一个空向量。为了修复该问题并实现 search ,我们的程序需要遵循以下步骤:

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:

  1. 遍历内容的每一行。

  2. 检查该行是否包含我们的查询字符串。

  3. 如果包含,将其添加到我们要返回的值列表中。

  4. 如果不包含,什么都不做。

  5. 返回匹配的结果列表。

  6. Iterate through each line of the contents.

  7. Check whether the line contains our query string.

  8. If it does, add it to the list of values we’re returning.

  9. If it doesn’t, do nothing.

  10. Return the list of results that match.

让我们逐一完成每个步骤,从遍历行开始。

Let’s work through each step, starting with iterating through lines.

使用 lines 方法遍历行 (Iterating Through Lines with the lines Method)

Iterating Through Lines with the lines Method

Rust 有一个有用的方法来处理字符串的逐行遍历,它的名字很方便,叫 lines ,其用法如示例 12-17 所示。注意这目前还无法编译。

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 that this won’t compile yet.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-17/src/lib.rs:here}}

lines 方法返回一个迭代器。我们将在第 13 章中深入探讨迭代器。但回想一下你在示例 3-5中见过这种使用迭代器的方式,我们在那里使用带迭代器的 for 循环在集合的每一项上运行一些代码。

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.

在每一行中搜索查询字符串 (Searching Each Line for the Query)

Searching Each Line for the Query

接下来,我们将检查当前行是否包含我们的查询字符串。幸运的是,字符串有一个名为 contains 的有用方法可以为我们完成此任务!在 search 函数中添加对 contains 方法的调用,如示例 12-18 所示。请注意,这仍然无法编译。

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 that this still won’t compile yet.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-18/src/lib.rs:here}}

目前,我们正在构建功能。为了让代码通过编译,我们需要像函数签名中所指示的那样,从函数体返回一个值。

At the moment, we’re building up functionality. To get the code to compile, we need to return a value from the body as we indicated we would in the function signature.

存储匹配的行 (Storing Matching Lines)

Storing Matching Lines

为了完成此函数,我们需要一种方法来存储我们要返回的匹配行。为此,我们可以在 for 循环之前创建一个可变向量,并调用 push 方法将 line 存储在向量中。在 for 循环之后,我们返回该向量,如示例 12-19 所示。

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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-19/src/lib.rs:here}}

现在 search 函数应该只返回包含 query 的行,并且我们的测试应该通过。让我们运行测试:

Now the search function should return only the lines that contain query, and our test should pass. Let’s run the test:

{{#include ../listings/ch12-an-io-project/listing-12-19/output.txt}}

我们的测试通过了,所以我们知道它有效!

Our test passed, so we know it works!

此时,我们可以考虑在保持测试通过以维持相同功能的同时,重构搜索函数的实现。搜索函数中的代码还不算太差,但它没有利用迭代器的一些有用功能。我们将在第 13 章中回到这个示例,在那里我们将详细探索迭代器,并看看如何改进它。

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.

现在整个程序应该可以工作了!让我们尝试一下,首先用一个应该从 Emily Dickinson 的诗中返回恰好一行的单词:frog

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.

{{#include ../listings/ch12-an-io-project/no-listing-02-using-search-in-run/output.txt}}

酷!现在让我们尝试一个匹配多行的单词,比如 body

Cool! Now let’s try a word that will match multiple lines, like body:

{{#include ../listings/ch12-an-io-project/output-only-03-multiple-matches/output.txt}}

最后,让我们确保在搜索诗中任何地方都没有的单词(例如 monomorphization )时,不会得到任何行:

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:

{{#include ../listings/ch12-an-io-project/output-only-04-no-matches/output.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)


x-i18n: generated_at: “2026-03-01T14:17:51Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 83185725d64339fa71448b45152abf9cc2c5efb33db6aacda25de9d5b7b456b5 source_path: ch12-05-working-with-environment-variables.md workflow: 16

使用环境变量 (Working with Environment Variables)

Working with Environment Variables

我们将通过添加一个额外的功能来改进 minigrep 二进制文件:一个用户可以通过环境变量开启的区分大小写搜索选项。我们可以将此功能设为命令行选项,并要求用户每次想应用它时都输入它,但通过将其设为环境变量,我们允许我们的用户设置一次环境变量,并在该终端会话中让他们的所有搜索都不区分大小写。

We’ll improve the minigrep binary 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 库添加一个新的 search_case_insensitive 函数,该函数将在环境变量有值时被调用。我们将继续遵循 TDD 过程,所以第一步再次是编写一个失败的测试。我们将为新的 search_case_insensitive 函数添加一个新测试,并将旧测试从 one_result 重命名为 case_sensitive ,以阐明两个测试之间的区别,如示例 12-20 所示。

We first add a new search_case_insensitive function to the minigrep library 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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-20/src/lib.rs:here}}

请注意,我们也编辑了旧测试的 contents 。我们添加了一个带有文本 "Duct tape." 的新行,其使用了大写字母 D,当我们以区分大小写的方式搜索查询 "duct" 时,它不应该匹配。以这种方式更改旧测试有助于确保我们不会意外破坏已经实现的区分大小写搜索功能。这个测试现在应该通过,并且在我们开发不区分大小写搜索时也应该继续通过。

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.

新的“不”区分大小写搜索测试使用 "rUsT" 作为其查询。在我们将要添加的 search_case_insensitive 函数中,查询 "rUsT" 应该匹配包含大写字母 R"Rust:" 这一行,并匹配 "Trust me." 这一行,尽管两者的拼写大小写与查询不同。这是我们的失败测试,因为它会编译失败,因为我们尚未定义 search_case_insensitive 函数。随意添加一个始终返回空向量的骨架实现,类似于我们在示例 12-16 中为 search 函数所做的那样,以观察测试的编译和失败。

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.

实现 search_case_insensitive 函数 (Implementing the search_case_insensitive Function)

Implementing the search_case_insensitive Function

示例 12-21 所示的 search_case_insensitive 函数将与 search 函数几乎相同。唯一的区别是我们将 query 和每一行 line 都转换为小写,这样无论输入参数的大小写如何,在检查该行是否包含查询时,它们的大小写都是相同的。

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 that whatever the case of the input arguments, they’ll be the same case when we check whether the line contains the query.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-21/src/lib.rs:here}}

首先,我们将 query 字符串转换为小写,并将其存储在同名的新变量中,从而遮蔽原始的 query 。在查询上调用 to_lowercase 是必要的,这样无论用户的查询是 "rust""RUST""Rust" 还是 "rUsT",我们都会将查询视为 "rust" 且对大小写不敏感。虽然 to_lowercase 会处理基础 Unicode,但它不会百分之百准确。如果我们正在编写一个真正的应用程序,我们会想在这里做更多的工作,但本节是关于环境变量的,而不是关于 Unicode 的,所以我们在这里点到为止。

First, we lowercase the query string and store it in a new variable with the same name, shadowing the original query. Calling to_lowercase on the query is necessary so that 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 percent 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 现在是 String 而不是字符串切片,因为调用 to_lowercase 创建了新数据而不是引用现有数据。以查询 "rUsT" 为例:该字符串切片不包含供我们使用的小写 ut,因此我们必须分配一个新的包含 "rust"String 。当现在将 query 作为参数传递给 contains 方法时,我们需要添加一个 & 符号,因为 contains 的签名被定义为接收一个字符串切片。

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.

接下来,我们在每一行 line 上添加一个对 to_lowercase 的调用,将所有字符转换为小写。既然我们已经将 linequery 转换为了小写,那么无论查询的大小写如何,我们都会找到匹配项。

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.

让我们看看这个实现是否通过了测试:

Let’s see if this implementation passes the tests:

{{#include ../listings/ch12-an-io-project/listing-12-21/output.txt}}

太棒了!它们通过了。现在让我们从 run 函数中调用新的 search_case_insensitive 函数。首先,我们将向 Config 结构体添加一个配置选项,以便在区分大小写和不区分大小写的搜索之间切换。添加此字段将导致编译器错误,因为我们尚未在任何地方初始化此字段:

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:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-22/src/main.rs:here}}

我们添加了持有布尔值的 ignore_case 字段。接下来,我们需要 run 函数检查 ignore_case 字段的值,并使用它来决定调用 search 函数还是 search_case_insensitive 函数,如示例 12-22 所示。这目前还无法编译。

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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-22/src/main.rs:there}}

最后,我们需要检查环境变量。用于处理环境变量的函数位于标准库的 env 模块中,该模块已经在 src/main.rs 的顶部被引入作用域。我们将使用 env 模块中的 var 函数来检查是否为名为 IGNORE_CASE 的环境变量设置了任何值,如示例 12-23 所示。

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, which is already in scope at the top of src/main.rs. We’ll use the var function from the env module to check to see if any value has been set for an environment variable named IGNORE_CASE, as shown in Listing 12-23.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-23/src/main.rs:here}}

在这里,我们创建了一个新变量 ignore_case 。为了设置它的值,我们调用 env::var 函数并将环境变量的名称 IGNORE_CASE 传递给它。如果环境变量被设置为任何值,env::var 函数将返回成功的 Ok 变体,其中包含该环境变量的值。如果环境变量未设置,它将返回 Err 变体。

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.

我们正在使用 Result 上的 is_ok 方法来检查是否设置了环境变量,这意味着程序应该执行不区分大小写的搜索。如果 IGNORE_CASE 环境变量未被设置,is_ok 将返回 false ,程序将执行区分大小写的搜索。我们不关心环境变量的“值”,只关心它是已设置还是未设置,所以我们检查的是 is_ok 而不是使用 unwrapexpect 或我们在 Result 上看到的任何其他方法。

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.

我们将 ignore_case 变量中的值传递给 Config 实例,以便 run 函数可以读取该值并决定调用 search_case_insensitive 还是 search ,正如我们在示例 12-22 中实现的那样。

We pass the value in the ignore_case variable to the Config instance so that the run function can read that value and decide whether to call search_case_insensitive or search, as we implemented in Listing 12-22.

让我们试一试!首先,我们在未设置环境变量的情况下运行程序,并使用查询 to ,它应该匹配任何包含全小写单词 to 的行:

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:

{{#include ../listings/ch12-an-io-project/listing-12-23/output.txt}}

看起来依然正常工作!现在让我们在设置 IGNORE_CASE1 的情况下运行程序,但使用相同的查询 to

$ IGNORE_CASE=1 cargo run -- to poem.txt

如果你正在使用 PowerShell,你需要将设置环境变量和运行程序作为单独的命令执行:

If you’re using PowerShell, you will need to set the environment variable and run the program as separate commands:

PS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt

这将使 IGNORE_CASE 在你当前的 shell 会话剩余时间内保持生效。可以使用 Remove-Item cmdlet 将其取消设置:

PS> Remove-Item Env:IGNORE_CASE

我们应该得到包含 to 且可能包含大写字母的行:

Are you nobody, too?
How dreary to be somebody!
To tell your name the livelong day
To an admiring bog!

优秀,我们也得到了包含 To 的行!我们的 minigrep 程序现在可以通过由环境变量控制来执行不区分大小写的搜索。现在你已经了解了如何管理使用命令行参数或环境变量设置的选项。

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.

有些程序允许为相同的配置设置参数“和”环境变量。在这些情况下,程序会决定哪一个具有优先级。作为你自己的另一个练习,尝试通过命令行参数或环境变量来控制大小写敏感性。如果程序在运行时一个设置为区分大小写而另一个设置为忽略大小写,请决定是命令行参数还是环境变量应具有优先级。

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.

std::env 模块包含了更多处理环境变量的有用的功能:查阅其文档以了解有哪些可用功能。

The std::env module contains many more useful features for dealing with environment variables: Check out its documentation to see what is available.

将错误重定向到标准错误 (Redirecting Errors to Standard Error)


x-i18n: generated_at: “2026-03-01T14:18:40Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f61a0dce702794c35688c89b09a7b5db6b91769a3d65ce1b53d45d84b2202ffb source_path: ch12-06-writing-to-stderr-instead-of-stdout.md workflow: 16

将错误重定向到标准错误 (Redirecting Errors to Standard Error)

Redirecting Errors to Standard Error

目前,我们正使用 println! 宏将所有输出写入终端。在大多数终端中,有两种输出:用于一般信息的“标准输出 (standard output,stdout)”和用于错误消息的“标准错误 (standard error,stderr)”。这种区分使用户能够选择将程序的成功输出定向到文件,但仍将错误消息打印到屏幕上。

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! 宏只能打印到标准输出,因此我们必须使用其他工具来打印到标准错误。

The println! macro is only capable of printing to standard output, so we have to use something else to print to standard error.

检查错误写在哪里 (Checking Where Errors Are Written)

Checking Where Errors Are Written

首先,让我们观察 minigrep 打印的内容目前是如何被写入标准输出的,包括我们想要改写到标准错误的任何错误消息。我们将通过在故意引发错误的同时将标准输出流重定向到文件来实现这一点。我们不会重定向标准错误流,因此任何发送到标准错误的内容将继续显示在屏幕上。

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.

命令行程序应该将错误消息发送到标准错误流,这样即使我们将标准输出流重定向到文件,我们仍然可以在屏幕上看到错误消息。我们的程序目前表现得并不好:我们将看到它将错误消息输出保存到了文件中!

Command line programs are expected to send error messages to the standard error stream so that 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!

为了演示此行为,我们将使用 > 和想要重定向标准输出流到的文件路径 output.txt 来运行该程序。我们不传递任何参数,这应该会导致错误:

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:

$ cargo run > output.txt

> 语法告诉 shell 将标准输出的内容写入 output.txt 而不是屏幕。我们没有看到预期的错误消息打印到屏幕上,这意味着它一定进入了文件中。这是 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:

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 that only data from a successful run ends up in the file. We’ll change that.

将错误打印到标准错误 (Printing Errors to Standard Error)

Printing Errors to Standard Error

我们将使用示例 12-24 中的代码来更改错误消息的打印方式。得益于我们在本章前面所做的重构,所有打印错误消息的代码都在一个函数 main 中。标准库提供了打印到标准错误流的 eprintln! 宏,所以让我们将调用 println! 打印错误的两处地方改为使用 eprintln!

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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-24/src/main.rs:here}}

现在让我们以相同的方式再次运行程序,不带任何参数并使用 > 重定向标准输出:

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

现在我们在屏幕上看到了错误,而 output.txt 什么都没有包含,这正是我们期望的命令行程序的行为。

Now we see the error onscreen and output.txt contains nothing, which is the behavior we expect of command line programs.

让我们再次带参数运行程序,这些参数不会导致错误但仍将标准输出重定向到文件,如下所示:

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

我们将不会在终端看到任何输出,而 output.txt 将包含我们的结果:

We won’t see any output to the terminal, and output.txt will contain our results:

文件名: output.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)

Summary

本章回顾了你目前学到的一些主要概念,并涵盖了如何在 Rust 中执行常见的 I/O 操作。通过使用命令行参数、文件、环境变量以及用于打印错误的 eprintln! 宏,你现在已经准备好编写命令行应用程序。结合前几章的概念,你的代码将组织良好,有效地在适当的数据结构中存储数据,很好地处理错误,并经过充分测试。

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 特性:闭包 (closures) 和迭代器 (iterators)。

Next, we’ll explore some Rust features that were influenced by functional languages: closures and iterators.

函数式语言特性:迭代器与闭包 (Functional Language Features: Iterators and Closures)


x-i18n: generated_at: “2026-03-01T14:19:31Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 13f319cc2e816545bbad17d38aa661748680f83ae67c2775fce05ee43ef541be source_path: ch13-00-functional-features.md workflow: 16

函数式语言特性:迭代器与闭包 (Functional Language Features: Iterators and Closures)

Functional Language Features: Iterators and Closures

Rust 的设计从许多现有的语言和技术中汲取了灵感,其中一个重要的影响是“函数式编程 (functional programming)”。以函数式风格进行编程通常包括将函数作为值使用,例如将其作为参数传递、从其他函数返回、将其分配给变量以便稍后执行等等。

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.

更具体地说,我们将涵盖:

More specifically, we’ll cover:

  • “闭包 (Closures)”,一种可以存储在变量中的类函数结构

  • “迭代器 (Iterators)”,一种处理一系列元素的方法

  • 如何使用闭包和迭代器改进第 12 章中的 I/O 项目

  • 闭包和迭代器的性能(剧透警告:它们比你想象的要快!)

  • 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

  • The performance of closures and iterators (spoiler alert: They’re faster than you might think!)

我们已经介绍了一些其他受函数式风格影响的 Rust 特性,例如模式匹配和枚举。由于掌握闭包和迭代器是编写快速、地道的 Rust 代码的重要组成部分,我们将用整整一章的篇幅来介绍它们。

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 fast, idiomatic, Rust code, we’ll devote this entire chapter to them.

闭包 (Closures)


x-i18n: generated_at: “2026-03-01T14:21:14Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: a20cbb0b6af2a985486d9ec88f5be83dac27fd45893983bfe600a08c5faf7b6e source_path: ch13-01-closures.md workflow: 16

闭包 (Closures)

Rust 的闭包是你可以保存在变量中或作为参数传递给其他函数的匿名函数。你可以在一个地方创建闭包,然后在他处调用它,以便在不同的上下文中进行求值。与函数不同,闭包可以从定义它们的作用域中捕获值。我们将演示这些闭包特性如何实现代码重用和行为定制。

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.

捕获环境 (Capturing the Environment)

我们将首先研究如何使用闭包从定义它们的环境中捕获值以备后用。场景如下:每隔一段时间,我们的 T 恤公司就会向邮寄列表中的某人赠送一件独家限量版衬衫作为促销。邮寄列表中的人可以有选择地在他们的个人资料中添加他们最喜欢的颜色。如果被选中获得免费衬衫的人设置了他们最喜欢的颜色,他们就会得到那种颜色的衬衫。如果该人没有指定最喜欢的颜色,他们将得到公司目前库存最多的颜色。

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.

实现这一点有很多方法。在这个例子中,我们将使用一个名为 ShirtColor 的枚举,它具有 RedBlue 变体(为了简单起见,限制了可用颜色的数量)。我们用一个 Inventory 结构体来代表公司的库存,该结构体有一个名为 shirts 的字段,包含一个代表当前库存衬衫颜色的 Vec<ShirtColor>。定义在 Inventory 上的 giveaway 方法获取获胜者可选的衬衫颜色偏好,并返回该人将获得的衬衫颜色。此设置如示例 13-1 所示。

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 it returns the shirt color the person will get. This setup is shown in Listing 13-1.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-01/src/main.rs}}

main 中定义的 store 还有两件蓝色衬衫和一件红色衬衫可供此次限量版促销活动分发。我们为一位偏好红色衬衫的用户和一位没有任何偏好的用户调用了 giveaway 方法。

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.

同样,这段代码可以用很多方式实现,在这里,为了专注于闭包,除了使用闭包的 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 调用该闭包并返回闭包返回的值。

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.

我们指定闭包表达式 || self.most_stocked() 作为 unwrap_or_else 的参数。这是一个本身不带参数的闭包(如果闭包带有参数,它们将出现在两条垂直线之间)。闭包体调用了 self.most_stocked()。我们在这里定义了闭包,如果需要结果,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 pipes). 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.

运行这段代码会打印以下内容:

Running this code prints the following:

{{#include ../listings/ch13-functional-features/listing-13-01/output.txt}}

这里一个有趣的方面是我们传递了一个闭包,它在当前的 Inventory 实例上调用 self.most_stocked()。标准库不需要了解我们定义的 InventoryShirtColor 类型,也不需要了解我们在这个场景中想要使用的逻辑。闭包捕获了对 self Inventory 实例的一个不可变引用,并将其与我们指定的代码一起传递给 unwrap_or_else 方法。另一方面,函数无法以这种方式捕获其环境。

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.

推断并标注闭包类型 (Inferring and Annotating Closure Types)

函数和闭包之间还有更多的区别。闭包通常不要求你像 fn 函数那样标注参数或返回值的类型。函数要求类型标注是因为类型是暴露给用户的显式接口的一部分。严谨地定义此接口对于确保每个人都同意函数使用和返回什么类型的值非常重要。另一方面,闭包不用于这样的暴露接口:它们存储在变量中,并且在使用时不需要命名它们并将其暴露给库的用户。

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 submitters of 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 they’re used without naming them and exposing them to users of our library.

闭包通常很短,并且仅在狭窄的语境中相关,而不是在任何任意场景中。在这些有限的语境中,编译器可以推断参数的类型和返回类型,类似于它推断大多数变量类型的方式(在极少数情况下,编译器也需要闭包类型标注)。

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).

与变量一样,如果我们想要增加显式性和清晰度,我们可以添加类型标注,代价是比严格必要的更冗长。为一个闭包标注类型看起来像示例 13-2 中的定义。在这个例子中,我们定义了一个闭包并将其存储在一个变量中,而不是像在示例 13-1 中那样在将其作为参数传递的地方定义闭包。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-02/src/main.rs:here}}
}

添加类型标注后,闭包的语法看起来与函数的语法更加相似。为了对比,这里我们定义了一个在其参数上加 1 的函数和一个具有相同行为的闭包。我们添加了一些空格来对齐相关部分。这说明了除了使用垂直线和可选语法的数量之外,闭包语法如何与函数语法相似:

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:

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  ;

第一行显示了一个函数定义,第二行显示了一个带有完整标注的闭包定义。在第三行,我们从闭包定义中删除了类型标注。在第四行,我们删除了括号,因为闭包体只有一个表达式,所以括号是可选的。这些都是有效的定义,当它们被调用时将产生相同的行为。add_one_v3add_one_v4 行要求对闭包进行求值才能通过编译,因为类型将从其用法中推断出来。这类似于 let v = Vec::new(); 需要类型标注或向 Vec 中插入某种类型的值才能让 Rust 推断出类型。

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.

对于闭包定义,编译器将为其每个参数和返回值推断一个具体的类型。例如,示例 13-3 显示了一个简单的闭包定义,它只返回它作为参数接收的值。除了用于本例目的之外,这个闭包并不是很有用。注意我们没有向定义中添加任何类型标注。因为没有类型标注,我们可以用任何类型调用该闭包,这里我们第一次使用了 String。如果我们随后尝试用一个整数调用 example_closure,我们将得到一个错误。

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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-03/src/main.rs:here}}

编译器给了我们这个错误:

{{#include ../listings/ch13-functional-features/listing-13-03/output.txt}}

第一次我们用 String 值调用 example_closure 时,编译器推断出 x 的类型和闭包的返回类型为 String。这些类型随后被锁定在 example_closure 的闭包中,当我们下次尝试对同一个闭包使用不同类型时,就会得到一个类型错误。

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.

捕获引用或移动所有权 (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.

在示例 13-4 中,我们定义了一个捕获对名为 list 的向量的不可变引用的闭包,因为它只需要一个不可变引用来打印该值。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-04/src/main.rs}}
}

这个例子还说明了一个变量可以绑定到一个闭包定义,并且我们稍后可以通过使用变量名和圆括号来调用该闭包,就像变量名是一个函数名一样。

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.

因为我们可以同时拥有多个对 list 的不可变引用,所以 list 在闭包定义之前、闭包定义之后但在闭包被调用之前、以及在闭包被调用之后,仍然是可以访问的。这段代码可以编译、运行并打印:

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:

{{#include ../listings/ch13-functional-features/listing-13-04/output.txt}}

接下来,在示例 13-5 中,我们更改了闭包体,使其向 list 向量中添加一个元素。闭包现在捕获了一个可变引用。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-05/src/main.rs}}
}

这段代码可以编译、运行并打印:

{{#include ../listings/ch13-functional-features/listing-13-05/output.txt}}

注意,在 borrows_mutably 闭包的定义和调用之间不再有 println! :当 borrows_mutably 被定义时,它捕获了对 list 的一个可变引用。我们在闭包被调用后就不再使用该闭包,所以可变借用结束了。在闭包定义和闭包调用之间,不允许进行用于打印的不可变借用,因为当存在可变借用时不允许有其他借用。尝试在那里添加一个 println! 看看你会得到什么错误消息!

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!

如果你想强制闭包获取它在环境中所使用值的所有权,即使闭包体并不严格需要所有权,你可以在参数列表前使用 move 关键字。

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.

这种技术主要在将闭包传递给新线程以移动数据使其归新线程所有时很有用。我们将在第 16 章讨论并发时详细讨论线程以及你为什么想要使用它们,但现在,让我们简要地探索一下使用需要 move 关键字的闭包来启动一个新线程。示例 13-6 显示了修改后的示例 13-4,在新线程而不是主线程中打印向量。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-06/src/main.rs}}
}

我们启动了一个新线程,并将一个闭包作为参数交给该线程运行。闭包体打印出了列表。在示例 13-4 中,闭包仅使用不可变引用捕获了 list ,因为那是打印它所需的最少访问量。在这个例子中,尽管闭包体仍然只需要一个不可变引用,我们仍需要通过在闭包定义的开头放置 move 关键字来指定应该将 list 移动到闭包中。如果主线程在对新线程调用 join 之前执行了更多操作,新线程可能会在主线程其余部分完成之前完成,或者主线程可能会先完成。如果主线程保持了 list 的所有权但在新线程之前结束并丢弃了 list ,那么线程中的不可变引用将是无效的。因此,编译器要求将 list 移动到交给新线程的闭包中,以便引用有效。尝试删除 move 关键字或在闭包定义后在主线程中使用 list ,看看你会得到什么编译器错误!

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. If the main thread performed more operations before calling join on the new thread, 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 and drops 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 that 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!

将捕获的值移出闭包 (Moving Captured Values Out of Closures)

一旦闭包从定义它的环境中捕获了引用或捕获了值的所有权(从而影响了什么内容被移入闭包,如果有的话),闭包体内的代码就定义了当闭包稍后被求值时这些引用或值会发生什么(从而影响了什么内容从闭包被移出,如果有的话)。

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.

闭包捕获和处理环境中的值的方式会影响闭包实现的特征,而特征是函数和结构体指定它们可以使用哪种闭包的方式。闭包将根据闭包体处理值的方式,以累加的方式自动实现这三个 Fn 特征中的一个、两个或全部三个:

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:

  • FnOnce 适用于可以被调用一次的闭包。所有闭包都至少实现了这个特征,因为所有闭包都是可以被调用的。一个将捕获的值从其主体中移出的闭包将仅实现 FnOnce 而不实现其他 Fn 特征,因为它只能被调用一次。

  • FnMut 适用于不从其主体中移出捕获的值、但可能会修改捕获值的闭包。这些闭包可以被调用多次。

  • 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 implement FnOnce and none of the other Fn traits because it can only be called once.

  • FnMut applies to closures that don’t move captured values out of their body but might mutate the captured values. These closures can be called more than once.

  • Fn applies to closures that don’t move captured values out of their body and 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.

让我们看看我们在示例 13-1 中使用的 Option<T> 上的 unwrap_or_else 方法的定义:

Let’s look at the definition of the unwrap_or_else method on Option<T> that we used in Listing 13-1:

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(),
        }
    }
}

回想一下,T 是代表 OptionSome 变体中值的类型的泛型类型。该类型 T 也是 unwrap_or_else 函数的返回类型:例如,在 Option<String> 上调用 unwrap_or_else 的代码将得到一个 String

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.

接下来,注意 unwrap_or_else 函数具有额外的泛型类型参数 FF 类型是名为 f 的参数的类型,它是我们在调用 unwrap_or_else 时提供的闭包。

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.

在泛型类型 F 上指定的特征约束是 FnOnce() -> T ,这意味着 F 必须能够被调用一次、不带参数并返回一个 T 。在特征约束中使用 FnOnce 表达了 unwrap_or_else 调用 f 不会超过一次的约束。在 unwrap_or_else 的主体中,我们可以看到如果 OptionSomef 就不会被调用。如果 OptionNonef 将被调用一次。因为所有闭包都实现了 FnOnceunwrap_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 will not call f more than once. 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.

注意:如果我们想要做的事情不需要从环境中捕获值,我们可以在需要实现 Fn 特征之一的地方使用函数名称而不是闭包。例如,在一个 Option<Vec<T>> 值上,如果值是 None ,我们可以调用 unwrap_or_else(Vec::new) 来获得一个新的空向量。编译器会自动为函数定义实现任何适用的 Fn 特征。

Note: 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. The compiler automatically implements whichever of the Fn traits is applicable for a function definition.

现在让我们看看在切片上定义的标准库方法 sort_by_key ,看看它与 unwrap_or_else 有何不同,以及为什么 sort_by_key 为特征约束使用了 FnMut 而不是 FnOnce 。闭包以引用的形式获得一个参数,该引用指向正在考虑的切片中的当前项,并返回一个可以排序的 K 类型的值。当你想要根据每个项的特定属性对切片进行排序时,此函数非常有用。在示例 13-7 中,我们有一个 Rectangle 实例列表,我们使用 sort_by_key 按它们的 width 属性从小到大排序。

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 it 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-07/src/main.rs}}
}

这段代码打印:

{{#include ../listings/ch13-functional-features/listing-13-07/output.txt}}

sort_by_key 被定义为接收一个 FnMut 闭包的原因是它会多次调用该闭包:对切片中的每个项调用一次。闭包 |r| r.width 不会从其环境中捕获、修改或移出任何内容,因此它满足特征约束要求。

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 anything out from its environment, so it meets the trait bound requirements.

相比之下,示例 13-8 显示了一个仅实现了 FnOnce 特征的闭包示例,因为它从环境中移出了一个值。编译器不允许我们在 sort_by_key 中使用这个闭包。

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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-08/src/main.rs}}

这是一种人为设计的、令人费解的方法(而且行不通),试图计算在对 list 进行排序时 sort_by_key 调用闭包的次数。这段代码尝试通过将 value ——一个来自闭包环境的 String ——推入 sort_operations 向量来完成计数。闭包捕获了 value ,然后通过将 value 的所有权转移到 sort_operations 向量将其移出了闭包。这个闭包只能被调用一次;尝试第二次调用它将行不通,因为 value 将不再存在于环境中,无法再次推入 sort_operations !因此,这个闭包仅实现了 FnOnce 。当我们尝试编译这段代码时,我们会得到这个错误,即 value 无法移出闭包,因为闭包必须实现 FnMut

This is a contrived, convoluted way (that doesn’t work) to try to 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 and 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:

{{#include ../listings/ch13-functional-features/listing-13-08/output.txt}}

该错误指向了闭包体中将 value 移出环境的那一行。为了修复此问题,我们需要更改闭包体,使其不将值移出环境。在环境中保持一个计数器并在闭包体中增加其值,是计算闭包被调用次数的一种更直接的方法。示例 13-9 中的闭包可以与 sort_by_key 配合使用,因为它仅捕获了对 num_sort_operations 计数器的可变引用,因此可以被多次调用。

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. Keeping a counter in the environment and incrementing its value in the closure body is a more straightforward way to count the number of times the closure is called. 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-09/src/main.rs}}
}

当定义或使用利用了闭包的函数或类型时, Fn 特征非常重要。在下一节中,我们将讨论迭代器。许多迭代器方法接收闭包参数,所以请在继续时记住这些闭包细节!

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!

使用迭代器处理一系列项 (Processing a Series of Items with Iterators)


x-i18n: generated_at: “2026-03-01T14:21:50Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 5f2a112bb6bbda36bc2ae2bf29196b433dd0fbcf649fcb0dd3f9448094592fd1 source_path: ch13-02-iterators.md workflow: 16

使用迭代器处理一系列项 (Processing a Series of Items with Iterators)

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.

在 Rust 中,迭代器是“惰性的 (lazy)”,这意味着它们在调用消耗迭代器以将其用尽的方法之前没有任何效果。例如,示例 13-10 中的代码通过调用 Vec<T> 上定义的 iter 方法,创建了一个遍历向量 v1 中各项的迭代器。这段代码本身并不执行任何有用的操作。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-10/src/main.rs:here}}
}

迭代器存储在 v1_iter 变量中。一旦创建了迭代器,我们就可以通过多种方式使用它。在示例 3-5 中,我们使用 for 循环遍历一个数组,以对其每个项执行某些代码。在底层,这隐式地创建并随后消耗了一个迭代器,但在此之前我们一直略过了它的具体工作方式。

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, 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.

在示例 13-11 的例子中,我们将迭代器的创建与 for 循环中迭代器的使用分离开来。当使用 v1_iter 中的迭代器调用 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-11/src/main.rs:here}}
}

在标准库不提供迭代器的语言中,你可能会通过从索引 0 开始一个变量,使用该变量对向量进行索引以获取值,并在循环中递增变量值直到达到向量中的项总数,来编写相同的功能。

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.

迭代器为你处理了所有这些逻辑,减少了你可能弄错的重复代码。迭代器为你提供了更大的灵活性,让你能对许多不同类型的序列使用相同的逻辑,而不仅仅是像向量这样可以进行索引的数据结构。让我们来看看迭代器是如何做到这一点的。

Iterators handle all of 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.

Iterator 特征和 next 方法 (The Iterator Trait and the next Method)

The Iterator Trait and the next Method

所有迭代器都实现了一个名为 Iterator 的特征,该特征定义在标准库中。该特征的定义如下所示:

All iterators implement a trait named Iterator that is defined in the standard library. The definition of the trait looks like this:

#![allow(unused)]
fn main() {
pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;

    // methods with default implementations elided
}
}

注意这个定义使用了一些新语法:type ItemSelf::Item ,它们定义了与该特征关联的类型 (associated type)。我们将在第 20 章深入讨论关联类型。目前,你只需要知道这段代码表示实现 Iterator 特征要求你也定义一个 Item 类型,并且这个 Item 类型被用于 next 方法的返回类型。换句话说,Item 类型将是从迭代器返回的类型。

Notice that 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 20. 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.

Iterator 特征仅要求实现者定义一个方法:next 方法,它一次返回迭代器的一个项,并包裹在 Some 中,当迭代结束时,返回 None

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.

我们可以直接在迭代器上调用 next 方法;示例 13-12 演示了重复调用从向量创建的迭代器上的 next 所返回的值。

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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-12/src/lib.rs:here}}

注意我们需要使 v1_iter 可变:在迭代器上调用 next 方法会改变迭代器用于跟踪序列位置的内部状态。换句话说,这段代码“消耗 (consumes)”或用尽了迭代器。每次对 next 的调用都会从迭代器中吞掉一个项。我们在使用 for 循环时不需要使 v1_iter 可变,因为循环获取了 v1_iter 的所有权并在幕后使其可变。

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.

还要注意,我们从 next 调用中得到的值是对向量中值的不可变引用。iter 方法产生一个不可变引用的迭代器。如果我们想创建一个获取 v1 所有权并返回拥有所有权的值的迭代器,我们可以调用 into_iter 而不是 iter 。类似地,如果我们想遍历可变引用,我们可以调用 iter_mut 而不是 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.

消耗迭代器的方法 (Methods That Consume the Iterator)

Methods That Consume the Iterator

Iterator 特征具有许多由标准库提供的具有默认实现的不同方法;你可以通过查看 Iterator 特征的标准库 API 文档来了解这些方法。其中一些方法在定义中调用了 next 方法,这就是为什么在实现 Iterator 特征时要求实现 next 方法的原因。

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.

调用 next 的方法被称为“消耗适配器 (consuming adapters)”,因为调用它们会耗尽迭代器。一个例子是 sum 方法,它获取迭代器的所有权并通过重复调用 next 遍历各项,从而消耗迭代器。在遍历过程中,它将每个项加到一个累加值中,并在迭代完成时返回该总和。示例 13-13 有一个说明 sum 方法用法的测试。

Methods that call next are called consuming adapters 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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-13/src/lib.rs:here}}

在调用 sum 之后我们不被允许使用 v1_iter ,因为 sum 获取了我们调用它的迭代器的所有权。

We aren’t allowed to use v1_iter after the call to sum, because sum takes ownership of the iterator we call it on.

产生其他迭代器的方法 (Methods That Produce Other Iterators)

Methods That Produce Other Iterators

“迭代器适配器 (Iterator adapters)” 是定义在 Iterator 特征上的不消耗迭代器的方法。相反,它们通过改变原始迭代器的某些方面来产生不同的迭代器。

Iterator adapters 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.

示例 13-14 显示了调用迭代器适配器方法 map 的示例,该方法接收一个闭包,在遍历项时对每个项调用该闭包。map 方法返回一个产生修改后项的新迭代器。这里的闭包创建了一个新的迭代器,其中向量中的每个项都将增加 1。

Listing 13-14 shows an example of calling the iterator adapter 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-14/src/main.rs:here}}
}

然而,这段代码产生了一个警告:

{{#include ../listings/ch13-functional-features/listing-13-14/output.txt}}

示例 13-14 中的代码不执行任何操作;我们指定的闭包永远不会被调用。警告提醒了我们原因:迭代器适配器是惰性的,我们需要在这里消耗迭代器。

The code in Listing 13-14 doesn’t do anything; the closure we’ve specified never gets called. The warning reminds us why: Iterator adapters are lazy, and we need to consume the iterator here.

为了消除此警告并消耗迭代器,我们将使用 collect 方法,我们在示例 12-1 中将其与 env::args 一起使用过。该方法消耗迭代器并将结果值收集到一个集合数据类型中。

To fix this warning and consume the iterator, we’ll use the collect method, which we used with env::args in Listing 12-1. This method consumes the iterator and collects the resultant values into a collection data type.

在示例 13-15 中,我们将遍历调用 map 返回的迭代器的结果收集到一个向量中。这个向量最终将包含原始向量中的每个项,且每个项都加了 1。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch13-functional-features/listing-13-15/src/main.rs:here}}
}

因为 map 接收一个闭包,我们可以指定想要对每个项执行的任何操作。这是一个关于闭包如何让你定制某些行为,同时重用 Iterator 特征提供的迭代行为的绝佳例子。

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.

你可以链式调用多个迭代器适配器,以一种可读的方式执行复杂的操作。但因为所有的迭代器都是惰性的,你必须调用一个消耗适配器方法才能从迭代器适配器的调用中获得结果。

You can chain multiple calls to iterator adapters to perform complex actions in a readable way. But because all iterators are lazy, you have to call one of the consuming adapter methods to get results from calls to iterator adapters.

捕获其环境的闭包 (Closures That Capture Their Environment)

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.

对于这个例子,我们将使用接收闭包的 filter 方法。闭包从迭代器中获得一个项并返回一个 bool 。如果闭包返回 true ,该值将被包含在由 filter 产生的迭代中。如果闭包返回 false ,该值将不被包含。

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.

在示例 13-16 中,我们使用带有从其环境中捕获 shoe_size 变量的闭包的 filter ,来遍历 Shoe 结构体实例的集合。它将仅返回指定尺寸的鞋子。

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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-16/src/lib.rs}}

shoes_in_size 函数获取一个鞋子向量和一个鞋子尺寸作为参数。它返回一个仅包含指定尺寸鞋子的向量。

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 的函数体中,我们调用 into_iter 来创建一个获取向量所有权的迭代器。然后,我们调用 filter 将该迭代器适配成一个新的迭代器,该迭代器仅包含闭包返回 true 的元素。

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.

该闭包从环境中捕获 shoe_size 参数,并将该值与每只鞋的尺寸进行比较,仅保留指定尺寸的鞋子。最后,调用 collect 将由适配后的迭代器返回的值汇集到一个由函数返回的向量中。

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.

测试显示,当我们调用 shoes_in_size 时,我们仅得到了尺寸与我们指定的值相同的鞋子。

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.

改进我们的 I/O 项目 (Improving Our I/O Project)


x-i18n: generated_at: “2026-03-01T14:22:49Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 0ba736d1914be507b6ab06bdd64ede35dc4d5ce57836b09c87dd84c177681cc9 source_path: ch13-03-improving-our-io-project.md workflow: 16

改进我们的 I/O 项目 (Improving Our I/O Project)

Improving Our I/O Project

利用关于迭代器的新知识,我们可以通过使用迭代器使代码中的某些地方更清晰、更简洁,从而改进第 12 章中的 I/O 项目。让我们看看迭代器如何改进我们的 Config::build 函数和 search 函数的实现。

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.

使用迭代器消除 clone (Removing a clone Using an Iterator)

在示例 12-6 中,我们添加了接收一个 String 值切片的代码,并通过对切片进行索引和克隆值来创建一个 Config 结构体的实例,从而允许 Config 结构体拥有这些值。在示例 13-17 中,我们重现了示例 12-23 中 Config::build 函数的实现。

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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs:ch13}}

当时,我们说过不要担心低效的 clone 调用,因为我们将来会消除它们。现在,那个时刻到来了!

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 是因为在参数 args 中有一个带有 String 元素的切片,但 build 函数并不拥有 args 。为了返回一个 Config 实例的所有权,我们必须克隆 Configqueryfile_path 字段中的值,以便 Config 实例可以拥有其值。

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 that the Config instance can own its values.

有了关于迭代器的新知识,我们可以将 build 函数更改为将其参数的所有权作为迭代器而不是借用切片。我们将使用迭代器功能而不是检查切片长度和索引特定位置的代码。由于迭代器将访问这些值,这将阐明 Config::build 函数正在执行的操作。

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.

一旦 Config::build 获取了迭代器的所有权并停止使用借用的索引操作,我们就可以将 String 值从迭代器移动到 Config 中,而不是调用 clone 并进行新的内存分配。

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.

直接使用返回的迭代器 (Using the Returned Iterator Directly)

打开你的 I/O 项目的 src/main.rs 文件,它应该看起来像这样:

Open your I/O project’s src/main.rs file, which should look like this:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs:ch13}}

我们将首先把示例 12-24 中 main 函数的开头改为示例 13-18 中的代码,这次使用了迭代器。在我们同时也更新了 Config::build 之前,这段代码将无法编译。

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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-18/src/main.rs:here}}

env::args 函数返回一个迭代器!现在我们不再将迭代器的值收集到向量中然后将切片传递给 Config::build ,而是直接将 env::args 返回的迭代器的所有权传递给 Config::build

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.

接下来,我们需要更新 Config::build 的定义。让我们将 Config::build 的签名改为如示例 13-19 所示。由于我们需要更新函数体,这段代码仍然无法编译。

Next, we need to update the definition of Config::build. 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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-19/src/main.rs:here}}

env::args 函数的标准库文档显示,它返回的迭代器类型是 std::env::Args ,并且该类型实现了 Iterator 特征并返回 String 值。

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.

我们更新了 Config::build 函数的签名,使得参数 args 的泛型类型具有特征约束 impl Iterator<Item = String> 而不是 &[String] 。我们在第 10 章“特征作为参数”部分讨论过这种 impl Trait 语法的用法,它意味着 args 可以是任何实现了 Iterator 特征并返回 String 项的类型。

We’ve updated the signature of the Config::build function so that 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 “Using Traits as Parameters” section of Chapter 10 means that args can be any type that implements the Iterator trait and returns String items.

因为我们正在获取 args 的所有权,并且我们将通过遍历来修改 args ,所以我们可以在 args 参数的规范中添加 mut 关键字以使其可变。

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.

使用 Iterator 特征方法 (Using Iterator Trait Methods)

接下来,我们将修复 Config::build 的主体。因为 args 实现了 Iterator 特征,我们知道可以在其上调用 next 方法!示例 13-20 将示例 12-23 中的代码更新为使用 next 方法。

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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-20/src/main.rs:here}}

请记住,env::args 返回值中的第一个值是程序的名称。我们要忽略该值并获取下一个值,因此首先我们调用 next 并且不对返回值进行任何操作。然后,我们调用 next 获取我们要放入 Configquery 字段中的值。如果 next 返回 Some ,我们使用 match 提取该值。如果它返回 None ,则意味着给出的参数不够,我们提前返回一个 Err 值。我们对 file_path 值执行相同的操作。

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. Then, we call next to get the value we want to put in the query field of Config. If next returns 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.

使用迭代器适配器使代码更清晰 (Clarifying Code with Iterator Adapters)

Clarifying Code with Iterator Adapters

我们还可以在 I/O 项目的 search 函数中利用迭代器,示例 13-21 重现了示例 12-19 中的代码。

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.

{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-19/src/lib.rs:ch13}}

我们可以使用迭代器适配器方法以更简洁的方式编写这段代码。这样做还可以让我们避免使用可变的中间变量 results 向量。函数式编程风格更倾向于最小化可变状态的量,以使代码更清晰。移除可变状态可能支持未来的增强,使搜索能够并行进行,因为我们不必管理对 results 向量的并发访问。示例 13-22 显示了这一更改。

We can write this code in a more concise way using iterator adapter 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.

{{#rustdoc_include ../listings/ch13-functional-features/listing-13-22/src/lib.rs:here}}

回想一下,search 函数的目的是返回 contents 中所有包含 query 的行。类似于示例 13-16 中的 filter 例子,这段代码使用 filter 适配器仅保留 line.contains(query) 返回 true 的行。然后我们用 collect 将匹配的行收集到另一个向量中。简单多了!欢迎在 search_case_insensitive 函数中也进行同样的更改以使用迭代器方法。

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 adapter to keep only the lines for which line.contains(query) returns true. 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.

为了进一步改进,可以尝试通过删除对 collect 的调用并将返回类型更改为 impl Iterator<Item = &'a str> ,从 search 函数返回一个迭代器,从而使该函数成为一个迭代器适配器。请注意,你还需要更新测试!在进行此更改前后,使用你的 minigrep 工具搜索一个大文件,以观察行为上的差异。在更改之前,程序在收集完所有结果之前不会打印任何结果,但在更改之后,随着找到每一条匹配行,结果就会被打印出来,因为 run 函数中的 for 循环能够利用迭代器的惰性。

For a further improvement, return an iterator from the search function by removing the call to collect and changing the return type to impl Iterator<Item = &'a str> so that the function becomes an iterator adapter. Note that you’ll also need to update the tests! Search through a large file using your minigrep tool before and after making this change to observe the difference in behavior. Before this change, the program won’t print any results until it has collected all of the results, but after the change, the results will be printed as each matching line is found because the for loop in the run function is able to take advantage of the laziness of the iterator.

在循环和迭代器之间做出选择 (Choosing Between Loops and Iterators)

Choosing Between Loops and Iterators

下一个逻辑问题是,在你自己的代码中你应该选择哪种风格,以及为什么:是示例 13-21 中的原始实现,还是示例 13-22 中使用迭代器的版本(假设我们在返回结果之前收集了所有结果,而不是返回迭代器)。大多数 Rust 程序员更喜欢使用迭代器风格。起初掌握它可能有点难,但一旦你对各种迭代器适配器及其作用有了感觉,迭代器就会更容易理解。代码不再折腾各种循环片段并构建新向量,而是专注于循环的高级目标。这抽象掉了部分平凡的代码,从而更容易看清此代码独有的概念,例如迭代器中每个元素必须通过的过滤条件。

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 (assuming we’re collecting all the results before returning them rather than returning the iterator). 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 adapters 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 that 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.

但这两项实现真的是等价的吗?直觉上的假设可能是较低级别的循环会更快。让我们谈谈性能。

But are the two implementations truly equivalent? The intuitive assumption might be that the lower-level loop will be faster. Let’s talk about performance.

循环与迭代器的性能对比 (Performance in Loops vs. Iterators)


x-i18n: generated_at: “2026-03-01T14:23:37Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 200b43a32e2bef5de723b6211bb0e6b6ca01461093ccb5c277bad1954bad0de0 source_path: ch13-04-performance.md workflow: 16

循环与迭代器的性能比较 (Performance in Loops vs. Iterators)

为了决定使用循环还是迭代器,你需要知道哪种实现更快:是带有显式 for 循环的 search 函数版本,还是使用迭代器的版本。

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.

我们通过将 Arthur Conan Doyle 爵士的《福尔摩斯探案集》全文加载到 String 中,并在内容中搜索单词 the 来运行了一个基准测试。以下是使用 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:

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 two implementations have similar performance! 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.

为了进行更全面的基准测试,你应该尝试使用各种不同大小的文本作为 contents ,使用不同的单词和不同长度的单词作为 query ,以及各种其他变化。重点在于:迭代器虽然是高级抽象,但会被编译成与你手动编写低级代码大致相同的机器码。迭代器是 Rust 的“零成本抽象 (zero-cost abstractions)”之一,这意味着使用该抽象不会带来额外的运行时开销。这类似于 C++ 的原始设计者和实现者 Bjarne Stroustrup 在其 2012 年 ETAPS 主旨演讲《C++ 基础》(Foundations of C++) 中对“零开销”的定义:

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 that 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 his 2012 ETAPS keynote presentation “Foundations of C++”:

通常,C++ 的实现遵循零开销原则:你没用到的,你不需要为其付费。更进一步:你用到的,你无法通过手写代码做得更好。

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.

在许多情况下,使用迭代器的 Rust 代码会编译成与你手动编写的相同的汇编代码。诸如循环展开和消除数组访问的边界检查等优化措施会被应用,使生成的代码极其高效。既然你知道了这一点,你就可以放心大胆地使用迭代器和闭包了!它们让代码看起来级别更高,但这样做并不会带来运行时性能损失。

In many cases, Rust code using iterators compiles to the same assembly you’d write by hand. Optimizations such as loop unrolling and eliminating bounds checking on array access apply and make the resultant 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.

总结 (Summary)

闭包和迭代器是受函数式编程语言思想启发的 Rust 特性。它们有助于 Rust 能够以低级性能清晰地表达高级思想。闭包和迭代器的实现方式使得运行时性能不受影响。这是 Rust 努力提供零成本抽象目标的一部分。

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.

现在我们已经提高了 I/O 项目的表达能力,让我们看看 cargo 的更多特性,这些特性将帮助我们将项目分享给世界。

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.

关于 Cargo 和 Crates.io 的更多信息 (More about Cargo and Crates.io)


x-i18n: generated_at: “2026-03-01T14:24:29Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: b65b3d97000dff979a58e111dcdab150284674c21b73d16a7d0745578be243fd source_path: ch14-00-more-about-cargo.md workflow: 16

关于 Cargo 和 Crates.io 的更多信息 (More About Cargo and Crates.io)

More About Cargo and Crates.io

到目前为止,我们仅使用了 Cargo 最基础的功能来构建、运行和测试我们的代码,但它能做的远不止这些。在本章中,我们将讨论它的一些其他更高级的功能,向你展示如何执行以下操作:

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:

  • 通过发布配置 (release profiles) 自定义你的构建。

  • crates.io 上发布库。

  • 使用工作空间 (workspaces) 组织大型项目。

  • crates.io 安装二进制文件。

  • 使用自定义命令扩展 Cargo。

  • Customize your build through release profiles.

  • Publish libraries on crates.io.

  • Organize large projects with workspaces.

  • Install binaries from 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.

使用发布配置定制构建 (Customizing Builds with Release Profiles)


x-i18n: generated_at: “2026-03-01T14:25:40Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 89c703f79284a38445f136feede175a251d0161b1c0efb3d49aa84344af04bf0 source_path: ch14-01-release-profiles.md workflow: 16

使用发布配置自定义构建 (Customizing Builds with Release Profiles)

Customizing Builds with Release Profiles

在 Rust 中,“发布配置 (release profiles)”是预定义的、可定制的配置,具有不同的设置,允许程序员更好地控制编译代码的各种选项。每个配置都是独立设置的。

In Rust, release profiles are predefined, 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.

Cargo 有两个主要的配置:一个是当你运行 cargo build 时 Cargo 使用的 dev 配置,另一个是当你运行 cargo build --release 时 Cargo 使用的 release 配置。dev 配置定义了适合开发的良好默认值,而 release 配置定义了适合发布构建的良好默认值。

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.

这些配置名称你可能从构建输出中感到熟悉:

These profile names might be familiar from the output of your builds:

$ cargo build
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
$ cargo build --release
    Finished `release` profile [optimized] target(s) in 0.32s

devrelease 就是编译器使用的这些不同的配置。

The dev and release are these different profiles used by the compiler.

Cargo 为每个配置提供了默认设置,当你没有在项目的 Cargo.toml 文件中显式添加任何 [profile.*] 部分时,这些设置就会生效。通过为你想要自定义的任何配置添加 [profile.*] 部分,你可以覆盖默认设置的任何子集。例如,以下是 devrelease 配置中 opt-level 设置的默认值:

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.dev]
opt-level = 0

[profile.release]
opt-level = 3

opt-level 设置控制 Rust 将应用于代码的优化程度,范围为 0 到 3。应用更多优化会延长编译时间,因此如果你处于开发阶段并经常编译代码,你会希望减少优化以加快编译速度,即使生成的代码运行速度较慢。因此,dev 的默认 opt-level0。当你准备发布代码时,最好花更多时间进行编译。你只需在发布模式下编译一次,但你会多次运行编译后的程序,因此发布模式是以更长的编译时间换取更快的运行速度。这就是为什么 release 配置的默认 opt-level3 的原因。

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 resultant 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.

你可以通过在 Cargo.toml 中为其添加不同的值来覆盖默认设置。例如,如果我们想在开发配置中使用优化级别 1,我们可以将这两行添加到项目的 Cargo.toml 文件中:

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

[profile.dev]
opt-level = 1

这段代码覆盖了默认设置 0。现在当我们运行 cargo build 时,Cargo 将使用 dev 配置的默认值加上我们对 opt-level 的自定义。因为我们将 opt-level 设置为 1 ,Cargo 将应用比默认情况更多的优化,但不如发布构建中的那么多。

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.

有关每个配置的完整配置选项列表和默认值,请参阅 Cargo 文档

For the full list of configuration options and defaults for each profile, see Cargo’s documentation.

将 Crate 发布到 Crates.io (Publishing a Crate to Crates.io)


x-i18n: generated_at: “2026-03-01T14:27:13Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: dc30b41f9c5d8c5ae3ff2e13d193a7466709483e90ca8d4939b663e39c450a79 source_path: ch14-02-publishing-to-crates-io.md workflow: 16

将 Crate 发布到 Crates.io (Publishing a Crate to Crates.io)

Publishing a Crate to Crates.io

我们已经使用过来自 crates.io 的包作为我们项目的依赖项,但你也可以通过发布自己的包来与他人分享你的代码。crates.io 上的 crate 注册表分发你的包的源代码,因此它主要托管开源代码。

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.

Rust 和 Cargo 提供了一些功能,使你发布的包更容易被人们找到和使用。接下来我们将讨论其中的一些功能,然后解释如何发布包。

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.

编写有用的文档注释 (Making Useful Documentation Comments)

Making Useful Documentation Comments

准确地为你的包编写文档将有助于其他用户了解如何以及何时使用它们,因此投入时间编写文档是值得的。在第 3 章中,我们讨论了如何使用两个斜杠 // 为 Rust 代码添加注释。Rust 还有一种专门用于文档的注释,通俗地称为“文档注释 (documentation comment)”,它可以生成 HTML 文档。HTML 会显示公共 API 项的文档注释内容,这些内容是面向那些有兴趣了解如何“使用”你的 crate 而非它是如何“实现”的程序员的。

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.

文档注释使用三个斜杠 /// 而不是两个,并支持 Markdown 记法来格式化文本。将文档注释放在它们所说明的项之前。示例 14-1 展示了名为 my_crate 的 crate 中 add_one 函数的文档注释。

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.

{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-01/src/lib.rs}}

在这里,我们描述了 add_one 函数的作用,以标题 Examples 开始一个部分,然后提供演示如何使用 add_one 函数的代码。我们可以通过运行 cargo doc 从此文档注释生成 HTML 文档。此命令运行随 Rust 分发的 rustdoc 工具,并将生成的 HTML 文档放入 target/doc 目录中。

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.

为了方便起见,运行 cargo doc --open 将为当前 crate 的文档(以及所有依赖项的文档)构建 HTML,并在 Web 浏览器中打开结果。导航到 add_one 函数,你将看到文档注释中的文本是如何渲染的,如图 14-1 所示。

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.

my_crate 的 add_one 函数生成的 HTML 文档

图 14-1:add_one 函数的 HTML 文档

常用的部分 (Commonly Used Sections)

我们在示例 14-1 中使用了 # Examples 这个 Markdown 标题,在 HTML 中创建了一个标题为 “Examples” 的部分。以下是 crate 作者在文档中经常使用的其他一些部分:

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:

  • Panics:这些是文档所说明的函数可能会引发恐慌的场景。不希望其程序发生恐慌的函数调用者应确保不在这些情况下调用该函数。

  • Errors:如果函数返回 Result ,描述可能发生的错误类型以及导致返回这些错误的条件,对调用者来说会很有帮助,这样他们就可以编写代码以不同的方式处理不同种类的错误。

  • Safety:如果调用该函数是 unsafe(不安全的)(我们将在第 20 章讨论不安全性),应该有一个部分解释为什么该函数是不安全的,并涵盖函数期望调用者遵守的不变量。

  • Panics: These are 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 that they can write code to handle the different kinds of errors in different ways.

  • Safety: If the function is unsafe to call (we discuss unsafety in Chapter 20), there should be a section explaining why the function is unsafe and covering the invariants that the function expects callers to uphold.

大多数文档注释不需要包含所有这些部分,但这是一个很好的清单,可以提醒你用户会有兴趣了解的代码方面。

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)

在文档注释中添加示例代码块有助于演示如何使用你的库,并且还有一个额外的好处:运行 cargo test 将运行文档中的代码示例作为测试!没有什么比带有示例的文档更好的了。但也没有什么比无法运行的示例更糟糕的了,因为代码在编写文档后发生了更改。如果我们运行带示例 14-1 中 add_one 函数文档的 cargo test ,我们将看到测试结果中有一个如下所示的部分:

Adding example code blocks in your documentation comments can help demonstrate how to use your library and 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 that looks like this:

   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

现在,如果我们更改函数或示例,使示例中的 assert_eq! 引发恐慌,并再次运行 cargo test ,我们将看到文档测试捕获了示例和代码之间不同步的问题!

Now, if we change either the function or the example so that 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!

包含项注释 (Contained Item Comments)

//! 风格的文档注释是为“包含”注释的项添加文档,而不是为注释“之后”的项添加文档。我们通常在 crate 根文件(按照惯例是 src/lib.rs)或模块内部使用这些文档注释,以便为 crate 或模块整体编写文档。

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.

例如,为了添加说明包含 add_one 函数的 my_crate 的用途的文档,我们在 src/lib.rs 文件的开头添加以 //! 开头的文档注释,如示例 14-2 所示。

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.

{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-02/src/lib.rs:here}}

注意最后一行以 //! 开头后没有任何代码。因为我们是以 //! 而不是 /// 开始注释,所以我们正在为包含此注释的项编写文档,而不是为紧随其后的项编写。在这种情况下,该项是 src/lib.rs 文件,它是 crate 根。这些注释描述了整个 crate。

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.

当我们运行 cargo doc --open 时,这些注释将显示在 my_crate 文档首页的 crate 公共项列表上方,如图 14-2 所示。

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.

项内部的文档注释对于描述 crate 和模块特别有用。使用它们来解释容器的总体目的,帮助用户了解 crate 的组织结构。

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.

为整个 crate 带有注释的渲染 HTML 文档

图 14-2:my_crate 的渲染文档,包括描述整个 crate 的注释

公开方便的公有 API (Exporting a Convenient Public API)

在发布 crate 时,公有 API 的结构是一个主要的考虑因素。使用你的 crate 的人对结构的熟悉程度不如你,如果你的 crate 有一个庞大的模块层级结构,他们可能很难找到想要使用的部分。

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.

在第 7 章中,我们介绍了如何使用 pub 关键字使项成为公有的,以及如何使用 use 关键字将项引入作用域。然而,在你开发 crate 时对你有意义的结构对你的用户来说可能并不方便。你可能想将结构体组织在包含多个层级的层级结构中,但随后想要使用你定义在层级深处的类型的人可能会在发现该类型存在时遇到困难。他们可能还会对必须输入 use my_crate::some_module::another_module::UsefulType; 而不是 use my_crate::UsefulType; 感到厌烦。

In Chapter 7, we covered how to make items public using the pub keyword, and how to 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;.

好消息是,如果该结构对于其他库的人来说使用起来“不”方便,你不需要重新安排你的内部组织:相反,你可以使用 pub use 重新导出项,以创建一个与你的私有结构不同的公有结构。“重导出 (Re-exporting)” 获取一个位置的公有项,并在另一个位置使其成为公有的,就好像它是在另一个位置定义的一样。

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.

例如,假设我们制作了一个名为 art 的库,用于建模艺术概念。在此库中有两个模块:一个名为 kinds 的模块,包含两个名为 PrimaryColorSecondaryColor 的枚举;另一个名为 utils 的模块,包含一个名为 mix 的函数,如示例 14-3 所示。

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.

{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-03/src/lib.rs:here}}

图 14-3 展示了由 cargo doc 生成的此 crate 文档首页的样子。

Figure 14-3 shows what the front page of the documentation for this crate generated by cargo doc would look like.

列出 kinds 和 utils 模块的 art crate 渲染文档

图 14-3:列出 kindsutils 模块的 art 文档首页

注意,PrimaryColorSecondaryColor 类型没有列在首页上,mix 函数也没有。我们必须点击 kindsutils 才能看到它们。

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.

另一个依赖此库的 crate 将需要 use 语句,将 art 中的项引入作用域,并指定当前定义的模块结构。示例 14-4 显示了一个使用 art crate 中 PrimaryColormix 项的 crate 示例。

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.

{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-04/src/main.rs}}

示例 14-4 中使用 art crate 的代码作者必须弄清楚 PrimaryColorkinds 模块中,mixutils 模块中。art crate 的模块结构对于开发 art crate 的开发者来说比对于使用它的人来说更相关。内部结构对于试图了解如何使用 art crate 的人来说没有任何有用的信息,反而会导致混淆,因为使用它的开发者必须弄清楚去哪里寻找,并且必须在 use 语句中指定模块名称。

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.

为了从公有 API 中移除内部组织,我们可以修改示例 14-3 中的 art crate 代码,添加 pub use 语句在顶层重导出这些项,如示例 14-5 所示。

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.

{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-05/src/lib.rs:here}}

cargo doc 为此 crate 生成的 API 文档现在将在首页列出并链接这些重导出项,如图 14-4 所示,使得 PrimaryColorSecondaryColor 类型以及 mix 函数更容易找到。

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.

在首页带有重导出的 art crate 渲染文档

图 14-4:列出重导出的 art 文档首页

art crate 的用户仍然可以看到并使用示例 14-3 中的内部结构(如示例 14-4 所示),或者他们可以使用示例 14-5 中更方便的结构,如示例 14-6 所示。

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.

{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-06/src/main.rs:here}}

在有许多嵌套模块的情况下,使用 pub use 在顶层重导出类型可以显著改善使用该 crate 的人的体验。pub use 的另一个常见用途是重导出当前 crate 中某个依赖项的定义,使该 crate 的定义成为你的 crate 公有 API 的一部分。

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.

创建一个有用的公有 API 结构与其说是一门科学,不如说是一门艺术,你可以通过迭代来找到最适合用户的 API。选择 pub use 让你能灵活地在内部构建 crate,并将内部结构与你呈现给用户的内容解耦。看看你安装的一些 crate 的代码,看看它们的内部结构是否与其公有 API 不同。

Creating a useful public API structure is more 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.

设置 Crates.io 账号 (Setting Up a Crates.io Account)

Setting Up a Crates.io Account

在发布任何 crate 之前,你需要在 crates.io 上创建一个账号并获取一个 API 令牌。为此,请访问 crates.io 首页并通过 GitHub 账号登录。(目前需要 GitHub 账号,但该网站将来可能会支持其他创建账号的方式。)登录后,访问你的账号设置 https://crates.io/me/ 并获取你的 API 密钥。然后,运行 cargo login 命令并在提示时粘贴你的 API 密钥,如下所示:

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:

$ cargo login
abcdefghijklmnopqrstuvwxyz012345

此命令将通知 Cargo 你的 API 令牌,并将其存储在本地的 ~/.cargo/credentials.toml 中。注意此令牌是一个秘密:请勿与他人分享。如果你因任何原因与他人分享了它,你应该撤销它并在 crates.io 上生成一个新令牌。

This command will inform Cargo of your API token and store it locally in ~/.cargo/credentials.toml. 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.

为新 Crate 添加元数据 (Adding Metadata to a New Crate)

假设你有一个想要发布的 crate。在发布之前,你需要在该 crate 的 Cargo.toml 文件的 [package] 部分添加一些元数据。

你的 crate 需要一个唯一的名称。虽然你可以在本地工作时给 crate 命名任何你喜欢的名称,但 crates.io 上的 crate 名称是按照先到先得的原则分配的。一旦某个 crate 名称被占用,其他人就不能再使用该名称发布 crate 了。在尝试发布 crate 之前,请搜索你想使用的名称。如果该名称已被使用,你需要另找一个名称,并编辑 Cargo.toml 文件 [package] 部分下的 name 字段,以使用新名称进行发布,如下所示:

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:

文件名: Cargo.toml

[package]
name = "guessing_game"

即使你选择了一个唯一的名称,如果在此时运行 cargo publish 来发布该 crate,你也会得到一个警告,然后是一个错误:

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
    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 (status 400 Bad Request): missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for more information on configuring these fields

这会导致错误,因为你遗漏了一些关键信息:为了让人们知道你的 crate 是做什么的以及在什么条款下可以使用它,描述(description)和许可证(license)是必需的。在 Cargo.toml 中,添加一两句话的描述,因为它将出现在搜索结果中。对于 license 字段,你需要提供一个“许可证标识符值”。Linux 基金会的软件包数据交换 (SPDX) 列出了你可以用于此值的标识符。例如,要指定你使用 MIT 许可证授权你的 crate,请添加 MIT 标识符:

This results in an error because you’re missing some crucial information: A description and license are required so that 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

[package]
name = "guessing_game"
license = "MIT"

如果你想使用不出现在 SPDX 中的许可证,你需要将该许可证的文本放入一个文件中,将该文件包含在你的项目中,然后使用 license-file 来指定该文件的名称,而不是使用 license 键。

关于哪个许可证适合你的项目,这超出了本书的范围。Rust 社区中的许多人以与 Rust 相同的方式对其项目进行授权,即使用 MIT OR Apache-2.0 的双重许可证。这种做法说明你也可以指定由 OR 分隔的多个许可证标识符,以便为你的项目提供多个许可证。

有了唯一的名称、版本、你的描述和添加的许可证,准备发布的项目的 Cargo.toml 文件可能看起来像这样:

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

[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
description = "A fun game where you guess what number the computer has chosen."
license = "MIT OR Apache-2.0"

[dependencies]

Cargo 文档 描述了你可以指定的其他元数据,以确保其他人可以更轻松地发现和使用你的 crate。

Cargo’s documentation describes other metadata you can specify to ensure that others can discover and use your crate more easily.

发布到 Crates.io (Publishing to Crates.io)

Publishing to Crates.io

现在你已经创建了账号、保存了 API 令牌、为你的 crate 选择了名称并指定了必需的元数据,你可以发布了!发布 crate 会将特定版本上传到 crates.io 供他人使用。

请保持谨慎,因为发布是“永久的 (permanent)”。版本永远不能被覆盖,并且除非在某些特定情况下,代码不能被删除。Crates.io 的一个主要目标是充当代码的永久存档,以便所有依赖于来自 crates.io 的 crate 的项目构建都能继续工作。允许版本删除将使实现该目标变得不可能。然而,你可以发布的 crate 版本数量是没有限制的。

再次运行 cargo publish 命令。现在它应该会成功:

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.

Be careful, because a publish is permanent. The version can never be overwritten, and the code cannot be deleted except in certain circumstances. 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.

Run the cargo publish command again. It should succeed now:

$ cargo publish
    Updating crates.io index
   Packaging guessing_game v0.1.0 (file:///projects/guessing_game)
    Packaged 6 files, 1.2KiB (895.0B compressed)
   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` profile [unoptimized + debuginfo] target(s) in 0.19s
   Uploading guessing_game v0.1.0 (file:///projects/guessing_game)
    Uploaded guessing_game v0.1.0 to registry `crates-io`
note: waiting for `guessing_game v0.1.0` to be available at registry
`crates-io`.
You may press ctrl-c to skip waiting; the crate should be available shortly.
   Published guessing_game v0.1.0 at registry `crates-io`

恭喜!你现在已与 Rust 社区分享了你的代码,任何人都可以轻松地将你的 crate 作为其项目的依赖项添加。

Congratulations! You’ve now shared your code with the Rust community, and anyone can easily add your crate as a dependency of their project.

发布现有 Crate 的新版本 (Publishing a New Version of an Existing Crate)

Publishing a New Version of an Existing Crate

当你对 crate 进行了更改并准备好发布新版本时,你需要更改 Cargo.toml 文件中指定的 version 值并重新发布。根据你所做的更改类型,使用 语义化版本 (Semantic Versioning) 规则 来决定合适的下一个版本号。然后,运行 cargo publish 来上传新版本。

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.

从 Crates.io 撤回版本 (Deprecating Versions from Crates.io)

Deprecating Versions from Crates.io

虽然你无法移除 crate 的旧版本,但你可以防止任何未来的项目将它们作为新依赖项添加。当一个 crate 版本由于某种原因而损坏时,这非常有用。在这种情况下,Cargo 支持“撤回 (yank)”一个 crate 版本。

“撤回”一个版本会阻止新项目依赖该版本,同时允许所有依赖该版本的现有项目继续工作。本质上,撤回意味着所有带有 Cargo.lock 的项目都不会损坏,并且以后生成的任何 Cargo.lock 文件都不会使用被撤回的版本。

要撤回某个版本的 crate,请在你之前发布的该 crate 的目录中运行 cargo yank 并指定你要撤回哪个版本。例如,如果我们发布了 guessing_game 的 1.0.1 版本并想撤回它,那么我们将在 guessing_game 的项目目录中运行:

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.

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.

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, then we’d run the following in the project directory for guessing_game:

$ cargo yank --vers 1.0.1
    Updating crates.io index
        Yank guessing_game@1.0.1

通过在命令中添加 --undo ,你还可以撤销撤回操作,并允许项目再次开始依赖某个版本:

By adding --undo to the command, you can also undo a yank and allow projects to start depending on a version again:

$ 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 工作空间 (Cargo Workspaces)


x-i18n: generated_at: “2026-03-01T14:27:59Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 5be8eb3df879a8bd6945f165dcc8659dc0d20fb56df108a6bc51a9a2571ebdce source_path: ch14-03-cargo-workspaces.md workflow: 16

Cargo 工作空间 (Cargo Workspaces)

Cargo Workspaces

在第 12 章中,我们构建了一个包含二进制 crate 和库 crate 的包。随着项目的发展,你可能会发现库 crate 会继续变大,你想将包进一步拆分为多个库 crate。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.

创建工作空间 (Creating a Workspace)

Creating a Workspace

“工作空间 (workspace)”是一组共享同一个 Cargo.lock 和输出目录的包。让我们使用工作空间创建一个项目——我们将使用简单的代码,以便专注于工作空间的结构。构建工作空间有多种方式,这里我们仅展示一种常见方式。我们将拥有一个包含一个二进制文件和两个库的工作空间。二进制文件将提供主要功能,并依赖于这两个库。一个库将提供 add_one 函数,另一个库提供 add_two 函数。这三个 crate 将属于同一个工作空间。我们首先为工作空间创建一个新目录:

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 that 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 the other 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:

$ mkdir add
$ cd add

接下来,在 add 目录中,我们创建用于配置整个工作空间的 Cargo.toml 文件。此文件不会有 [package] 部分。相反,它将以 [workspace] 部分开始,允许我们向工作空间添加成员。我们还决定通过将 resolver 值设置为 "3",在我们的工作空间中使用 Cargo 解析器算法的最新且最伟大的版本:

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. We also make a point to use the latest and greatest version of Cargo’s resolver algorithm in our workspace by setting the resolver value to "3":

文件名: Cargo.toml

{{#include ../listings/ch14-more-about-cargo/no-listing-01-workspace/add/Cargo.toml}}

接下来,我们通过在 add 目录下运行 cargo new 来创建 adder 二进制 crate:

Next, we’ll create the adder binary crate by running cargo new within the add directory:

$ cargo new adder
     Created binary (application) `adder` package
      Adding `adder` as member of workspace at `file:///projects/add`

在工作空间内运行 cargo new 也会自动将新创建的包添加到工作空间 Cargo.toml[workspace] 定义的 members 键里,如下所示:

Running cargo new inside a workspace also automatically adds the newly created package to the members key in the [workspace] definition in the workspace Cargo.toml, like this:

{{#include ../listings/ch14-more-about-cargo/output-only-01-adder-crate/add/Cargo.toml}}

此时,我们可以通过运行 cargo build 来构建工作空间。你的 add 目录中的文件应该看起来像这样:

At this point, we can build the workspace by running cargo build. The files in your add directory should look like this:

├── Cargo.lock
├── Cargo.toml
├── adder
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── target

工作空间在顶层有一个 target 目录,编译产物将放在其中;adder 包没有自己的 target 目录。即使我们要从 adder 目录内部运行 cargo build ,编译产物最终仍会进入 add/target 而不是 add/adder/target 。Cargo 这样构建工作空间中的 target 目录是因为工作空间中的 crate 旨在相互依赖。如果每个 crate 都有自己的 target 目录,那么每个 crate 都必须重新编译工作空间中的每一个其他 crate,以将产物放入自己的 target 目录中。通过共享一个 target 目录,crate 可以避免不必要的重新构建。

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.

在工作空间中创建第二个包 (Creating the Second Package in the Workspace)

Creating the Second Package in the Workspace

接下来,让我们在工作空间中创建另一个成员包并将其命名为 add_one 。生成一个名为 add_one 的新库 crate:

Next, let’s create another member package in the workspace and call it add_one. Generate a new library crate named add_one:

$ cargo new add_one --lib
     Created library `add_one` package
      Adding `add_one` as member of workspace at `file:///projects/add`

顶层的 Cargo.toml 现在将在 members 列表中包含 add_one 路径:

The top-level Cargo.toml will now include the add_one path in the members list:

文件名: Cargo.toml

{{#include ../listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml}}

你的 add 目录现在应该包含这些目录和文件:

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

add_one/src/lib.rs 文件中,让我们添加一个 add_one 函数:

In the add_one/src/lib.rs file, let’s add an add_one function:

文件名: add_one/src/lib.rs

{{#rustdoc_include ../listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add_one/src/lib.rs}}

现在我们可以让包含二进制文件的 adder 包依赖于包含库的 add_one 包。首先,我们需要在 adder/Cargo.toml 中添加对 add_one 的路径依赖。

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/Cargo.toml

{{#include ../listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml:6:7}}

Cargo 不会假设工作空间中的 crate 相互依赖,因此我们需要明确依赖关系。

Cargo doesn’t assume that crates in a workspace will depend on each other, so we need to be explicit about the dependency relationships.

接下来,让我们在 adder crate 中使用 add_one 函数(来自 add_one crate)。打开 adder/src/main.rs 文件,修改 main 函数以调用 add_one 函数,如示例 14-7 所示。

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 change the main function to call the add_one function, as in Listing 14-7.

{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs}}

让我们通过在顶层 add 目录运行 cargo build 来构建工作空间!

Let’s build the workspace by running cargo build in the top-level add directory!

$ cargo build
   Compiling add_one v0.1.0 (file:///projects/add/add_one)
   Compiling adder v0.1.0 (file:///projects/add/adder)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.22s

要从 add 目录运行二进制 crate,我们可以使用 -p 参数和包名并通过 cargo run 指定我们要运行工作空间中的哪个包:

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:

$ cargo run -p adder
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/adder`
Hello, world! 10 plus one is 11!

这会运行 adder/src/main.rs 中的代码,它依赖于 add_one crate。

This runs the code in adder/src/main.rs, which depends on the add_one crate.

依赖外部包 (Depending on an External Package)

注意工作空间在顶层只有一个 Cargo.lock 文件,而不是在每个 crate 的目录中都有一个 Cargo.lock 。这确保了所有 crate 都使用所有依赖项的相同版本。如果我们向 adder/Cargo.tomladd_one/Cargo.toml 文件添加 rand 包,Cargo 将把它们都解析为 rand 的一个版本,并记录在那一个 Cargo.lock 中。使工作空间中的所有 crate 使用相同的依赖项意味着 crate 之间始终是兼容的。让我们将 rand crate 添加到 add_one/Cargo.toml 文件的 [dependencies] 部分,以便我们可以在 add_one crate 中使用 rand crate:

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 that we can use the rand crate in the add_one crate:

文件名: add_one/Cargo.toml

{{#include ../listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add_one/Cargo.toml:6:7}}

我们现在可以将 use rand; 添加到 add_one/src/lib.rs 文件中,通过在 add 目录中运行 cargo build 构建整个工作空间,将会引入并编译 rand crate。我们将得到一个警告,因为我们没有引用我们引入作用域的 rand

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:

$ 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 (run `cargo fix --lib -p add_one` to apply 1 suggestion)
   Compiling adder v0.1.0 (file:///projects/add/adder)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.95s

顶层的 Cargo.lock 现在包含了关于 add_one 依赖 rand 的信息。然而,即使 rand 在工作空间的某个地方被使用,除非我们也向其他 crate 的 Cargo.toml 文件中添加 rand ,否则我们无法在该工作空间的其他 crate 中使用它。例如,如果我们向 adder 包的 adder/src/main.rs 文件添加 use rand; ,我们将得到一个错误:

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 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`

要修复此问题,请编辑 adder 包的 Cargo.toml 文件,并指明 rand 也是它的依赖项。构建 adder 包会将 rand 添加到 Cargo.lockadder 的依赖项列表中,但不会下载额外的 rand 副本。Cargo 将确保工作空间中使用 rand 包的每个包中的每个 crate 都使用相同的版本,只要它们指定了兼容的 rand 版本,这既节省了空间,又确保了工作空间中的 crate 能够彼此兼容。

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 use 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.

如果工作空间中的 crate 指定了相同依赖项的不兼容版本,Cargo 将解析它们中的每一个,但仍会尝试解析尽可能少的版本。

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.

为工作空间添加测试 (Adding a Test to a Workspace)

Adding a Test to a Workspace

作为另一项增强,让我们在 add_one crate 中添加对 add_one::add_one 函数的测试:

For another enhancement, let’s add a test of the add_one::add_one function within the add_one crate:

文件名: add_one/src/lib.rs

{{#rustdoc_include ../listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add_one/src/lib.rs}}

现在在顶层 add 目录运行 cargo test 。在像这样结构的工作空间中运行 cargo test 会运行工作空间中所有 crate 的测试:

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
   Compiling add_one v0.1.0 (file:///projects/add/add_one)
   Compiling adder v0.1.0 (file:///projects/add/adder)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.20s
     Running unittests src/lib.rs (target/debug/deps/add_one-93c49ee75dc46543)

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-3a47283c568d2b6a)

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

输出的第一部分显示 add_one crate 中的 it_works 测试通过了。下一部分显示在 adder crate 中没有找到测试,接下来的最后一部分显示在 add_one crate 中没有找到文档测试。

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 that zero documentation tests were found in the add_one crate.

我们还可以通过使用 -p 标志并指定我们要测试的 crate 名称,从顶层目录运行工作空间中某个特定 crate 的测试:

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:

$ cargo test -p add_one
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/add_one-93c49ee75dc46543)

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

此输出显示 cargo test 仅运行了 add_one crate 的测试,而没有运行 adder crate 的测试。

This output shows cargo test only ran the tests for the add_one crate and didn’t run the adder crate tests.

如果你将工作空间中的 crate 发布到 crates.io,工作空间中的每个 crate 都需要分别发布。与 cargo test 类似,我们可以通过使用 -p 标志并指定我们要发布的 crate 名称来发布工作空间中的特定 crate。

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.

作为额外的练习,尝试以类似于 add_one crate 的方式向此工作空间添加一个 add_two crate!

For additional practice, add an add_two crate to this workspace in a similar way as the add_one crate!

随着你的项目增长,请考虑使用工作空间:它使你能够处理更小、更容易理解的组件,而不是一大坨代码。此外,如果 crate 经常同时更改,将它们放在工作空间中可以使 crate 之间的协调更容易。

As your project grows, consider using a workspace: It enables you to work with smaller, easier-to-understand 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.

使用 cargo install 安装二进制文件 (Installing Binaries with cargo install)


x-i18n: generated_at: “2026-03-01T14:28:42Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 5e9d6e61baa315b97a51080bd2dd96acd69690c280e6cb9bc13b4e6b6af82b15 source_path: ch14-04-installing-binaries.md workflow: 16

使用 cargo install 安装二进制文件 (Installing Binaries with cargo install)

Installing Binaries with cargo install

cargo install 命令允许你在本地安装和使用二进制 crate。这并不是为了取代系统包管理器;它旨在为 Rust 开发人员提供一种便捷的方式,来安装他人在 crates.io 上分享的工具。注意你只能安装具有二进制目标的包。“二进制目标 (binary target)”是如果 crate 具有 src/main.rs 文件或指定为二进制文件的其他文件时创建的可运行程序,这与本身不可运行但适合包含在其他程序中的库目标相对。通常,crate 在 README 文件中会有关于该 crate 是库、具有二进制目标还是两者兼有的信息。

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 安装的二进制文件都存储在安装根目录的 bin 文件夹中。如果你使用 rustup.rs 安装了 Rust 且没有任何自定义配置,该目录将是 $HOME/.cargo/bin 。请确保此目录在你的 $PATH 中,以便能够运行通过 cargo install 安装的程序。

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 this directory is in your $PATH to be able to run programs you’ve installed with cargo install.

例如,在第 12 章中我们提到有一个名为 ripgrepgrep 工具的 Rust 实现,用于搜索文件。要安装 ripgrep ,我们可以运行以下命令:

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:

$ cargo install ripgrep
    Updating crates.io index
  Downloaded ripgrep v14.1.1
  Downloaded 1 crate (213.6 KB) in 0.40s
  Installing ripgrep v14.1.1
--snip--
   Compiling grep v0.3.2
    Finished `release` profile [optimized + debuginfo] target(s) in 6.73s
  Installing ~/.cargo/bin/rg
   Installed package `ripgrep v14.1.1` (executable `rg`)

输出的倒数第二行显示了安装好的二进制文件的位置和名称,在 ripgrep 的情况下是 rg 。如前所述,只要安装目录在你的 $PATH 中,你就可以运行 rg --help 并开始使用一个更快、更 Rust 范儿的工具来搜索文件了!

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!

使用自定义命令扩展 Cargo (Extending Cargo with Custom Commands)


x-i18n: generated_at: “2026-03-01T14:29:34Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 1a18d238852672a56de0b521226c4a6ef21946f0a3d6bec7f0ffb11794a4232e source_path: ch14-05-extending-cargo.md workflow: 16

使用自定义命令扩展 Cargo (Extending Cargo with Custom Commands)

Extending Cargo with Custom Commands

Cargo 的设计允许你使用新的子命令来扩展它,而无需修改 Cargo 本身。如果你的 $PATH 中有一个名为 cargo-something 的二进制文件,你可以通过运行 cargo something 来将其作为 Cargo 子命令运行。运行 cargo --list 时也会列出这类自定义命令。能够使用 cargo install 安装扩展,然后像使用内置 Cargo 工具一样运行它们,是 Cargo 设计中一个超级方便的优势!

Cargo is designed so that you can extend it with new subcommands without having to modify it. If a binary in your $PATH is named cargo-something, you can run it as if it were 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!

总结 (Summary)

Summary

使用 Cargo 和 crates.io 分享代码是使 Rust 生态系统对许多不同任务都非常有用的原因之一。Rust 的标准库小而稳定,但 crate 很容易分享、使用,并能在与语言不同的时间线上进行改进。不要害羞,请在 crates.io 上分享对你有用的代码;它很可能对其他人也有用!

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!

智能指针 (Smart Pointers)


x-i18n: generated_at: “2026-03-01T14:30:34Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: adf324198a3eb791ba5828cee69a201f3f2e6f8493280bfb5c897e8b50fca0f1 source_path: ch15-00-smart-pointers.md workflow: 16

智能指针 (Smart Pointers)

Smart Pointers

指针是一个通用概念,指包含内存地址的变量。该地址引用或“指向”某些其他数据。Rust 中最常见的指针类型是引用,你在第 4 章中已经学习过。引用由 & 符号指示,并借用它们指向的值。除了引用数据之外,它们没有其他特殊功能,也没有额外开销。

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 they have no overhead.

另一方面,“智能指针 (smart pointers)”是表现得像指针,但同时也具有额外的元数据和功能的数据结构。智能指针的概念并非 Rust 特有:智能指针起源于 C++,也存在于其他语言中。Rust 标准库中定义了多种智能指针,提供引了用所不具备的功能。为了探索这个通用概念,我们将看几个不同的智能指针示例,包括“引用计数 (reference counting)”智能指针类型。这种指针允许通过跟踪所有者的数量来使数据拥有多个所有者,并在没有所有者剩余时清理数据。

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 中,引用和智能指针之间还有一个额外的区别:引用仅借用数据,而在许多情况下,智能指针“拥有”它们指向的数据。

In Rust, with its concept of ownership and borrowing, there is an additional difference between references and smart pointers: While references only borrow data, in many cases smart pointers own the data they point to.

智能指针通常使用结构体来实现。与普通结构体不同,智能指针实现了 DerefDrop 特征。Deref 特征允许智能指针结构体的实例表现得像引用一样,这样你编写的代码就可以同时适用于引用或智能指针。Drop 特征允许你自定义当智能指针实例超出作用域时运行的代码。在本章中,我们将讨论这两个特征,并演示它们对智能指针的重要性。

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 that 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 of these traits and demonstrate why they’re important to smart pointers.

鉴于智能指针模式是 Rust 中经常使用的通用设计模式,本章不会涵盖每一种现有的智能指针。许多库都有自己的智能指针,你甚至可以编写自己的。我们将涵盖标准库中最常见的智能指针:

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:

  • Box<T>,用于在堆上分配值

  • Rc<T>,一种支持多重所有权的引用计数类型

  • Ref<T>RefMut<T>,通过 RefCell<T> 访问,这是一种在运行时而非编译时强制执行借用规则的类型

  • Box<T>, for allocating values on the heap

  • Rc<T>, a reference counting type that enables multiple ownership

  • Ref<T> and RefMut<T>, accessed through RefCell<T>, a type that enforces the borrowing rules at runtime instead of compile time

此外,我们还将介绍“内部可变性 (interior mutability)”模式,即一个不可变类型暴露一个用于修改内部值的 API。我们还将讨论引用循环:它们如何导致内存泄漏,以及如何防止它们。

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.

让我们开始吧!

Let’s dive in!

使用 Box<T> 指向堆上的数据 (Using Box<T> to Point to Data on the Heap)


x-i18n: generated_at: “2026-03-01T14:32:00Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 67822be0c96dcae16057dadf4cb17d685586a8165f42134871c3e0590b5adf09 source_path: ch15-01-box.md workflow: 16

使用 Box<T> 指向堆上的数据 (Using Box<T> to Point to Data on the Heap)

Using Box<T> to Point to Data on the Heap

最直观的智能指针是 Box,其类型写作 Box<T>。“Box” 允许你在堆上而不是栈上存储数据。留在栈上的是指向堆数据的指针。请参阅第 4 章回顾栈和堆之间的区别。

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 没有性能开销。但它们也没有许多额外的功能。你最常在这些情况下使用它们:

  • 当你有一个在编译时无法知道大小的类型,而你又想在需要确切大小的上下文中使用该类型的值时
  • 当你有大量数据,且你想转移所有权但要确保在转移时不复制数据时
  • 当你想拥有一个值,并且你只关心它是实现了特定特征的类型,而不是特定类型时

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 that 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

我们将在“通过 Box 启用递归类型”中演示第一种情况。在第二种情况下,转移大量数据的所有权可能需要很长时间,因为数据会在栈上被复制。为了提高这种情况下的性能,我们可以将大量数据存储在堆上的 Box 中。这样,只有少量的指针数据在栈上被复制,而它引用的数据则保留在堆上的一个地方。第三种情况被称为“特征对象 (trait object)”,第 18 章的“使用特征对象实现不同类型间的抽象行为”专门讨论了这个话题。所以,你在这里学到的东西将在该节中再次应用!

We’ll demonstrate the first situation in “Enabling Recursive Types with Boxes”. 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 “Using Trait Objects to Abstract over Shared Behavior” in Chapter 18 is devoted to that topic. So, what you learn here you’ll apply again in that section!

在堆上存储数据 (Storing Data on the Heap)

Storing Data on the Heap

在讨论 Box<T> 的堆存储用例之前,我们将介绍其语法以及如何与存储在 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>.

示例 15-1 展示了如何使用 Box 在堆上存储一个 i32 值。

Listing 15-1 shows how to use a box to store an i32 value on the heap.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-01/src/main.rs}}
}

我们定义变量 b 具有一个 Box 的值,该 Box 指向分配在堆上的值 5。此程序将打印 b = 5;在这种情况下,我们可以像处理栈上的数据一样访问 Box 中的数据。就像任何拥有所有权的值一样,当 Box 超出作用域时(如 main 结束时的 b),它将被释放。释放操作既针对 Box(存储在栈上),也针对它指向的数据(存储在堆上)。

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 similarly 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).

将单个值放在堆上并不是非常有用,因此你不会经常这样单独使用 Box。在大多数情况下,将像单个 i32 这样的值放在栈上(默认存储位置)更为合适。让我们看看一种如果不使用 Box 我们就不被允许定义类型的情况。

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 define if we didn’t have boxes.

通过 Box 启用递归类型 (Enabling Recursive Types with Boxes)

Enabling Recursive Types with Boxes

一个“递归类型 (recursive type)”的值可以拥有另一个相同类型的值作为其自身的一部分。递归类型带来了一个问题,因为 Rust 需要在编译时知道一个类型占用多少空间。然而,递归类型值的嵌套理论上可以无限进行,因此 Rust 无法知道该值需要多少空间。因为 Box 具有已知的大小,我们可以通过在递归类型定义中插入一个 Box 来启用递归类型。

A value of a recursive type can have another value of the same type as part of itself. Recursive types pose an issue because Rust needs to know at compile time 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.

作为递归类型的一个例子,让我们探索一下 cons list。这是函数式编程语言中常见的一种数据类型。除了递归之外,我们要定义的 cons list 类型很简单;因此,我们将要处理的示例中的概念在任何进入涉及递归类型的更复杂情况时都将非常有用。

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 anytime you get into more complex situations involving recursive types.

理解 Cons List (Understanding the Cons List)

“Cons list” 是一种源自 Lisp 编程语言及其方言的数据结构,由嵌套的对 (pairs) 组成,是 Lisp 版本的链表。它的名字来自 Lisp 中的 cons 函数(“construct function” 的缩写),该函数利用两个参数构造一个新的对。通过对由一个值和另一个对组成的对调用 cons ,我们可以构造由递归对组成的 cons list。

A cons list is a data structure that comes from the Lisp programming language and its dialects, 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.

例如,这里有一个包含列表 1, 2, 3 的 cons list 的伪代码表示,每对都在括号中:

For example, here’s a pseudocode representation of a cons list containing the list 1, 2, 3 with each pair in parentheses:

(1, (2, (3, Nil)))

cons list 中的每一项都包含两个元素:当前项的值和下一项。列表中的最后一项只包含一个名为 Nil 的值,没有下一项。cons list 是通过递归调用 cons 函数产生的。表示递归基本情况的规范名称是 Nil 。注意,这与第 6 章讨论的 “null” 或 “nil” 概念不同,后者是指无效或缺失的值。

Each item in a cons list contains two elements: the value of the current item and of 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 discussed in Chapter 6, which is an invalid or absent value.

Cons list 在 Rust 中并不是一种常用的数据结构。大多数时候,当你在 Rust 中有一个项列表时,Vec<T> 是一个更好的选择。其他更复杂的递归数据类型在各种情况下“确实”有用,但通过从本章的 cons list 开始,我们可以探索 Box 如何让我们在没有太多干扰的情况下定义递归数据类型。

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.

示例 15-2 包含了一个 cons list 的枚举定义。注意这段代码目前还无法编译,因为我们将证明 List 类型不具有已知的大小。

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.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-02/src/main.rs:here}}

注意:为了本例的目的,我们要实现的是一个仅持有 i32 值的 cons list。我们可以使用我们在第 10 章讨论过的泛型来实现它,以定义一个可以存储任何类型值的 cons list 类型。

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.

使用 List 类型存储列表 1, 2, 3 看起来将如示例 15-3 中的代码所示。

Using the List type to store the list 1, 2, 3 would look like the code in Listing 15-3.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-03/src/main.rs:here}}

第一个 Cons 值持有 1 和另一个 List 值。这个 List 值是另一个 Cons 值,持有 2 和另一个 List 值。这个 List 值又是另一个 Cons 值,持有 3 和一个 List 值,最后是 Nil ,这是表示列表结束的非递归变体。

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.

如果我们尝试编译示例 15-3 中的代码,我们会得到如示例 15-4 所示的错误。

If we try to compile the code in Listing 15-3, we get the error shown in Listing 15-4.

{{#include ../listings/ch15-smart-pointers/listing-15-03/output.txt}}

错误显示该类型“具有无限大小”。原因是我们将 List 定义为一个具有递归性质的变体:它直接持有自身的另一个值。因此,Rust 无法弄清楚存储一个 List 值需要多少空间。让我们分解一下为什么我们会得到这个错误。首先,我们将看看 Rust 如何决定存储非递归类型的值需要多少空间。

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.

计算非递归类型的大小 (Computing the Size of a Non-Recursive Type)

回想我们在第 6 章讨论枚举定义时定义的 Message 枚举(示例 6-2):

Recall the Message enum we defined in Listing 6-2 when we discussed enum definitions in Chapter 6:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs:here}}
}

为了确定为 Message 值分配多少空间,Rust 遍历每个变体,看哪个变体需要的空间最多。Rust 看到 Message::Quit 不需要任何空间,Message::Move 需要足够的空间来存储两个 i32 值,依此类推。因为只会使用一个变体,所以 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.

与此相对,看看当 Rust 尝试确定像示例 15-2 中的 List 枚举这样的递归类型需要多少空间时会发生什么。编译器首先查看 Cons 变体,它持有一个 i32 类型的值和一个 List 类型的值。因此,Cons 需要的空间量等于 i32 的大小加上 List 的大小。为了算出 List 类型需要多少内存,编译器查看变体,从 Cons 变体开始。Cons 变体持有一个 i32 类型的值和一个 List 类型的值,这个过程无限持续下去,如图 15-1 所示。

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.

一个无限的 Cons list:一个标注为 'Cons' 的矩形被分成两个较小的矩形。第一个较小的矩形标注为 'i32',第二个较小的矩形标注为 'Cons' 且包含外部 'Cons' 矩形的一个较小版本。这些 'Cons' 矩形继续包含越来越小的自身版本,直到最小的尺寸合适的矩形包含一个无穷大符号,表明这种重复会永远持续下去。

图 15-1:一个由无限个 Cons 变体组成的无限 List

获得具有已知大小的递归类型 (Getting a Recursive Type with a Known Size)

因为 Rust 无法算出为递归定义的类型分配多少空间,编译器给出了一个带点建议的错误:

Because Rust can’t figure out how much space to allocate for recursively defined types, the compiler gives an error with this helpful suggestion:

help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
  |
2 |     Cons(i32, Box<List>),
  |               ++++    +

(建议:插入一些间接寻址(例如 BoxRc&)来打破循环)

在这个建议中,“间接寻址 (indirection)”意味着我们不应该直接存储值,而应该通过存储指向该值的指针来间接存储值。

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.

因为 Box<T> 是一个指针,所以 Rust 总是知道一个 Box<T> 需要多少空间:指针的大小不会根据它指向的数据量而改变。这意味着我们可以在 Cons 变体内部放入一个 Box<T> 而不是直接放入另一个 List 值。该 Box<T> 将指向下一个 List 值,该值将位于堆上而不是在 Cons 变体内部。从概念上讲,我们仍然有一个通过持有其他列表的列表而创建的列表,但现在的实现更像是将项相邻放置而不是相互包含。

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.

我们可以将示例 15-2 中的 List 枚举定义和示例 15-3 中的 List 用法更改为示例 15-5 中的代码,它将可以编译。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-05/src/main.rs}}
}

Cons 变体需要一个 i32 的大小加上存储 Box 指针数据的空间。Nil 变体不存储任何值,因此它在栈上需要的空间比 Cons 变体少。我们现在知道任何 List 值都将占用一个 i32 的大小加上 Box 指针数据的大小。通过使用 Box,我们打破了无限递归链,因此编译器可以算出存储 List 值所需的大小。图 15-2 显示了 Cons 变体现在的样子。

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 on the stack 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',第二个较小的矩形标注为 'Box',内部包含一个标注为 'usize' 的矩形,代表 Box 指针的有限大小。

图 15-2:一个不是无限大小的 List ,因为 Cons 持有一个 Box

Box 仅提供间接寻址和堆分配;它们没有我们在本章其余部分将看到的其他智能指针类型所具有的任何其他特殊功能。它们也没有这些特殊功能所带来的性能开销,因此在 cons list 这样间接寻址是我们唯一需要的功能的情况下很有用。我们将在第 18 章中看到 Box 的更多用例。

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 18.

Box<T> 类型是一个智能指针,因为它实现了 Deref 特征,这允许将 Box<T> 值视为引用。当 Box<T> 值超出作用域时,由于 Drop 特征的实现,Box 所指向的堆数据也会被清理。这两个特征对于我们将在本章其余部分讨论的其他智能指针类型所提供的功能将更加重要。让我们更详细地探讨这两个特征。

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.

像对待常规引用一样对待智能指针 (Treating Smart Pointers Like Regular References)


x-i18n: generated_at: “2026-03-01T14:33:03Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 36001d087e5aeabe658ce2689fe7c286c774fc74045841d62f6cf01108d0980e source_path: ch15-02-deref.md workflow: 16

像普通引用一样处理智能指针 (Treating Smart Pointers Like Regular References)

Treating Smart Pointers Like Regular References

实现 Deref 特征允许你自定义“解引用运算符 (dereference operator)” * (不要与乘法或通配符运算符混淆)的行为。通过以智能指针可以像普通引用一样被处理的方式实现 Deref ,你可以编写操作引用的代码,并将其同样用于智能指针。

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.

让我们先看看解引用运算符如何与普通引用配合使用。然后,我们将尝试定义一个行为类似于 Box<T> 的自定义类型,并看看为什么解引用运算符在我们的新定义类型上不像引用那样工作。我们将探索实现 Deref 特征如何使智能指针能够以类似于引用的方式工作。接着,我们将研究 Rust 的 deref 强制转换 (deref coercion) 功能,以及它如何让我们能够同时处理引用或智能指针。

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.

通过引用获取值 (Following the Reference to the Value)

Following the Reference to the Value

普通引用是一种指针类型,可以将指针看作是指向存储在别处的值的箭头。在示例 15-6 中,我们创建了一个 i32 值的引用,然后使用解引用运算符跟随引用获取该值。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-06/src/main.rs}}
}

变量 x 持有一个 i325 。我们将 y 设置为等于 x 的引用。我们可以断言 x 等于 5 。然而,如果我们想对 y 中的值进行断言,我们必须使用 *y 来跟随引用指向的值(因此称为“解引用 (dereference)”),以便编译器可以比较实际的值。一旦我们对 y 进行了解引用,我们就可以访问 y 指向的整数值,并将其与 5 进行比较。

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 that 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.

如果我们尝试改为编写 assert_eq!(5, y); ,我们将得到如下编译错误:

If we tried to write assert_eq!(5, y); instead, we would get this compilation error:

{{#include ../listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt}}

不允许将数字与数字引用进行比较,因为它们是不同的类型。我们必须使用解引用运算符来跟随引用指向的值。

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.

像引用一样使用 Box<T> (Using Box<T> Like a Reference)

Using Box<T> Like a Reference

我们可以重写示例 15-6 中的代码,使用 Box<T> 代替引用;在示例 15-7 中对 Box<T> 使用的解引用运算符的功能与示例 15-6 中对引用使用的解引用运算符的功能相同。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-07/src/main.rs}}
}

示例 15-7 和示例 15-6 之间的主要区别在于,这里我们将 y 设置为指向 x 的拷贝值的 Box 实例,而不是指向 x 值的引用。在最后一个断言中,我们可以使用解引用运算符来跟随 Box 的指针,就像 y 是引用时所做的那样。接下来,我们将通过定义自己的 Box 类型来探索 Box<T> 有什么特殊之处,从而使其能够使用解引用运算符。

The main difference between Listing 15-7 and Listing 15-6 is that here we set y to be an instance of a box 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 box’s pointer 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 box type.

定义我们自己的智能指针 (Defining Our Own Smart Pointer)

Defining Our Own Smart Pointer

让我们构建一个类似于标准库提供的 Box<T> 类型的包装器类型,以体验智能指针类型在默认情况下与引用的不同表现。然后,我们将看看如何添加使用解引用运算符的能力。

Let’s build a wrapper type similar to the Box<T> type provided by the standard library to experience how smart pointer types behave differently from references by default. Then, we’ll look at how to add the ability to use the dereference operator.

注意:我们将要构建的 MyBox<T> 类型与真实的 Box<T> 之间有一个很大的区别:我们的版本不会将其数据存储在堆上。本例我们将重点放在 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.

Box<T> 类型最终被定义为一个带有一个元素的元组结构体,所以示例 15-8 以同样的方式定义了一个 MyBox<T> 类型。我们还将定义一个 new 函数来匹配在 Box<T> 上定义的 new 函数。

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>.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-08/src/main.rs:here}}
}

我们定义了一个名为 MyBox 的结构体并声明了一个泛型参数 T ,因为我们希望我们的类型可以持有任何类型的值。MyBox 类型是一个元组结构体,具有一个 T 类型的元素。MyBox::new 函数接收一个 T 类型的参数并返回一个持有传入值的 MyBox 实例。

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.

让我们尝试将示例 15-7 中的 main 函数添加到示例 15-8 中,并将其更改为使用我们定义的 MyBox<T> 类型而不是 Box<T> 。示例 15-9 中的代码无法通过编译,因为 Rust 不知道如何对 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.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-09/src/main.rs:here}}

这是产生的编译错误:

Here’s the resultant compilation error:

{{#include ../listings/ch15-smart-pointers/listing-15-09/output.txt}}

我们的 MyBox<T> 类型不能被解引用,因为我们还没有在我们的类型上实现这种能力。为了启用 * 运算符进行解引用,我们需要实现 Deref 特征。

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.

实现 Deref 特征 (Implementing the Deref Trait)

Implementing the Deref Trait

正如在第 10 章“在类型上实现特征”中所讨论的,要实现一个特征,我们需要为特征要求的某些方法提供实现。由标准库提供的 Deref 特征要求我们实现一个名为 deref 的方法,该方法借用 self 并返回一个内部数据的引用。示例 15-10 包含了要添加到 MyBox<T> 定义中的 Deref 实现。

As discussed in “Implementing a Trait on a Type” in 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<T>.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-10/src/main.rs:here}}
}

type Target = T; 语法为 Deref 特征定义了一个关联类型。关联类型是声明泛型参数的一种略有不同的方式,但你现在不需要担心它们;我们将在第 20 章更详细地介绍它们。

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 20.

我们在 deref 方法体中填充了 &self.0 ,这样 deref 就会返回一个指向我们想用 * 运算符访问的值的引用;回想第 5 章“使用元组结构体创建不同的类型”部分可知, .0 用于访问元组结构体中的第一个值。示例 15-9 中在 MyBox<T> 值上调用 *main 函数现在可以编译了,并且断言通过了!

We fill in the body of the deref method with &self.0 so that deref returns a reference to the value we want to access with the * operator; recall from “Creating Different Types with Tuple Structs” in 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!

如果没有 Deref 特征,编译器只能对 & 引用进行解引用。 deref 方法赋予了编译器这样一种能力:获取任何实现了 Deref 的类型的值,并调用 deref 方法来获得一个它知道如何解引用的引用。

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.

当我们在示例 15-9 中输入 *y 时,在幕后 Rust 实际上运行了这段代码:

When we entered *y in Listing 15-9, behind the scenes Rust actually ran this code:

*(y.deref())

Rust 将 * 运算符替换为对 deref 方法的调用,然后再进行一次普通解引用,这样我们就不必思考是否需要调用 deref 方法。Rust 的这一特性让我们编写的代码在无论是普通引用还是实现了 Deref 的类型时,其功能都是完全相同的。

Rust substitutes the * operator with a call to the deref method and then a plain dereference so that 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.

deref 方法返回的是值的引用,而 *(y.deref()) 括号外的普通解引用仍然是必要的,这与所有权系统有关。如果 deref 方法直接返回该值而不是其引用,那么该值将被移出 self 。在这种情况下,或者在大多数使用解引用运算符的情况下,我们并不想获取 MyBox<T> 内部值的所有权。

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, has 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 in this case or in most cases where we use the dereference operator.

请注意,每当我们代码中使用 * 时, * 运算符会被替换为对 deref 方法的调用,然后再调用一次 * 运算符,仅此一次。因为 * 运算符的这种替换不会无限递归,所以我们最终得到了 i32 类型的数据,这与示例 15-9 中 assert_eq!5 相匹配。

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.

函数和方法中的解引用强制转换 (Using Deref Coercion in Functions and Methods)

Using Deref Coercion in Functions and Methods

“解引用强制转换 (Deref coercion)”可以将实现了 Deref 特征的类型的引用转换为另一种类型的引用。例如,解引用强制转换可以将 &String 转换为 &str ,因为 String 实现了 Deref 特征,使其返回 &str 。解引用强制转换是 Rust 在函数和方法参数上执行的一种便利操作,它仅适用于实现了 Deref 特征的类型。当我们向函数或方法传递特定类型的引用作为参数,而该参数类型与函数或方法定义中的不匹配时,它就会自动发生。一系列对 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 it 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.

解引用强制转换被加入 Rust 是为了让编写函数和方法调用的程序员不需要添加那么多使用 &* 的显式引用和解引用。解引用强制转换功能还让我们能编写更多同时适用于引用或智能指针的代码。

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.

为了看到解引用强制转换的实际应用,让我们使用示例 15-8 中定义的 MyBox<T> 类型,以及示例 15-10 中添加的 Deref 实现。示例 15-11 显示了一个带有字符串切片参数的函数定义。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-11/src/main.rs:here}}
}

我们可以使用字符串切片作为实参来调用 hello 函数,例如 hello("Rust"); 。由于有了解引用强制转换,可以使用 MyBox<String> 类型值的引用来调用 hello ,如示例 15-12 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-12/src/main.rs:here}}
}

在这里,我们正在调用 hello 函数,传入实参 &m ,它是对 MyBox<String> 值的引用。因为我们在示例 15-10 中在 MyBox<T> 上实现了 Deref 特征,Rust 可以通过调用 deref&MyBox<String> 转换为 &String 。标准库提供了 String 上的 Deref 实现,该实现返回一个字符串切片,这在 Deref 的 API 文档中可以找到。Rust 再次调用 deref&String 转换为 &str ,这与 hello 函数的定义相匹配。

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.

如果 Rust 没有实现解引用强制转换,为了使用 &MyBox<String> 类型的值调用 hello ,我们将不得不编写示例 15-13 中的代码,而不是示例 15-12 中的代码。

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>.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-13/src/main.rs:here}}
}

(*m)MyBox<String> 解引用为 String 。然后, &[..] 取得与整个字符串相等的 String 的字符串切片,以匹配 hello 的签名。如果没有解引用强制转换,这段涉及所有这些符号的代码将更难读、写和理解。解引用强制转换允许 Rust 为我们自动处理这些转换。

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.

当为所涉及的类型定义了 Deref 特征时,Rust 将分析这些类型并根据需要使用 Deref::deref 任意次,以获得与参数类型匹配的引用。需要插入 Deref::deref 的次数在编译时就已确定,因此利用解引用强制转换不会带来运行时损失!

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!

解引用强制转换如何与可变性交互 (Handling Deref Coercion with Mutable References)

Handling Deref Coercion with Mutable References

类似于你使用 Deref 特征覆盖不可变引用上的 * 运算符,你可以使用 DerefMut 特征覆盖可变引用上的 * 运算符。

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.

当 Rust 发现类型和特征实现在以下三种情况下,它会执行解引用强制转换:

Rust does deref coercion when it finds types and trait implementations in three cases:

  1. T: Deref<Target=U> 时,从 &T&U

  2. T: DerefMut<Target=U> 时,从 &mut T&mut U

  3. T: Deref<Target=U> 时,从 &mut T&U

  4. From &T to &U when T: Deref<Target=U>

  5. From &mut T to &mut U when T: DerefMut<Target=U>

  6. From &mut T to &U when T: Deref<Target=U>

前两种情况是相同的,除了第二种实现了可变性。第一种情况声明,如果你有一个 &T ,并且 T 实现了指向某种类型 UDeref ,你可以透明地获得一个 &U 。第二种情况声明,同样地解引用强制转换也发生在可变引用上。

The first two cases are the same 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.

第三种情况更为微妙:Rust 也会将可变引用强制转换为不可变引用。但反之则“不”可能:不可变引用永远不会强制转换为可变引用。由于借用规则,如果你有一个可变引用,那么该可变引用必须是该数据的唯一引用(否则,程序将无法通过编译)。将一个可变引用转换为一个不可变引用永远不会违反借用规则。将不可变引用转换为可变引用则要求初始的不可变引用是该数据的唯一不可变引用,但借用规则无法保证这一点。因此,Rust 无法假设将不可变引用转换为可变引用是可能的。

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.

使用 Drop Trait 在清理时运行代码 (Running Code on Cleanup with the Drop Trait)


x-i18n: generated_at: “2026-03-01T14:33:44Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: b7be9004339b812131797124d5afc0658b35197e21de39d39ba7af814ad7488c source_path: ch15-03-drop.md workflow: 16

使用 Drop 特征在清理时运行代码 (Running Code on Cleanup with the Drop Trait)

Running Code on Cleanup with the Drop Trait

对智能指针模式很重要的第二个特征是 Drop ,它允许你自定义当一个值即将超出作用域时发生的事情。你可以在任何类型上提供 Drop 特征的实现,该代码可用于释放资源,如文件或网络连接。

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 特征的功能。例如,当一个 Box<T> 被丢弃时,它会释放 Box 指向的堆空间。

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.

在某些语言中,对于某些类型,程序员每次使用完这些类型的实例后,必须调用代码来释放内存或资源。例子包括文件句柄、套接字 (sockets) 和锁 (locks)。如果程序员忘记了,系统可能会过载并崩溃。在 Rust 中,你可以指定每当一个值超出作用域时运行的一段特定代码,编译器将自动插入这段代码。因此,你不需要小心翼翼地在程序中使用完某个特定类型实例的每个地方放置清理代码——你仍然不会泄露资源!

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, and locks. If the programmer forgets, 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!

你通过实现 Drop 特征来指定值超出作用域时运行的代码。 Drop 特征要求你实现一个名为 drop 的方法,该方法接收一个对 self 的可变引用。为了看看 Rust 何时调用 drop ,我们目前先用 println! 语句来实现 drop

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.

示例 15-14 展示了一个 CustomSmartPointer 结构体,其唯一的自定义功能是当实例超出作用域时打印 Dropping CustomSmartPointer! ,以此展示 Rust 何时运行 drop 方法。

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 method.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-14/src/main.rs}}
}

Drop 特征包含在 prelude(预导入)中,所以我们不需要将其引入作用域。我们在 CustomSmartPointer 上实现 Drop 特征,并为调用 println!drop 方法提供了一个实现。 drop 方法体是你放置当类型实例超出作用域时想要运行的任何逻辑的地方。我们在这里打印一些文本,以便直观地演示 Rust 何时调用 drop

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 method 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.

main 中,我们创建了两个 CustomSmartPointer 实例,然后打印 CustomSmartPointers created 。在 main 结束时,我们的 CustomSmartPointer 实例将超出作用域,Rust 将调用我们在 drop 方法中放入的代码,打印我们的最后一条消息。注意我们不需要显式调用 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.

当我们运行此程序时,我们将看到以下输出:

When we run this program, we’ll see the following output:

{{#include ../listings/ch15-smart-pointers/listing-15-14/output.txt}}

当我们的实例超出作用域时,Rust 自动为我们调用了 drop ,运行了我们指定的代码。变量按其创建的相反顺序被丢弃,因此 dc 之前被丢弃。这个例子的目的是为你提供一个关于 drop 方法如何工作的直观指南;通常你会指定你的类型需要运行的清理代码,而不是一条打印消息。

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.

不幸的是,禁用自动 drop 功能并不直接。通常不需要禁用 dropDrop 特征的全部意义就在于它是自动处理的。然而,有时你可能想提前清理一个值。一个例子是使用管理锁的智能指针:你可能想强制调用释放锁的 drop 方法,以便同一作用域内的其他代码可以获取锁。Rust 不允许你手动调用 Drop 特征的 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.

通过修改示例 15-14 中的 main 函数来尝试手动调用 Drop 特征的 drop 方法是行不通的,如示例 15-15 所示。

Trying to call the Drop trait’s drop method manually by modifying the main function from Listing 15-14 won’t work, as shown in Listing 15-15.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-15/src/main.rs:here}}

当我们尝试编译这段代码时,我们会得到这个错误:

When we try to compile this code, we’ll get this error:

{{#include ../listings/ch15-smart-pointers/listing-15-15/output.txt}}

这条错误消息指出,我们不被允许显式调用 drop 。错误消息使用了术语“析构函数 (destructor)”,这是编程中对清理实例的函数的通用术语。“析构函数”类似于“构造函数 (constructor)”,后者创建实例。Rust 中的 drop 函数就是一个特定的析构函数。

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.

Rust 不允许我们显式调用 drop ,因为 Rust 仍然会在 main 结束时自动在该值上调用 drop 。这将导致双重释放错误,因为 Rust 将尝试两次清理同一个值。

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.

我们无法禁用值超出作用域时 drop 的自动插入,我们也无法显式调用 drop 方法。因此,如果我们需要强制提前清理一个值,我们使用 std::mem::drop 函数。

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.

std::mem::drop 函数与 Drop 特征中的 drop 方法不同。我们通过传入想要强制丢弃的值作为实参来调用它。该函数包含在 prelude 中,所以我们可以修改示例 15-15 中的 main 来调用该 drop 函数,如示例 15-16 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-16/src/main.rs:here}}
}

运行这段代码将打印以下内容:

Running this code will print the following:

{{#include ../listings/ch15-smart-pointers/listing-15-16/output.txt}}

文本 Dropping CustomSmartPointer with data `some data`! 被打印在 CustomSmartPointer createdCustomSmartPointer dropped before the end of main 文本之间,表明 drop 方法代码在此时被调用来丢弃 c

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.

你可以通过多种方式使用 Drop 特征实现中指定的代码,使清理变得方便且安全:例如,你可以用它来创建你自己的内存分配器!有了 Drop 特征和 Rust 的所有权系统,你不需要记得去清理,因为 Rust 会自动完成。

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 仅被调用一次。

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.

现在我们已经研究了 Box<T> 和智能指针的一些特性,让我们看看标准库中定义的其他一些智能指针。

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.

Rc<T> 引用计数智能指针 (Rc<T>, the Reference Counted Smart Pointer)


x-i18n: generated_at: “2026-03-01T14:34:49Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 3ef419d9f6d39ad665238bd0ead40f7ad65485e8762a8f8f64dd13d7152e5868 source_path: ch15-04-rc.md workflow: 16

Rc<T> 引用计数智能指针 (Rc<T>, the Reference-Counted Smart Pointer)

Rc<T>, the Reference-Counted Smart Pointer

在大多数情况下,所有权是明确的:你清楚地知道哪个变量拥有给定的值。然而,有些情况下,一个值可能拥有多个所有者。例如,在图数据结构中,多个边可能指向同一个节点,而该节点在概念上归属于所有指向它的边。除非一个节点没有任何指向它的边,即没有所有者,否则它不应该被清理。

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.

你必须使用 Rust 类型 Rc<T> 来显式启用多重所有权,它是“引用计数 (reference counting)”的缩写。 Rc<T> 类型跟踪指向一个值的引用数量,以确定该值是否仍在使用。如果一个值的引用数量为零,则该值可以在不使任何引用变为无效的情况下被清理。

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.

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 an 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> 仅用于单线程场景。当我们在第 16 章讨论并发时,我们将介绍如何在多线程程序中进行引用计数。

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.

共享数据 (Sharing Data)

让我们回到示例 15-5 中的 cons list 示例。回想一下,我们使用 Box<T> 定义了它。这一次,我们将创建两个列表,它们都共享第三个列表的所有权。从概念上讲,这类似于图 15-3。

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.

一个标注为 'a' 指向三个元素的链表。第一个元素包含整数 5 并指向第二个元素。第二个元素包含整数 10 并指向第三个元素。第三个元素包含表示列表结束的值 'Nil';它不指向任何地方。一个标注为 'b' 的链表指向包含整数 3 并指向列表 'a' 第一个元素的元素。一个标注为 'c' 的链表指向包含整数 4 并同样指向列表 'a' 第一个元素的元素,因此列表 'b' 和 'c' 的尾部都是列表 'a'。

图 15-3:两个列表 bc 共享第三个列表 a 的所有权

我们将创建包含 510 的列表 a 。然后,我们将创建另外两个列表:以 3 开始的 b 和以 4 开始的 c 。列表 bc 随后都将继续指向包含 510 的第一个列表 a 。换句话说,两个列表将共享包含 510 的第一个列表。

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 the 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.

如示例 15-17 所示,尝试使用带有 Box<T>List 定义来实现此场景是行不通的。

Trying to implement this scenario using our definition of List with Box<T> won’t work, as shown in Listing 15-17.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-17/src/main.rs}}

当我们编译这段代码时,会得到这个错误:

When we compile this code, we get this error:

{{#include ../listings/ch15-smart-pointers/listing-15-17/output.txt}}

Cons 变体拥有它们持有的数据,所以当我们创建列表 b 时, a 被移动到了 b 中, b 拥有了 a 。然后,当我们尝试在创建 c 时再次使用 a 时,是不允许的,因为 a 已经被移动了。

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 的定义以持有引用,但那样我们就必须指定生命周期参数。通过指定生命周期参数,我们将指定列表中的每个元素至少与整个列表一样长。在示例 15-17 的元素和列表中确实如此,但并不是每个场景都如此。

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.

相反,我们将更改 List 的定义,使用 Rc<T> 代替 Box<T> ,如示例 15-18 所示。每个 Cons 变体现在将持有一个值和一个指向 ListRc<T> 。当我们创建 b 时,不是获取 a 的所有权,而是克隆 a 持有的 Rc<List> ,从而将引用计数从一增加到二,并让 ab 共享该 Rc<List> 中的数据。在创建 c 时我们也克隆 a ,将引用计数从二增加到三。每次我们调用 Rc::clone ,指向 Rc<List> 内数据的引用计数就会增加,除非引用计数为零,否则数据不会被清理。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-18/src/main.rs}}
}

我们需要添加一个 use 语句将 Rc<T> 引入作用域,因为它不在 prelude 中。在 main 中,我们创建了持有 510 的列表并将其存储在 a 中的一个新 Rc<List> 中。然后,当我们创建 bc 时,我们调用 Rc::clone 函数并传入 aRc<List> 的引用作为实参。

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.

我们本可以调用 a.clone() 而不是 Rc::clone(&a) ,但 Rust 的惯例是在这种情况下使用 Rc::cloneRc::clone 的实现并不像大多数类型的 clone 实现那样对所有数据进行深拷贝。对 Rc::clone 的调用只会增加引用计数,这并不会花费太多时间。数据的深拷贝可能会花费很多时间。通过为引用计数使用 Rc::clone ,我们可以直观地将深拷贝类型的克隆与增加引用计数的克隆区分开来。当查找代码中的性能问题时,我们只需要考虑深拷贝克隆,而可以忽略对 Rc::clone 的调用。

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.

通过克隆增加引用计数 (Cloning to Increase the Reference Count)

Cloning to Increase the Reference Count

让我们更改示例 15-18 中的可行示例,以便我们可以看到当我们创建和丢弃对 aRc<List> 的引用时,引用计数是如何变化的。

Let’s change our working example in Listing 15-18 so that we can see the reference counts changing as we create and drop references to the Rc<List> in a.

在示例 15-19 中,我们将更改 main ,使其在列表 c 周围有一个内部作用域;然后,我们可以看到当 c 超出作用域时引用计数是如何变化的。

In Listing 15-19, we’ll change main so that it has an inner scope around list c; then, we can see how the reference count changes when c goes out of scope.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-19/src/main.rs:here}}
}

在程序中引用计数发生变化的每个点,我们都打印引用计数,这是通过调用 Rc::strong_count 函数获得的。此函数命名为 strong_count 而非 count ,是因为 Rc<T> 类型也有一个 weak_count ;我们将在“使用 Weak<T> 防止引用循环”中看到 weak_count 的用途。

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 “Preventing Reference Cycles Using Weak<T>.

这段代码打印以下内容:

{{#include ../listings/ch15-smart-pointers/listing-15-19/output.txt}}

我们可以看到 a 中的 Rc<List> 初始引用计数为 1;然后,每次我们调用 clone 时,计数都会增加 1。当 c 超出作用域时,计数会减少 1。我们不需要像调用 Rc::clone 增加引用计数那样通过调用函数来减少引用计数:当 Rc<T> 值超出作用域时, Drop 特征的实现会自动减少引用计数。

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.

在这个例子中我们看不出的是,当 main 结束时 b 然后 a 超出作用域,计数变为 0, Rc<List> 被完全清理。使用 Rc<T> 允许单个值拥有多个所有者,且计数确保了只要任何所有者仍然存在,该值就保持有效。

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 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.

通过不可变引用, Rc<T> 允许你在程序的多个部分之间共享数据以仅进行读取。如果 Rc<T> 也允许你拥有多个可变引用,你可能会违反第 4 章讨论的借用规则之一:对同一地点的多个可变借用会导致数据竞争和不一致。但是能够修改数据非常有用!在下一节中,我们将讨论内部可变性模式以及 RefCell<T> 类型,你可以将其与 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.

RefCell<T> 与内部可变性模式 (RefCell<T> and the Interior Mutability Pattern)


x-i18n: generated_at: “2026-03-01T14:36:13Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 44b89630fd7ba91ef3916854e849623118219d900adb94ad1e13a870a3dba8ed source_path: ch15-05-interior-mutability.md workflow: 16

RefCell<T> 与内部可变性模式 (RefCell<T> and the Interior Mutability Pattern)

RefCell<T> and the Interior Mutability Pattern

“内部可变性 (Interior mutability)”是 Rust 中的一种设计模式,它允许你即使在存在该数据的不可变引用时也可以修改数据;通常,借用规则是不允许这种操作的。为了修改数据,该模式在数据结构内部使用了 unsafe(不安全)代码来绕过 Rust 通常控制修改和借用的规则。不安全代码向编译器表明,我们是在手动检查规则,而不是依赖编译器为我们检查;我们将在第 20 章更多地讨论不安全代码。

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 20.

只有当我们能确保在运行时遵循借用规则时,即使编译器无法保证这一点,我们才能使用采用了内部可变性模式的类型。所涉及的 unsafe 代码随后会被包裹在一个安全的 API 中,而外部类型仍然是不可变的。

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.

让我们通过研究遵循内部可变性模式的 RefCell<T> 类型来探索这个概念。

Let’s explore this concept by looking at the RefCell<T> type that follows the interior mutability pattern.

在运行时强制执行借用规则 (Enforcing Borrowing Rules at Runtime)

Enforcing Borrowing Rules at Runtime

Rc<T> 不同, RefCell<T> 类型代表对其持有的数据的单一所有权。那么,是什么让 RefCell<T> 与像 Box<T> 这样的类型不同呢?回想一下你在第 4 章中学到的借用规则:

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:

  • 在任何给定时间,你“要么”拥有一个可变引用,“要么”拥有任意数量的不可变引用(但不能两者都有)。

  • 引用必须始终有效。

  • At any given time, you can have either one mutable reference or any number of immutable references (but not both).

  • References must always be valid.

对于引用和 Box<T> ,借用规则的不变量是在编译时强制执行的。而对于 RefCell<T> ,这些不变量是在“运行时”强制执行的。对于引用,如果你违反了这些规则,你会得到一个编译器错误。对于 RefCell<T> ,如果你违反了这些规则,你的程序将引发恐慌并退出。

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.

在编译时检查借用规则的优势在于,错误会在开发过程的早期被发现,并且由于所有的分析都已预先完成,因此不会对运行时性能产生影响。出于这些原因,在大多数情况下,在编译时检查借用规则是最佳选择,这就是 Rust 将其设为默认设置的原因。

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 编译器)本质上是保守的。通过分析代码,有些代码属性是无法检测到的:最著名的例子是停机问题 (Halting Problem),这超出了本书的范围,但它是一个值得研究的有趣话题。

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 编译器无法确定代码符合所有权规则,它可能会拒绝一个正确的程序;从这个意义上说,它是保守的。如果 Rust 接受了一个不正确的程序,用户就无法信任 Rust 所做的保证。然而,如果 Rust 拒绝了一个正确的程序,虽然会给程序员带来不便,但不会发生灾难性的后果。当你确信你的代码遵循了借用规则,但编译器无法理解和保证这一点时, RefCell<T> 类型就派上用场了。

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 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.

类似于 Rc<T>RefCell<T> 仅用于单线程场景,如果你尝试在多线程上下文中使用它,它会给你一个编译时错误。我们将在第 16 章讨论如何在多线程程序中获得 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.

这里回顾一下选择 Box<T>Rc<T>RefCell<T> 的原因:

Here is a recap of the reasons to choose Box<T>, Rc<T>, or RefCell<T>:

  • Rc<T> 允许同一数据拥有多个所有者; Box<T>RefCell<T> 则只有一个所有者。

  • Box<T> 允许在编译时检查不可变或可变借用; Rc<T> 仅允许在编译时检查不可变借用; RefCell<T> 允许在运行时检查不可变或可变借用。

  • 因为 RefCell<T> 允许在运行时检查可变借用,所以即使当 RefCell<T> 是不可变的时,你也可以修改其内部的值。

  • Rc<T> enables multiple owners of the same data; Box<T> and RefCell<T> have single owners.

  • 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.

  • Because RefCell<T> allows mutable borrows checked at runtime, you can mutate the value inside the RefCell<T> even when the RefCell<T> is immutable.

在不可变值内部修改值就是内部可变性模式。让我们看一个内部可变性有用的场景,并研究它是如何实现的。

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.

使用内部可变性 (Using Interior Mutability)

Using Interior Mutability

借用规则的一个后果是,当你有一个不可变值时,你不能对其进行可变借用。例如,这段代码无法通过编译:

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:

{{#rustdoc_include ../listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs}}

如果你尝试编译这段代码,你会得到以下错误:

If you tried to compile this code, you’d get the following error:

{{#include ../listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt}}

然而,在某些情况下,一个值在它的方法内部修改自身,但对其他代码表现为不可变是非常有用的。值的方法之外的代码将无法修改该值。使用 RefCell<T> 是获得内部可变性能力的一种方式,但 RefCell<T> 并没有完全绕过借用规则:编译器中的借用检查器允许这种内部可变性,而借用规则改为在运行时进行检查。如果你违反了规则,你将得到一个 panic! 而不是编译器错误。

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> 来修改一个不可变值,并了解为什么这很有用。

Let’s work through a practical example where we can use RefCell<T> to mutate an immutable value and see why that is useful.

使用模拟对象进行测试 (Testing with Mock Objects)

有时在测试期间,程序员会使用一种类型代替另一种类型,以便观察特定行为并断言其实现是否正确。这种占位符类型被称为“测试双倍 (test double)”。可以将其理解为电影制作中的替身演员(stunt double),某个人介入并代替演员完成一场特别棘手的戏。当我们运行测试时,测试双倍会替代其他类型。 “模拟对象 (Mock objects)” 是一种特定类型的测试双倍,它记录测试期间发生的事情,以便你可以断言正确的动作确实发生了。

Sometimes during testing a programmer will use a type in place of another type, in order to observe particular behavior and assert that 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 particularly 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 that you can assert that the correct actions took place.

Rust 没有像其他语言那样具有“对象”的概念,并且 Rust 在其标准库中也没有像其他一些语言那样内置模拟对象功能。然而,你绝对可以创建一个结构体来实现与模拟对象相同的目的。

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.

这是我们要测试的场景:我们将创建一个库,它跟踪一个值相对于最大值的进度,并根据当前值与最大值的接近程度发送消息。例如,该库可以用来跟踪用户被允许进行的 API 调用数量配额。

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.

我们的库仅提供跟踪值与最大值的接近程度以及在什么时间应该发送什么消息的功能。使用我们库的应用程序应提供发送消息的机制:应用程序可以直接向用户显示消息、发送电子邮件、发送短信或执行其他操作。库不需要了解这些细节。它只需要一些实现了我们将提供的名为 Messenger 的特征的东西。示例 15-20 显示了库代码。

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 show the message to the user directly, send an email, send a text message, or do 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.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-20/src/lib.rs}}

这段代码的一个重要部分是, Messenger 特征有一个名为 send 的方法,它接收对 self 的不可变引用和消息文本。这个特征是我们的模拟对象需要实现的接口,以便模拟对象可以像真实对象一样被使用。另一个重要部分是,我们想要测试 LimitTrackerset_value 方法的行为。我们可以改变为 value 参数传入的值,但 set_value 不返回任何内容供我们进行断言。我们想要做到的是,如果我们创建一个带有实现了 Messenger 特征的东西和特定 max 值的 LimitTracker ,那么当我们传入不同的 value 数字时,信使 (messenger) 会被告知发送适当的消息。

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, the messenger is told to send the appropriate messages when we pass different numbers for value.

我们需要一个模拟对象,当调用 send 时,它不发送电子邮件或短信,而只是记录被告知要发送的消息。我们可以创建一个模拟对象的新实例,创建一个使用该模拟对象的 LimitTracker ,调用 LimitTracker 上的 set_value 方法,然后检查模拟对象是否具有我们预期的消息。示例 15-21 展示了实现模拟对象以达到此目的的一次尝试,但借用检查器不允许这样做。

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.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-21/src/lib.rs:here}}

此测试代码定义了一个 MockMessenger 结构体,该结构体具有一个 sent_messages 字段,其包含一个 String 值的 Vec 以记录其被告知要发送的消息。我们还定义了一个关联函数 new ,以便方便地创建以空消息列表开始的新 MockMessenger 值。然后我们为 MockMessenger 实现 Messenger 特征,以便我们可以将 MockMessenger 交给 LimitTracker 。在 send 方法的定义中,我们将作为参数传入的消息存储在 MockMessengersent_messages 列表中。

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 that 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.

在测试中,我们正在测试当 LimitTracker 被告知将 value 设置为超过 max 值的 75% 时会发生什么。首先,我们创建一个新的 MockMessenger ,它将以一个空的消息列表开始。然后,我们创建一个新的 LimitTracker ,并给它一个指向新 MockMessenger 的引用和 100max 值。我们调用 LimitTracker 上的 set_value 方法,传入 80 的值,这超过了 100 的 75%。然后,我们断言 MockMessenger 正在记录的消息列表现在应该包含一条消息。

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.

然而,这个测试有一个问题,如下所示:

However, there’s one problem with this test, as shown here:

{{#include ../listings/ch15-smart-pointers/listing-15-21/output.txt}}

我们无法修改 MockMessenger 以记录消息,因为 send 方法接收的是 self 的不可变引用。我们也不能采取错误文本中的建议,在 impl 方法和特征定义中都使用 &mut self 。我们不想仅仅为了测试而更改 Messenger 特征。相反,我们需要找到一种方法,让我们的测试代码在现有的设计下能够正确运行。

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 in both the impl method and the trait definition. We do not want to change the Messenger trait solely for the sake of testing. Instead, we need to find a way to make our test code work correctly with our existing design.

这就是内部可变性可以提供帮助的情况!我们将 sent_messages 存储在 RefCell<T> 中,然后 send 方法就能够修改 sent_messages 以存储我们见过的消息。示例 15-22 展示了它的样子。

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.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-22/src/lib.rs:here}}

sent_messages 字段现在的类型是 RefCell<Vec<String>> 而不是 Vec<String> 。在 new 函数中,我们在空向量周围创建一个新的 RefCell<Vec<String>> 实例。

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.

对于 send 方法的实现,第一个参数仍然是 self 的不可变借用,这符合特征定义。我们对 self.sent_messages 中的 RefCell<Vec<String>> 调用 borrow_mut ,以获得对 RefCell<Vec<String>> 内部值(即向量)的可变引用。然后,我们可以对向量的可变引用调用 push ,以记录测试期间发送的消息。

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.

我们需要做的最后一处更改是在断言中:为了查看内部向量中有多少项,我们对 RefCell<Vec<String>> 调用 borrow 以获得对向量的不可变引用。

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<T> ,让我们深入了解它的工作原理!

Now that you’ve seen how to use RefCell<T>, let’s dig into how it works!

在运行时跟踪借用 (Tracking Borrows at Runtime)

Tracking Borrows at Runtime

在创建不可变和可变引用时,我们分别使用 &&mut 语法。对于 RefCell<T> ,我们使用 borrowborrow_mut 方法,它们属于 RefCell<T> 的安全 API。 borrow 方法返回智能指针类型 Ref<T> ,而 borrow_mut 返回智能指针类型 RefMut<T> 。两种类型都实现了 Deref ,所以我们可以像处理普通引用一样处理它们。

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.

RefCell<T> 跟踪当前有多少 Ref<T>RefMut<T> 智能指针处于活动状态。每次我们调用 borrowRefCell<T> 就会增加其活动不可变借用的计数。当一个 Ref<T> 值超出作用域时,不可变借用的计数就会减少 1。就像编译时借用规则一样, RefCell<T> 允许我们在任何时间点拥有许多不可变借用或一个可变借用。

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 1. 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> 的实现不会像引用那样产生编译器错误,而是在运行时引发恐慌。示例 15-23 显示了对示例 15-22 中 send 实现的修改。我们故意尝试在同一作用域内创建两个活动的可变借用,以说明 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.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-23/src/lib.rs:here}}

我们为 borrow_mut 返回的 RefMut<T> 智能指针创建了一个变量 one_borrow 。然后,我们在变量 two_borrow 中以相同的方式创建了另一个可变借用。这就在同一作用域内创建了两个可变引用,这是不允许的。当我们运行库的测试时,示例 15-23 中的代码将通过编译且没有任何错误,但测试会失败:

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:

{{#include ../listings/ch15-smart-pointers/listing-15-23/output.txt}}

注意,代码发生了恐慌,消息为 already borrowed: BorrowMutError 。这就是 RefCell<T> 在运行时处理违反借用规则的方式。

Notice that the code panicked with the message already borrowed: BorrowMutError. This is how RefCell<T> handles violations of the borrowing rules at runtime.

选择在运行时而不是编译时捕获借用错误,正如我们在这里所做的,意味着你可能会在开发过程的后期(甚至可能直到代码部署到生产环境之后)才发现代码中的错误。此外,由于在运行时跟踪借用,你的代码还会承担一小部分运行时性能开销。然而,使用 RefCell<T> 使得编写一个能够在仅允许不可变值的上下文中使用时修改自身的模拟对象成为可能。尽管有这些权衡,你仍然可以使用 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.

允许可变数据的多重所有权 (Allowing Multiple Owners of Mutable Data)

使用 RefCell<T> 的一种常见方法是将其与 Rc<T> 结合使用。回想一下, Rc<T> 让你能够为一个数据拥有多个所有者,但它仅提供对该数据的不可变访问。如果你拥有一个持有 RefCell<T>Rc<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!

例如,回想示例 15-18 中的 cons list 示例,我们在那里使用 Rc<T> 允许多个列表共享另一个列表的所有权。因为 Rc<T> 仅持有不可变值,所以一旦创建了列表,我们就无法更改列表中的任何值。让我们加入 RefCell<T> 以获得更改列表中值的能力。示例 15-24 显示了通过在 Cons 定义中使用 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> for its 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-24/src/main.rs}}
}

我们创建了一个 Rc<RefCell<i32>> 实例的值并将其存储在名为 value 的变量中,以便稍后直接访问它。然后,我们在 a 中创建了一个具有持有 valueCons 变体的 List 。我们需要克隆 value ,以便 avalue 都拥有内部值 5 的所有权,而不是将所有权从 value 转移到 a ,或者让 a 借用自 value

We create a value that is an instance of Rc<RefCell<i32>> and store it in a variable named value so that 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 that 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.

我们将列表 a 包裹在 Rc<T> 中,这样当我们创建列表 bc 时,它们都可以引用 a ,这就是我们在示例 15-18 中所做的。

We wrap the list a in an Rc<T> so that when we create lists b and c, they can both refer to a, which is what we did in Listing 15-18.

在我们创建了 abc 中的列表后,我们想给 value 中的值加 10。我们通过在 value 上调用 borrow_mut 来实现这一点,它使用了我们在第 5 章-> 运算符在哪?”中讨论过的自动解引用功能,将 Rc<T> 解引用为内部的 RefCell<T> 值。 borrow_mut 方法返回一个 RefMut<T> 智能指针,我们对其使用解引用运算符并更改内部值。

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 “Where’s the -> Operator?” in Chapter 5 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.

当我们打印 abc 时,我们可以看到它们都具有修改后的值 15 而不是 5

{{#include ../listings/ch15-smart-pointers/listing-15-24/output.txt}}

这种技术非常巧妙!通过使用 RefCell<T> ,我们得到了一个外表不可变的 List 值。但我们可以使用 RefCell<T> 上提供访问其内部可变性的方法,以便在需要时修改我们的数据。借用规则的运行时检查保护我们免受数据竞争的影响,有时为了这种数据结构的灵活性,牺牲一点速度是值得的。请注意, RefCell<T> 不适用于多线程代码! Mutex<T>RefCell<T> 的线程安全版本,我们将在第 16 章讨论 Mutex<T>

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 that 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.

引用循环会导致内存泄漏 (Reference Cycles Can Leak Memory)


x-i18n: generated_at: “2026-03-01T14:37:07Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 63e59efb318ea3cf88df11b3f87528bd221abfd25174f8a0388a445c41018e71 source_path: ch15-06-reference-cycles.md workflow: 16

引用循环可能导致内存泄漏 (Reference Cycles Can Leak Memory)

Reference Cycles Can Leak Memory

Rust 的内存安全保证使其很难(但并非不可能)意外地创建永远不会被清理的内存(即“内存泄漏 (memory leak)”)。完全防止内存泄漏并不是 Rust 的保证之一,这意味着内存泄漏在 Rust 中是内存安全的。我们可以看到,通过使用 Rc<T>RefCell<T> ,Rust 允许发生内存泄漏:可以创建项与项之间循环引用的引用。这会产生内存泄漏,因为循环中每个项的引用计数永远不会达到 0,值也永远不会被丢弃。

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.

创建引用循环 (Creating a Reference Cycle)

让我们看看引用循环是如何发生的,以及如何防止它,首先从示例 15-25 中的 List 枚举定义和 tail 方法开始。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-25/src/main.rs:here}}
}

我们使用的是示例 15-5 中 List 定义的另一个变体。 Cons 变体中的第二个元素现在是 RefCell<Rc<List>> ,这意味着与其像我们在示例 15-24 中那样具有修改 i32 值的能力,我们现在想修改 Cons 变体指向的 List 值。我们还添加了一个 tail 方法,以便在拥有 Cons 变体时方便地访问第二个项。

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-26 中,我们添加了一个 main 函数,它使用示例 15-25 中的定义。这段代码在 a 中创建了一个列表,在 b 中创建了一个指向 a 中列表的列表。然后,它修改 a 中的列表以指向 b ,从而创建一个引用循环。在此过程中有 println! 语句来显示该过程各个点的引用计数。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-26/src/main.rs:here}}
}

我们在变量 a 中创建了一个持有 List 值的 Rc<List> 实例,初始列表为 5, Nil 。然后我们在变量 b 中创建了另一个持有 List 值的 Rc<List> 实例,它包含值 10 并且指向 a 中的列表。

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.

我们修改 a 使其指向 b 而非 Nil ,从而创建一个循环。我们通过使用 tail 方法获取 aRefCell<Rc<List>> 的引用来实现这一点,并将其放入变量 link 中。然后,我们在 RefCell<Rc<List>> 上使用 borrow_mut 方法,将其内部的值从持有 Nil 值的 Rc<List> 更改为 b 中的 Rc<List>

We modify a so that 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.

当我们运行这段代码时(暂时保持最后一条 println! 被注释掉),我们将得到以下输出:

When we run this code, keeping the last println! commented out for the moment, we’ll get this output:

{{#include ../listings/ch15-smart-pointers/listing-15-26/output.txt}}

在我们更改 a 中的列表以指向 b 之后, ab 中的 Rc<List> 实例的引用计数都是 2。在 main 结束时,Rust 丢弃变量 b ,这使 bRc<List> 实例的引用计数从 2 减少到 1。此时堆上 Rc<List> 所占用的内存不会被丢弃,因为其引用计数是 1,而不是 0。然后,Rust 丢弃 a ,这也使 aRc<List> 实例的引用计数从 2 减少到 1。该实例的内存也无法被丢弃,因为另一个 Rc<List> 实例仍然引用它。分配给列表的内存将永远保持未回收状态。为了可视化这个引用循环,我们创建了图 15-4。

The reference count of the Rc<List> instances in both a and b is 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 the diagram in Figure 15-4.

一个标注为 'a' 指向包含整数 5 的矩形。一个标注为 'b' 指向包含整数 10 的矩形。包含 5 的矩形指向包含 10 的矩形,包含 10 的矩形又指回包含 5 的矩形,形成一个循环。

图 15-4:列表 ab 互相指向的引用循环

如果你取消最后一条 println! 的注释并运行程序,Rust 将尝试打印这个循环: a 指向 bb 指向 a ,如此循环往复,直到栈溢出。

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.

与实际程序相比,本例中创建引用循环的后果并不是非常严重:在创建引用循环之后,程序立即就结束了。然而,如果一个更复杂的程序在循环中分配了大量内存并持有很长时间,程序将占用比它需要的更多的内存,并可能使系统超负荷,导致可用内存耗尽。

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.

创建引用循环并不容易,但也并非不可能。如果你拥有包含 Rc<T> 值或类似的内部可变性与引用计数嵌套组合类型的 RefCell<T> 值,你必须确保不创建循环;你不能指望 Rust 来捕获它们。创建引用循环是你程序中的一个逻辑 bug,你应该使用自动化测试、代码审查和其他软件开发实践来将其最小化。

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.

避免引用循环的另一种解决方案是重构你的数据结构,使某些引用表达所有权,而某些引用则不表达。因此,你可以拥有由某些所有权关系和一些非所有权关系组成的循环,并且只有所有权关系会影响一个值是否可以被丢弃。在示例 15-25 中,我们总是希望 Cons 变体拥有它们的列表,因此重构数据结构是不可行的。让我们看一个由父节点和子节点组成的图示例,看看非所有权关系何时是防止引用循环的一种合适方式。

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.

使用 Weak<T> 防止引用循环 (Preventing Reference Cycles Using Weak<T>)

Preventing Reference Cycles Using Weak<T>

到目前为止,我们已经演示了调用 Rc::clone 会增加 Rc<T> 实例的 strong_count (强引用计数),并且只有当其 strong_count 为 0 时 Rc<T> 实例才会被清理。你还可以通过调用 Rc::downgrade 并传递 Rc<T> 的引用,来创建指向 Rc<T> 实例内部值的弱引用。“强引用 (Strong references)” 是你可以共享 Rc<T> 实例所有权的方式。“弱引用 (Weak references)” 不表达所有权关系,它们的计数不会影响 Rc<T> 实例何时被清理。它们不会引起引用循环,因为一旦涉及的值的强引用计数为 0,任何涉及弱引用的循环都会被打破。

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::downgrade 时,你会得到一个 Weak<T> 类型的智能指针。调用 Rc::downgrade 不会将 Rc<T> 实例中的 strong_count 增加 1,而是将 weak_count (弱引用计数)增加 1。 Rc<T> 类型使用 weak_count 来跟踪存在多少个 Weak<T> 引用,类似于 strong_count 。区别在于 weak_count 不需要为 0 就能让 Rc<T> 实例被清理。

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.

因为 Weak<T> 引用的值可能已经被丢弃,要对 Weak<T> 指向的值执行任何操作,你必须确保该值仍然存在。通过在 Weak<T> 实例上调用 upgrade 方法来实现这一点,该方法将返回一个 Option<Rc<T>> 。如果 Rc<T> 值尚未被丢弃,你将得到 Some 结果;如果 Rc<T> 值已被丢弃,你将得到 None 结果。因为 upgrade 返回 Option<Rc<T>> ,Rust 将确保 Some 情况和 None 情况都得到处理,并且不会出现无效指针。

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.

举个例子,我们不再使用其项只知道下一个项的列表,而是创建一个其项知道其子项“以及”其父项的树。

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 child items and their parent items.

创建树形数据结构 (Creating a Tree Data Structure)

Creating a Tree Data Structure

首先,我们将构建一棵带有知道其子节点节点的树。我们将创建一个名为 Node 的结构体,它持有其自身的 i32 值以及对其子 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 child Node values:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-27/src/main.rs:here}}
}

我们希望一个 Node 拥有其子节点,并且我们希望与变量共享该所有权,以便我们可以直接访问树中的每个 Node 。为此,我们将 Vec<T> 项定义为 Rc<Node> 类型的值。我们还想修改哪些节点是另一个节点的子节点,所以我们在 childrenVec<Rc<Node>> 周围放了一个 RefCell<T>

We want a Node to own its children, and we want to share that ownership with variables so that 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>>.

接下来,我们将使用我们的结构体定义并创建一个名为 leafNode 实例,其值为 3 且没有子节点,以及另一个名为 branch 的实例,其值为 5 并且将 leaf 作为其子节点之一,如示例 15-27 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-27/src/main.rs:there}}
}

我们克隆了 leaf 中的 Rc<Node> 并将其存储在 branch 中,这意味着 leaf 中的 Node 现在有两个所有者: leafbranch 。我们可以通过 branch.childrenbranch 到达 leaf ,但没有办法从 leaf 到达 branch 。原因是 leaf 没有 branch 的引用,也不知道它们是相关的。我们希望 leaf 知道 branch 是它的父节点。我们接下来就做这件事。

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.

添加从子节点到其父节点的引用 (Adding a Reference from a Child to Its Parent)

为了让子节点意识到其父节点,我们需要在 Node 结构体定义中添加一个 parent 字段。困难在于决定 parent 的类型应该是什么。我们知道它不能包含 Rc<T> ,因为那会形成引用循环,即 leaf.parent 指向 branchbranch.children 指向 leaf ,这将导致它们的 strong_count 值永远不会为 0。

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.

换种方式思考这些关系,父节点应该拥有其子节点:如果父节点被丢弃,其子节点也应该被丢弃。然而,子节点不应该拥有其父节点:如果我们丢弃子节点,父节点应该仍然存在。这是一个弱引用的应用场景!

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!

所以,我们不使用 Rc<T> ,而是让 parent 的类型使用 Weak<T> ,具体来说是 RefCell<Weak<Node>> 。现在我们的 Node 结构体定义看起来像这样:

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:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-28/src/main.rs:here}}
}

一个节点将能够引用其父节点,但不拥有其父节点。在示例 15-28 中,我们更新 main 以使用这个新定义,以便 leaf 节点能够引用其父节点 branch

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 that the leaf node will have a way to refer to its parent, branch.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-28/src/main.rs:there}}
}

创建 leaf 节点看起来与示例 15-27 类似,除了 parent 字段: leaf 一开始没有父节点,所以我们创建了一个新的空 Weak<Node> 引用实例。

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.

此时,当我们尝试通过使用 upgrade 方法获取 leaf 的父节点引用时,我们得到了一个 None 值。我们在第一个 println! 语句的输出中看到了这一点:

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:

leaf parent = None

当我们创建 branch 节点时,它在 parent 字段中也将有一个新的 Weak<Node> 引用,因为 branch 没有父节点。我们仍然将 leaf 作为 branch 的子节点之一。一旦我们在 branch 中有了 Node 实例,我们就可以修改 leaf ,给它一个指向其父节点的 Weak<Node> 引用。我们在 leafparent 字段中的 RefCell<Weak<Node>> 上使用 borrow_mut 方法,然后使用 Rc::downgrade 函数从 branch 中的 Rc<Node> 创建一个指向 branchWeak<Node> 引用。

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.

当我们再次打印 leaf 的父节点时,这次我们将得到一个持有 branchSome 变体:现在 leaf 可以访问它的父节点了!当我们打印 leaf 时,我们也避免了像示例 15-26 中那样最终以栈溢出告终的循环; Weak<Node> 引用被打印为 (Weak)

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 parent = Some(Node { value: 5, parent: RefCell { value: (Weak) },
children: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) },
children: RefCell { value: [] } }] } })

没有无限的输出表明这段代码没有创建引用循环。我们也可以通过查看调用 Rc::strong_countRc::weak_count 得到的值来判断这一点。

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.

可视化 strong_countweak_count 的变化 (Visualizing Changes to strong_count and weak_count)

Visualizing Changes to strong_count and weak_count

让我们看看通过创建一个新的内部作用域并将 branch 的创建移动到该作用域中, Rc<Node> 实例的 strong_countweak_count 值是如何变化的。通过这样做,我们可以看到当 branch 被创建以及随后在它超出作用域时被丢弃时会发生什么。修改后的代码如示例 15-29 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-29/src/main.rs:here}}
}

创建 leaf 后,其 Rc<Node> 具有强计数 1 和弱计数 0。在内部作用域中,我们创建 branch 并将其与 leaf 关联,此时当我们打印计数时, branch 中的 Rc<Node> 将具有强计数 1 和弱计数 1(对应 leaf.parent 通过 Weak<Node> 指向 branch )。当我们打印 leaf 中的计数时,我们会看到它将具有强计数 2,因为 branch 现在在 branch.children 中存储了 leafRc<Node> 的克隆,但它仍将具有弱计数 0。

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.

当内部作用域结束时, branch 超出作用域, Rc<Node> 的强计数减少到 0,因此其 Node 被丢弃。来自 leaf.parent 的 1 个弱计数与 Node 是否被丢弃无关,因此我们没有得到任何内存泄漏!

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!

如果我们尝试在作用域结束后访问 leaf 的父节点,我们将再次得到 None 。在程序结束时, leaf 中的 Rc<Node> 具有强计数 1 和弱计数 0,因为变量 leaf 现在又是 Rc<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.

所有管理计数和值丢弃的逻辑都内置在 Rc<T>Weak<T> 及其 Drop 特征的实现中。通过在 Node 的定义中指定从子节点到其父节点的关系应该是 Weak<T> 引用,你就能够让父节点指向子节点,反之亦然,而不会创建引用循环和内存泄漏。

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.

总结 (Summary)

本章介绍了如何使用智能指针来做出与 Rust 对普通引用的默认保证不同的保证和权衡。 Box<T> 类型具有已知的大小并指向分配在堆上的数据。 Rc<T> 类型跟踪堆上数据的引用数量,以便数据可以拥有多个所有者。具有内部可变性的 RefCell<T> 类型为我们提供了一种类型,当我们既需要一个不可变类型但又需要更改该类型的内部值时可以使用它;它还在运行时而非编译时强制执行借用规则。

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 the 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.

还讨论了 DerefDrop 特征,它们实现了智能指针的大部分功能。我们探索了可能导致内存泄漏的引用循环,以及如何使用 Weak<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>.

如果本章引起了你的兴趣,并且你想实现自己的智能指针,请查看 “The Rustonomicon” 以获取更多有用信息。

If this chapter has piqued your interest and you want to implement your own smart pointers, check out “The Rustonomicon” for more useful information.

接下来,我们将讨论 Rust 中的并发。你甚至会了解到一些新的智能指针。

Next, we’ll talk about concurrency in Rust. You’ll even learn about a few new smart pointers.

无畏并发 (Fearless Concurrency)


x-i18n: generated_at: “2026-03-01T14:37:37Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 0101c582d4410d0136c4ef46195c3fa382438dc1a667cbe5d754605e2aa89fb2 source_path: ch16-00-concurrency.md workflow: 16

无畏并发 (Fearless Concurrency)

Fearless Concurrency

安全高效地处理并发编程是 Rust 的另一个主要目标。“并发编程 (Concurrent programming)”(程序的各部分独立执行)和“并行编程 (parallel programming)”(程序的各部分同时执行)正变得越来越重要,因为越来越多的计算机开始利用其多处理器的优势。从历史上看,在这些语境下进行编程一直很困难且容易出错。Rust 希望改变这一点。

Handling concurrent programming safely and efficiently is another of Rust’s major goals. Concurrent programming, in which different parts of a program execute independently, and parallel programming, in which 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 中的许多并发错误都是编译时错误,而不是运行时错误。因此,与其让你花费大量时间试图重现运行时并发错误发生的确切情况,不如让错误的代码拒绝编译并显示解释问题的错误。结果,你可以在编写代码时修复它,而不是可能在代码发布到生产环境后才修复。我们将 Rust 的这一方面昵称为“无畏并发 (fearless concurrency)”。无畏并发允许你编写没有微妙 bug 且易于重构而不会引入新 bug 的代码。

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.

注意:为了简单起见,我们将许多问题称为“并发 (concurrent)”,而不是更精确地称其为“并发和/或并行 (concurrent and/or parallel)”。在本章中,每当我们使用“并发”时,请在脑海中将其替换为“并发和/或并行”。在下一章中,这种区别更为重要,我们将更加具体。

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. For this chapter, please mentally substitute concurrent and/or parallel whenever we use concurrent. In the next chapter, where the distinction matters more, we’ll be more specific.

许多语言对于它们提供的处理并发问题的解决方案都是教条式的。例如,Erlang 具有优雅的消息传递并发功能,但只有晦涩难懂的方式在线程之间共享状态。对于高级语言来说,只支持可能解决方案的一个子集是一种合理的策略,因为高级语言承诺通过放弃一些控制来换取抽象带来的好处。然而,低级语言被期望在任何给定的情况下提供性能最佳的解决方案,并且对硬件的抽象较少。因此,Rust 提供了多种工具,让你能够以适合你的情况和要求的任何方式对问题进行建模。

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.

以下是我们在本章中将要介绍的主题:

  • 如何创建线程以同时运行多段代码
  • “消息传递 (Message-passing)”并发,其中通道 (channels) 在线程之间发送消息
  • “共享状态 (Shared-state)”并发,其中多个线程可以访问某段数据
  • SyncSend 特征,它们将 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 and Send traits, which extend Rust’s concurrency guarantees to user-defined types as well as types provided by the standard library

使用线程同时运行代码 (Using Threads to Run Code Simultaneously)


x-i18n: generated_at: “2026-03-01T14:38:55Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 84d2e46991bce433f8d50c29479e36fd0c7f62e735758c8a096ab4e1ebe58fe7 source_path: ch16-01-threads.md workflow: 16

使用线程同时运行代码 (Using Threads to Run Code Simultaneously)

Using Threads to Run Code Simultaneously

在大多数当前的操作系统中,执行程序的代码运行在“进程 (process)”中,操作系统将同时管理多个进程。在程序内部,你也可以拥有同时运行的独立部分。运行这些独立部分的功能被称为“线程 (threads)”。例如,一个 Web 服务器可以拥有多个线程,以便它能同时响应多个请求。

In most current operating systems, 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 can respond to more than one request at the same time.

将程序中的计算拆分为多个线程以同时运行多个任务可以提高性能,但也增加了复杂性。因为线程可以同时运行,所以无法固有地保证不同线程上代码部分的运行顺序。这可能导致一些问题,例如:

  • 竞态条件 (Race conditions),其中线程以不一致的顺序访问数据或资源
  • 死锁 (Deadlocks),其中两个线程互相等待,导致两个线程都无法继续
  • 仅在某些情况下发生的 bug,且很难可靠地重现和修复

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, in which threads are accessing data or resources in an inconsistent order
  • Deadlocks, in which two threads are waiting for each other, preventing both threads from continuing
  • Bugs that only happen in certain situations and are hard to reproduce and fix reliably

Rust 试图减轻使用线程的负面影响,但在多线程上下文中编程仍然需要深思熟虑,并需要一种与单线程运行程序不同的代码结构。

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.

编程语言实现线程的方式有几种,许多操作系统提供了编程语言可以调用以创建新线程的 API。Rust 标准库使用线程实现的“1:1”模型,即程序每个语言线程使用一个操作系统线程。有一些 crate 实现了其他线程模型,这些模型对 1:1 模型做出了不同的权衡。(Rust 的异步系统将在下一章介绍,它也提供了另一种并发方法。)

Programming languages implement threads in a few different ways, and many operating systems provide an API the programming 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 trade-offs to the 1:1 model. (Rust’s async system, which we will see in the next chapter, provides another approach to concurrency as well.)

使用 spawn 创建新线程 (Creating a New Thread with spawn)

Creating a New Thread with spawn

要创建一个新线程,我们调用 thread::spawn 函数并传递给它一个闭包(我们在第 13 章讨论过闭包),该闭包包含我们想要在新线程中运行的代码。示例 16-1 中的示例从主线程打印一些文本,并从新线程打印其他文本。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-01/src/main.rs}}
}

注意,当 Rust 程序的主线程完成时,所有生成的线程都会被关闭,无论它们是否已完成运行。该程序的输出每次可能会略有不同,但看起来类似于以下内容:

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:

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!

thread::sleep 的调用强制线程在短时间内停止执行,允许另一个线程运行。线程可能会轮流运行,但这并不能保证:这取决于你的操作系统如何调度线程。在这次运行中,尽管来自生成线程的打印语句在代码中首先出现,但主线程首先打印了。尽管我们告诉生成线程打印到 i 等于 9 为止,但在主线程关闭之前它只执行到了 5

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.

如果你运行此代码并且只看到主线程的输出,或者没有看到任何重叠,请尝试增加范围内的数字,以为操作系统提供更多在线程之间切换的机会。

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)

Waiting for All Threads to Finish

示例 16-1 中的代码不仅大多数时候由于主线程结束而提前停止了生成的线程,而且由于无法保证线程运行的顺序,我们也无法保证生成的线程根本会有机会运行!

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!

我们可以通过将 thread::spawn 的返回值保存在一个变量中来解决生成的线程未运行或提前结束的问题。 thread::spawn 的返回类型是 JoinHandle<T>JoinHandle<T> 是一个拥有所有权的值,当我们对其调用 join 方法时,它将等待其线程完成。示例 16-2 展示了如何使用我们在示例 16-1 中创建的线程的 JoinHandle<T> ,以及如何调用 join 以确保生成的线程在 main 退出之前完成。

We can fix the problem of the spawned thread not running or of it ending prematurely by saving the return value of thread::spawn in a variable. The return type of thread::spawn is JoinHandle<T>. A JoinHandle<T> 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<T> of the thread we created in Listing 16-1 and how to call join to make sure the spawned thread finishes before main exits.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-02/src/main.rs}}
}

在句柄上调用 join 会阻塞当前正在运行的线程,直到由该句柄代表的线程终止。“阻塞 (Blocking)”一个线程意味着该线程被阻止执行工作或退出。因为我们将 join 的调用放在了主线程的 for 循环之后,运行示例 16-2 应该产生类似于以下内容的输出:

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:

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!

这两个线程继续交替运行,但由于调用了 handle.join() ,主线程在等待,直到生成的线程完成后才结束。

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() 移动到 main 中的 for 循环“之前”,会发生什么,如下所示:

But let’s see what happens when we instead move handle.join() before the for loop in main, like this:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs}}
}

主线程将等待生成的线程完成,然后运行它的 for 循环,因此输出将不再交错,如下所示:

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:

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!

一些细微的细节,比如 join 在哪里被调用,都会影响你的线程是否在同一时间运行。

Small details, such as where join is called, can affect whether or not your threads run at the same time.

在线程中使用 move 闭包 (Using move Closures with Threads)

Using move Closures with Threads

我们经常会为传递给 thread::spawn 的闭包使用 move 关键字,因为这样闭包就会获取它从环境中使用的值的所有权,从而将这些值的所有权从一个线程转移到另一个线程。在第 13 章的“捕获引用或移动所有权”中,我们讨论了闭包背景下的 move 。现在我们将更多地关注 movethread::spawn 之间的交互。

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 “Capturing References or Moving Ownership” in Chapter 13, we discussed move in the context of closures. Now we’ll concentrate more on the interaction between move and thread::spawn.

注意在示例 16-1 中,我们传递给 thread::spawn 的闭包不接收任何参数:我们在生成的线程代码中没有使用来自主线程的任何数据。要在生成的线程中使用来自主线程的数据,生成的线程闭包必须捕获它所需的值。示例 16-3 展示了一次在主线程中创建一个向量并在生成的线程中使用它的尝试。然而,正如你很快就会看到的,这目前还行不通。

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 work yet, as you’ll see in a moment.

{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-03/src/main.rs}}

该闭包使用了 v ,因此它将捕获 v 并使其成为闭包环境的一部分。因为 thread::spawn 在一个新线程中运行此闭包,所以我们应该能够在那个新线程中访问 v 。但当我们编译这个例子时,我们得到了以下错误:

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:

{{#include ../listings/ch16-fearless-concurrency/listing-16-03/output.txt}}

Rust “推断” 如何捕获 v ,并且因为 println! 只需要一个 v 的引用,闭包尝试借用 v 。然而,有一个问题:Rust 无法判断生成的线程将运行多久,因此它不知道 v 的引用是否始终有效。

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 whether the reference to v will always be valid.

示例 16-4 提供了一个更有可能导致 v 的引用无效的场景。

Listing 16-4 provides a scenario that’s more likely to have a reference to v that won’t be valid.

{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-04/src/main.rs}}

如果 Rust 允许我们运行这段代码,则有一种可能性是生成的线程会立即被放到后台而根本没有运行。生成的线程内部有一个对 v 的引用,但主线程立即使用我们在第 15 章讨论过的 drop 函数丢弃了 v 。然后,当生成的线程开始执行时, v 就不再有效了,因此对它的引用也是无效的。噢不!

If Rust allowed us to run this code, there’s a possibility that 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!

要修复示例 16-3 中的编译器错误,我们可以使用错误消息的建议:

To fix the compiler error in Listing 16-3, we can use the error message’s advice:

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 || {
  |                                ++++

(帮助:要强制闭包获取 v(以及任何其他被引用的变量)的所有权,请使用 move 关键字)

通过在闭包前添加 move 关键字,我们强制闭包获取它所使用值的所有权,而不是允许 Rust 推断它应该借用这些值。对示例 16-3 进行修改后的示例 16-5 将按我们的意图编译并运行。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-05/src/main.rs}}
}

我们可能想尝试同样的事情来修复示例 16-4 中主线程通过使用 move 闭包调用 drop 的代码。然而,这一修复将行不通,因为示例 16-4 尝试做的操作由于另一个原因被禁止了。如果我们向闭包添加 move ,我们会将 v 移动到闭包的环境中,我们就不再能在主线程中对其调用 drop 了。我们会得到如下编译错误:

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:

{{#include ../listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt}}

Rust 的所有权规则再次救了我们!我们从示例 16-3 的代码中得到了一个错误,是因为 Rust 是保守的,仅为线程借用 v ,这意味着主线程理论上可以使生成的线程的引用无效。通过告诉 Rust 将 v 的所有权移动到生成的线程,我们就向 Rust 保证了主线程将不再使用 v 。如果我们以相同的方式更改示例 16-4,那么当我们尝试在主线程中使用 v 时就会违反所有权规则。 move 关键字覆盖了 Rust 保守的默认借用行为;它不代表我们可以违反所有权规则。

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 to 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.

既然我们已经介绍了线程是什么以及线程 API 提供的方法,让我们来看看一些可以使用线程的情况。

Now that we’ve covered what threads are and the methods supplied by the thread API, let’s look at some situations in which we can use threads.

通过消息传递在线程间转移数据 (Transfer Data Between Threads with Message Passing)


x-i18n: generated_at: “2026-03-01T14:39:53Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 883ed745d87151fa820cd337420a24f59cf8391d4ce87d2ee22af3bd278e05d1 source_path: ch16-02-message-passing.md workflow: 16

通过消息传递在线程间转移数据 (Transfer Data Between Threads with Message Passing)

确保安全并发的一种日益流行的方法是消息传递,即线程或 actor 通过相互发送包含数据的消息来进行通信。这里有来自 Go 语言文档的一个口号:“不要通过共享内存来通信;相反,通过通信来共享内存。”

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.”

为了实现消息发送并发,Rust 的标准库提供了一个通道(channels)的实现。“通道 (channel)”是一个通用的编程概念,数据通过它从一个线程发送到另一个线程。

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.

你可以把编程中的通道想象成一条有方向的水道,比如小溪或河流。如果你把一个橡皮鸭之类的东西放入河流,它会顺流而下到达水道的末端。

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 the rubber duck 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 with 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.

首先,在示例 16-6 中,我们将创建一个通道但不执行任何操作。请注意,这目前还无法编译,因为 Rust 无法判断我们想通过通道发送什么类型的值。

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.

{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-06/src/main.rs}}

我们使用 mpsc::channel 函数创建一个新通道; mpsc 代表“多个生产者,单个消费者 (multiple producer, single consumer)”。简而言之,Rust 标准库实现通道的方式意味着一个通道可以有多个产生值的“发送”端,但只能有一个消费这些值的“接收”端。想象一下多条小溪汇成一条大河:所有通过任何小溪发送的东西最终都会汇入尽头的一条河中。我们目前先从单个生产者开始,但当我们让这个例子运行起来后,我们会添加多个生产者。

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 函数返回一个元组,其第一个元素是发送端(发射器),第二个元素是接收端(接收器)。缩写 txrx 在许多领域中传统上分别用于“发射器 (transmitter)”和“接收器 (receiver)”,因此我们这样命名变量来指示每一端。我们正在使用带有模式的 let 语句来解构元组;我们将在第 19 章讨论 let 语句中模式的使用和解构。目前,只需知道以这种方式使用 let 语句是提取 mpsc::channel 返回的元组各部分的便捷方法。

The mpsc::channel function returns a tuple, the first element of which is the sending end—the transmitter—and the second element of which 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 19. For now, know that using a let statement in this way is a convenient approach to extract the pieces of the tuple returned by mpsc::channel.

让我们将发送端移动到一个生成的线程中,并让它发送一个字符串,以便生成的线程与主线程通信,如示例 16-7 所示。这就像在河流上游放入一只橡皮鸭,或者从一个线程向另一个线程发送聊天消息。

Let’s move the transmitting end into a spawned thread and have it send one string so that 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-07/src/main.rs}}
}

同样,我们使用 thread::spawn 创建一个新线程,然后使用 movetx 移动到闭包中,以便生成的线程拥有 tx 。生成的线程需要拥有发送端才能通过通道发送消息。

Again, we’re using thread::spawn to create a new thread and then using move to move tx into the closure so that the spawned thread owns tx. The spawned thread needs to own the transmitter to be able to send messages through the channel.

发送端有一个接收我们要发送的值的 send 方法。 send 方法返回一个 Result<T, E> 类型,所以如果接收端已经被丢弃并且没有地方可以发送值,发送操作将返回一个错误。在这个例子中,我们调用 unwrap 以便在出错时引发恐慌。但在实际应用程序中,我们会对其进行妥善处理:回到第 9 章回顾正确错误处理的策略。

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.

在示例 16-8 中,我们将从主线程的接收端获取该值。这就像从河流末端的水中取回橡皮鸭,或者接收一条聊天消息。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-08/src/main.rs}}
}

接收端有两个有用的方法: recvtry_recv 。我们使用的是 recv (receive 的缩写),它将阻塞主线程的执行并等待,直到有一个值被发送到通道。一旦发送了值, recv 将在 Result<T, E> 中返回它。当发送端关闭时, recv 将返回一个错误,表示不再有值到来。

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.

try_recv 方法不会阻塞,而是会立即返回一个 Result<T, E> :如果有一个消息可用,则返回一个持有该消息的 Ok 值;如果这一次没有任何消息,则返回一个 Err 值。如果线程在等待消息的同时还有其他工作要做,使用 try_recv 很有用:我们可以编写一个循环,每隔一段时间调用一次 try_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.

为了简单起见,我们在本例中使用了 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.

当我们运行示例 16-8 中的代码时,我们将看到主线程打印出的值:

When we run the code in Listing 16-8, we’ll see the value printed from the main thread:

Got: hi

完美!

Perfect!

通过通道转移所有权 (Transferring Ownership Through Channels)

Transferring Ownership Through Channels

所有权规则在消息发送中起着至关重要的作用,因为它们可以帮助你编写安全的并发代码。在整个 Rust 程序中考虑所有权的好处就是可以防止并发编程中的错误。让我们做一个实验,展示通道和所有权如何协同工作以防止问题:我们将尝试在将 val 值发送到通道“之后”在生成的线程中使用它。尝试编译示例 16-9 中的代码,看看为什么这种代码是不允许的。

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.

{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-09/src/main.rs}}

在这里,我们尝试在通过 tx.sendval 发送到通道后打印它。允许这样做会是个坏主意:一旦该值被发送到另一个线程,那个线程可能会在我们尝试再次使用该值之前修改或丢弃它。潜在地,由于数据不一致或不存在,另一个线程的修改可能会导致错误或意外结果。然而,如果我们尝试编译示例 16-9 中的代码,Rust 会给我们一个错误:

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:

{{#include ../listings/ch16-fearless-concurrency/listing-16-09/output.txt}}

我们的并发错误导致了编译时错误。 send 函数获取其参数的所有权,当值移动时,接收端就获取了它的所有权。这防止了我们在发送该值后意外地再次使用它;所有权系统会检查一切是否正常。

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.

发送多个值 (Sending Multiple Values)

Sending Multiple Values

示例 16-8 中的代码编译并运行了,但它并没有清晰地向我们展示两个独立的线程正在通过通道相互交谈。

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.

在示例 16-10 中,我们做了一些修改,这将证明示例 16-8 中的代码正在并发运行:生成的线程现在将发送多条消息,并在每条消息之间暂停一秒。

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.

{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-10/src/main.rs}}

这一次,生成的线程有一个我们想要发送到主线程的字符串向量。我们遍历它们,逐个发送,并在每个之间通过调用 thread::sleep 函数并传入一秒的 Duration 值来暂停。

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 one second.

在主线程中,我们不再显式调用 recv 函数:相反,我们将 rx 视为迭代器。对于接收到的每个值,我们都将其打印出来。当通道关闭时,迭代将结束。

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.

当运行示例 16-10 中的代码时,你应该看到以下输出,每行之间有一秒的暂停:

When running the code in Listing 16-10, you should see the following output with a one-second pause in between each line:

Got: hi
Got: from
Got: the
Got: thread

因为我们在主线程的 for 循环中没有任何暂停或延迟的代码,所以我们可以看出主线程正在等待从生成的线程接收值。

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.

创建多个生产者 (Creating Multiple Producers)

Creating Multiple Producers

早些时候我们提到 mpsc 是“多个生产者,单个消费者”的缩写。让我们应用 mpsc 并扩展示例 16-10 中的代码,创建多个线程,它们都向同一个接收端发送值。我们可以通过克隆发送端来实现这一点,如示例 16-11 所示。

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.

{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-11/src/main.rs:here}}

这一次,在我们创建第一个生成线程之前,我们在发送端上调用了 clone 。这将给我们一个新的发送端,我们可以将其传递给第一个生成线程。我们将原始发送端传递给第二个生成线程。这给了我们两个线程,每个线程都向那个唯一的接收端发送不同的消息。

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.

当你运行代码时,你的输出应该看起来像这样:

When you run the code, your output should look like something this:

Got: hi
Got: more
Got: from
Got: messages
Got: for
Got: the
Got: thread
Got: you

你可能会看到值的另一种顺序,这取决于你的系统。这就是并发之所以有趣也之所以困难的原因。如果你尝试使用 thread::sleep ,在不同的线程中给它赋予各种不同的值,那么每次运行都会更具非确定性,并且每次都会产生不同的输出。

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.

既然我们已经研究了通道的工作原理,让我们来看看另一种不同的并发方法。

Now that we’ve looked at how channels work, let’s look at a different method of concurrency.

共享状态并发 (Shared-State Concurrency)


x-i18n: generated_at: “2026-03-01T14:41:01Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 9aa8adf23ccf6ceaf7586b9aac35c30769bd13ebfbb8950a185d9b136104f10b source_path: ch16-03-shared-state.md workflow: 16

共享状态并发 (Shared-State Concurrency)

消息传递是处理并发的一种好方法,但并不是唯一的方法。另一种方法是让多个线程访问相同的共享数据。再次考虑来自 Go 语言文档的那部分口号:“不要通过共享内存来通信。”

Message passing is a fine way to handle concurrency, but it’s not the only way. 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.”

“通过共享内存来通信”会是什么样子的?此外,为什么消息传递的热衷者会警告不要使用内存共享?

What would communicating by sharing memory look like? In addition, why would message-passing enthusiasts caution not to use memory sharing?

在某种程度上,任何编程语言中的通道都类似于单一所有权,因为一旦你通过通道转移了一个值,你就不能再使用该值。共享内存并发类似于多重所有权:多个线程可以同时访问相同的内存位置。正如你在第 15 章中看到的,智能指针使多重所有权成为可能,但多重所有权会增加复杂性,因为这些不同的所有者需要管理。Rust 的类型系统和所有权规则极大地协助了这一管理的正确性。作为一个例子,让我们看看互斥锁 (mutexes),它是共享内存中较常见的并发原语之一。

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.

使用互斥锁控制访问 (Controlling Access with Mutexes)

“Mutex” 是“互斥 (mutual exclusion)”的缩写,也就是说,互斥锁在任何给定时间只允许一个线程访问某些数据。为了访问互斥锁中的数据,线程必须首先通过请求获取互斥锁的“锁 (lock)”来发出它想要访问的信号。锁是互斥锁的一部分,是一个记录当前谁拥有数据独占访问权的数据结构。因此,互斥锁被描述为通过锁定系统“保护 (guarding)”它所持有的数据。

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.

互斥锁因难以使用而声名狼藉,因为你必须记住两条规则:

  1. 在使用数据之前,必须尝试获取锁。
  2. 当你处理完互斥锁保护的数据后,必须对数据进行解锁,以便其他线程可以获取锁。

Mutexes have a reputation for being difficult to use because you have to remember two rules:

  1. You must attempt to acquire the lock before using the data.
  2. When you’re done with the data that the mutex guards, you must unlock the data so that 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!

管理互斥锁可能极其棘手,这也是为什么那么多人对通道充满热情的原因。然而,得益于 Rust 的类型系统和所有权规则,你不会弄错锁定和解锁。

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.

Mutex<T> 的 API (The API of Mutex<T>)

作为如何使用互斥锁的一个例子,让我们从在单线程上下文中使用互斥锁开始,如示例 16-12 所示。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-12/src/main.rs}}
}

与许多类型一样,我们使用关联函数 new 创建一个 Mutex<T> 。要访问互斥锁内部的数据,我们使用 lock 方法来获取锁。该调用将阻塞当前线程,使其无法执行任何工作,直到轮到我们获得锁为止。

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 that it can’t do any work until it’s our turn to have the lock.

如果另一个持有锁的线程发生了恐慌,那么对 lock 的调用将会失败。在这种情况下,任何人都无法获得锁,因此我们选择使用 unwrap ,如果处于这种情况,就让此线程发生恐慌。

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.

获取锁后,我们可以将返回值(在此例中命名为 num )视为指向内部数据的可变引用。类型系统确保了我们在使用 m 中的值之前获取了锁。 m 的类型是 Mutex<i32> 而不是 i32 ,所以我们“必须”调用 lock 才能使用 i32 值。我们不会忘记;否则类型系统不会让我们访问内部的 i32

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.

lock 的调用返回一个名为 MutexGuard 的类型,该类型被包裹在我们用 unwrap 调用处理的 LockResult 中。 MutexGuard 类型实现了 Deref 指向我们的内部数据;该类型还具有 Drop 实现,当 MutexGuard 超出作用域(发生于内部作用域结束时)时会自动释放锁。因此,我们没有忘记释放锁并阻止互斥锁被其他线程使用的风险,因为锁的释放是自动发生的。

The call to lock returns a type called MutexGuard, wrapped in a LockResult that we handled with the call to unwrap. The MutexGuard type implements Deref to point at our inner data; the type 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.

丢弃锁后,我们可以打印互斥锁的值,看到我们能够将内部的 i32 更改为 6

After dropping the lock, we can print the mutex value and see that we were able to change the inner i32 to 6.

多线程共享 Mutex<T> (Shared Access to Mutex<T>)

Shared Access to Mutex<T>

现在让我们尝试使用 Mutex<T> 在多个线程之间共享一个值。我们将启动 10 个线程,并让它们各自将计数器的值增加 1,使计数器从 0 增加到 10。示例 16-13 中的例子将出现编译器错误,我们将利用该错误来了解更多关于使用 Mutex<T> 的知识,以及 Rust 如何帮助我们正确地使用它。

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 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.

{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-13/src/main.rs}}

我们像示例 16-12 中所做的那样,创建了一个 counter 变量来在 Mutex<T> 中持有一个 i32 。接下来,我们通过遍历一系列数字来创建 10 个线程。我们使用 thread::spawn 并给所有线程相同的闭包:将计数器移动到线程中,通过调用 lock 方法获取 Mutex<T> 上的锁,然后在互斥锁中的值上加 1。当线程完成运行其闭包时, num 将超出作用域并释放锁,以便另一个线程可以获取它。

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 that another thread can acquire it.

在主线程中,我们收集所有的联接句柄 (join handles)。然后,就像我们在示例 16-2 中所做的那样,我们在每个句柄上调用 join 以确保所有线程都完成。在那一点上,主线程将获取锁并打印此程序的结果。

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.

我们暗示过这个例子无法编译。现在让我们找出原因!

We hinted that this example wouldn’t compile. Now let’s find out why!

{{#include ../listings/ch16-fearless-concurrency/listing-16-13/output.txt}}

错误消息指出 counter 值在循环的上一次迭代中已被移动。Rust 告诉我们,我们不能将 counter 锁的所有权移动到多个线程中。让我们使用我们在第 15 章讨论过的多重所有权方法来修复这个编译器错误。

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 lock counter into multiple threads. Let’s fix the compiler error with the multiple-ownership method we discussed in Chapter 15.

多线程的多重所有权 (Multiple Ownership with Multiple Threads)

Multiple Ownership with Multiple Threads

在第 15 章中,我们通过使用智能指针 Rc<T> 创建引用计数值,从而给一个值赋予了多个所有者。让我们在这里做同样的事情,看看会发生什么。我们将在示例 16-14 中将 Mutex<T> 包裹在 Rc<T> 中,并在将所有权移动到线程之前克隆 Rc<T>

In Chapter 15, we gave a value to 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.

{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-14/src/main.rs}}

再一次,我们编译并得到了……不同的错误!编译器教了我们很多:

Once again, we compile and get… different errors! The compiler is teaching us a lot:

{{#include ../listings/ch16-fearless-concurrency/listing-16-14/output.txt}}

哇,那条错误消息真冗长!这里是需要关注的重要部分: `Rc<Mutex<i32>>` cannot be sent between threads safely(无法在线程间安全地发送 Rc<Mutex<i32>>)。编译器还告诉了我们原因: the trait `Send` is not implemented for `Rc<Mutex<i32>>`Rc<Mutex<i32>> 未实现 Send 特征)。我们将在下一节讨论 Send :它是确保我们与线程一起使用的类型是用于并发场景的特征之一。

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 that the types we use with threads are meant for use in concurrent situations.

不幸的是, Rc<T> 在线程间共享是不安全的。当 Rc<T> 管理引用计数时,它会在每次调用 clone 时增加计数,并在每个克隆被丢弃时减少计数。但它没有使用任何并发原语来确保计数的更改不会被另一个线程打断。这可能导致错误的计数——细微的 bug 可能转而导致内存泄漏或是在我们用完之前值就被丢弃。我们需要的是一个完全像 Rc<T> ,但以线程安全的方式修改引用计数的类型。

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 that is exactly like Rc<T>, but that makes changes to the reference count in a thread-safe way.

使用 Arc<T> 进行原子引用计数 (Atomic Reference Counting with Arc<T>)

Atomic Reference Counting with Arc<T>

幸运的是, Arc<T> “是”一种像 Rc<T> 一样可以安全用于并发场景的类型。字母 a 代表“原子 (atomic)”,意思是它是一个“原子引用计数 (atomically reference-counted)”类型。“原子 (Atomics)”是另一种并发原语,我们在这里不做详细介绍:有关更多细节,请参阅 std::sync::atomic 的标准库文档。此时,你只需要知道原子类型的工作方式类似于原始类型,但在线程间共享是安全的。

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> 。原因是线程安全伴随着性能损失,你只在真正需要的时候才想支付这笔开销。如果你只是在单线程内对值执行操作,如果不必强制执行原子提供的保证,你的代码可以运行得更快。

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>Rc<T> 具有相同的 API,因此我们通过更改 use 行、 new 调用和 clone 调用来修复我们的程序。示例 16-15 中的代码终于可以编译并运行了。

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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-15/src/main.rs}}
}

这段代码将打印以下内容:

This code will print the following:

Result: 10

我们成功了!我们从 0 数到了 10,这看起来可能并不令人印象深刻,但它确实让我们学到了很多关于 Mutex<T> 和线程安全的知识。你也可以使用这个程序的结构来执行比仅仅递增计数器更复杂的操作。使用这种策略,你可以将计算拆分为独立的部分,将这些部分分散到多个线程中,然后使用 Mutex<T> 让每个线程使用其部分结果更新最终结果。

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.

注意,如果你正在进行简单的数值运算,标准库的 std::sync::atomic 模块提供了比 Mutex<T> 更简单的类型。这些类型提供了对原始类型的安全、并发、原子的访问。我们在这个例子中选择将 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 that we could concentrate on how Mutex<T> works.

RefCell<T>/Rc<T>Mutex<T>/Arc<T> 的比较 (Comparing RefCell<T>/Rc<T> and Mutex<T>/Arc<T>)

Comparing RefCell<T>/Rc<T> and Mutex<T>/Arc<T>

你可能已经注意到 counter 是不可变的,但我们可以获得它内部值的可变引用;这意味着 Mutex<T> 提供了内部可变性,就像 Cell 家族所做的那样。就像我们在第 15 章中使用 RefCell<T> 允许我们修改 Rc<T> 内部的内容一样,我们使用 Mutex<T> 来修改 Arc<T> 内部的内容。

You might have noticed that counter is immutable but that 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>.

另一个需要注意的细节是,当你使用 Mutex<T> 时,Rust 无法保护你免受所有种类的逻辑错误。回想第 15 章,使用 Rc<T> 伴随着创建引用循环的风险,即两个 Rc<T> 值相互引用,导致内存泄漏。类似地, Mutex<T> 伴随着创建“死锁 (deadlocks)”的风险。当一个操作需要锁定两个资源,而两个线程各获取了一个锁,导致它们永远互相等待时,就会发生这种情况。如果你对死锁感兴趣,请尝试创建一个具有死锁的 Rust 程序;然后,研究任何语言中互斥锁的死锁缓解策略,并尝试在 Rust 中实现它们。 Mutex<T>MutexGuard 的标准库 API 文档提供了有用的信息。

Another detail to note is that Rust can’t protect you from all kinds of logic errors when you use Mutex<T>. Recall from 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.

我们将通过讨论 SendSync 特征以及我们如何将它们与自定义类型结合使用,来圆满完成本章。

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 Send and Sync)


x-i18n: generated_at: “2026-03-01T14:41:41Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 0f8675202aba9f931af209bb9a4cce659af4686719ba54e9c9904ac6fd8264f4 source_path: ch16-04-extensible-concurrency-sync-and-send.md workflow: 16

使用 SendSync 的可扩展并发 (Extensible Concurrency with Send and Sync)

有趣的是,我们在本章中讨论的几乎每一个并发特性都是标准库的一部分,而不是语言本身。处理并发的选项并不局限于语言或标准库;你可以编写自己的并发特性,或者使用他人编写的特性。

Interestingly, 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.

然而,在嵌入语言本身而非标准库的关键并发概念中,包括 std::marker 特征 SendSync

However, among the key concurrency concepts that are embedded in the language rather than the standard library are the std::marker traits Send and Sync.

在线程间转移所有权 (Transferring Ownership Between Threads)

Transferring Ownership Between Threads

Send 标记特征指示实现 Send 的类型的所有权可以在线程间转移。几乎所有的 Rust 类型都实现了 Send ,但也有一些例外,包括 Rc<T> :它不能实现 Send ,因为如果你克隆了一个 Rc<T> 值并尝试将克隆的所有权转移到另一个线程,这两个线程可能会同时更新引用计数。出于这个原因, Rc<T> 被实现为用于你不希望支付线程安全性能损失的单线程场景。

The Send marker trait indicates that ownership of values of the type implementing Send can be transferred between threads. Almost every Rust type implements Send, but there are some exceptions, including Rc<T>: This cannot implement 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.

因此,Rust 的类型系统和特征约束确保了你永远不会意外地在线程间不安全地发送 Rc<T> 值。当我们在示例 16-14 中尝试这样做时,我们得到了错误 the trait `Send` is not implemented for `Rc<Mutex<i32>>`。当我们切换到确实实现了 SendArc<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 does implement Send, the code compiled.

任何完全由 Send 类型组成的类型也会自动被标记为 Send 。除了原始指针(我们将在第 20 章讨论)外,几乎所有的原始类型都是 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 20.

从多个线程进行访问 (Accessing from Multiple Threads)

Accessing from Multiple Threads

Sync 标记特征指示实现 Sync 的类型可以从多个线程中安全地引用。换句话说,对于任何类型 T ,如果 &T (对 T 的不可变引用)实现了 Send ,那么 T 就实现了 Sync ,这意味着该引用可以被安全地发送到另一个线程。类似于 Send ,原始类型都实现了 Sync ,完全由实现 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 implements Sync if &T (an immutable reference to T) implements Send, meaning the reference can be sent safely to another thread. Similar to Send, primitive types all implement Sync, and types composed entirely of types that implement Sync also implement Sync.

出于与不实现 Send 相同的原因,智能指针 Rc<T> 也不实现 Sync 。我们在第 15 章谈到的 RefCell<T> 类型和相关的 Cell<T> 家族类型不实现 SyncRefCell<T> 在运行时进行的借用检查实现不是线程安全的。智能指针 Mutex<T> 实现了 Sync ,可以用于在多个线程间共享访问,正如你在“多线程共享 Mutex<T>中看到的。

The smart pointer Rc<T> also doesn’t implement Sync for the same reasons that it doesn’t implement Send. The RefCell<T> type (which we talked about in Chapter 15) and the family of related Cell<T> types don’t implement Sync. The implementation of borrow checking that RefCell<T> does at runtime is not thread-safe. The smart pointer Mutex<T> implements Sync and can be used to share access with multiple threads, as you saw in “Shared Access to Mutex<T>.

手动实现 SendSync 是不安全的 (Implementing Send and Sync Manually Is Unsafe)

Implementing Send and Sync Manually Is Unsafe

因为完全由实现了 SendSync 特征的其他类型组成的类型会自动实现 SendSync ,所以我们不需要手动实现这些特征。作为标记特征,它们甚至没有任何方法需要实现。它们只是对于强制执行与并发相关的各种不变量很有用。

Because types composed entirely of other types that implement the Send and Sync traits also automatically implement 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.

手动实现这些特征涉及实现不安全的 Rust 代码。我们将在第 20 章谈论使用不安全的 Rust 代码;目前,重要的信息是构建不完全由 SendSync 部分组成的新并发类型需要仔细考虑以维护安全保证。“The Rustonomicon” 中有更多关于这些保证以及如何维护它们的信息。

Manually implementing these traits involves implementing unsafe Rust code. We’ll talk about using unsafe Rust code in Chapter 20; 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.

总结 (Summary)

这不是你在本书中最后一次看到并发:下一章将重点讨论异步编程,第 21 章中的项目将会在比这里讨论的小例子更实际的场景中使用本章的概念。

This isn’t the last you’ll see of concurrency in this book: The next chapter focuses on async programming, and the project in Chapter 21 will use the concepts in this chapter in a more realistic situation than the smaller examples discussed here.

如前所述,由于 Rust 处理并发的方式只有极少部分是语言的一部分,许多并发解决方案都是作为 crate 实现的。这些演进速度比标准库快,因此在多线程场景下,务必在网上搜索当前最先进的 crate。

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 标准库为消息传递提供了通道,并提供了智能指针类型,如 Mutex<T>Arc<T> ,它们在并发上下文中是安全的。类型系统和借用检查器确保使用这些解决方案的代码不会以竞态条件或无效引用告终。一旦你的代码通过编译,你就可以放心,它将在多线程上愉快地运行,而不会出现其他语言中常见的那些难以追踪的 bug。并发编程不再是一个令人恐惧的概念:去吧,让你的程序无畏地并发运行!

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!

异步编程基础:Async、Await、Futures 和 Streams (Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams)


x-i18n: generated_at: “2026-03-01T14:42:50Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f9cd7f4b2e03b4be88231c9dd2d6d0e10a4b770dc4f3033cf3e33a6e6a69550e source_path: ch17-00-async-await.md workflow: 16

异步编程基础:Async、Await、Future 和 Stream (Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams)

Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams

我们要求计算机执行的许多操作都需要一段时间才能完成。如果我们能在等待这些长时间运行的进程完成的同时做点别的事情,那就太好了。现代计算机提供了两种同时处理多个操作的技术:并行和并发。然而,我们的程序逻辑主要是以线性方式编写的。我们希望能够指定程序应执行的操作,以及函数可以暂停而让程序的其他部分代为运行的点,而不需要预先精确指定每段代码运行的顺序和方式。“异步编程 (Asynchronous programming)”是一种抽象,它让我们根据潜在的暂停点和最终结果来表达我们的代码,并为我们处理协调的细节。

Many operations we ask the computer to do can take a while to finish. It would be nice if we could do something else while we’re waiting for those long-running processes to complete. Modern computers offer two techniques for working on more than one operation at a time: parallelism and concurrency. Our programs’ logic, however, is written in a mostly linear fashion. We’d like to be able to specify the operations a program should perform and points at which a function could pause and some other part of the program could run instead, without needing to specify up front exactly the order and manner in which each bit of code should run. Asynchronous programming is an abstraction that lets us express our code in terms of potential pausing points and eventual results that takes care of the details of coordination for us.

本章在第 16 章使用线程实现并行和并发的基础上,引入了另一种编写代码的方法:Rust 的 future、stream 以及 asyncawait 语法,它们让我们能够表达操作如何可以是异步的,以及实现异步运行时的第三方 crate:管理和协调异步操作执行的代码。

This chapter builds on Chapter 16’s use of threads for parallelism and concurrency by introducing an alternative approach to writing code: Rust’s futures, streams, and the async and await syntax that let us express how operations could be asynchronous, and the third-party crates that implement asynchronous runtimes: code that manages and coordinates the execution of asynchronous operations.

让我们考虑一个例子。假设你正在导出一段你为家庭庆祝活动创建的视频,这个操作可能需要几分钟到几小时不等。视频导出将尽可能多地使用 CPU 和 GPU 功率。如果你只有一个 CPU 核心,并且你的操作系统在导出完成之前没有暂停该操作——也就是说,如果它“同步 (synchronously)”地执行导出——那么在该任务运行时,你无法在计算机上做任何其他事情。那将是一个相当令人沮丧的体验。幸运的是,你计算机的操作系统可以而且确实经常无形地中断导出,以便让你能够同时完成其他工作。

Let’s consider an example. Say you’re exporting a video you’ve created of a family celebration, an operation that could take anywhere from minutes to hours. The video export will use as much CPU and GPU power as it can. If you had only one CPU core and your operating system didn’t pause that export until it completed—that is, if it executed the export synchronously—you couldn’t do anything else on your computer while that task was running. That would be a pretty frustrating experience. Fortunately, your computer’s operating system can, and does, invisibly interrupt the export often enough to let you get other work done simultaneously.

现在假设你正在下载别人分享的视频,这可能也需要一段时间,但不会占用那么多的 CPU 时间。在这种情况下,CPU 必须等待数据从网络到达。虽然你可以在数据开始到达时就开始读取数据,但可能需要一些时间才能让所有数据都出现。即使数据全部到齐了,如果视频很大,加载完它也可能至少需要一两秒钟。这听起来可能不算多,但对于现代处理器来说,这是一段非常长的时间,因为它每秒可以执行数十亿次操作。同样,你的操作系统会无形地中断你的程序,以便允许 CPU 在等待网络调用完成时执行其他工作。

Now say you’re downloading a video shared by someone else, which can also take a while but does not take up as much CPU time. In this case, the CPU has to wait for data to arrive from the network. While you can start reading the data once it starts to arrive, it might take some time for all of it to show up. Even once the data is all present, if the video is quite large, it could take at least a second or two to load it all. That might not sound like much, but it’s a very long time for a modern processor, which can perform billions of operations every second. Again, your operating system will invisibly interrupt your program to allow the CPU to perform other work while waiting for the network call to finish.

视频导出是“CPU 密集型 (CPU-bound)”或“计算密集型 (compute-bound)”操作的一个例子。它受限于计算机在 CPU 或 GPU 内的潜在数据处理速度,以及它可以为该操作投入多少速度。视频下载是“I/O 密集型 (I/O-bound)”操作的一个例子,因为它受限于计算机“输入和输出”的速度;它只能和数据通过网络发送的速度一样快。

The video export is an example of a CPU-bound or compute-bound operation. It’s limited by the computer’s potential data processing speed within the CPU or GPU, and how much of that speed it can dedicate to the operation. The video download is an example of an I/O-bound operation, because it’s limited by the speed of the computer’s input and output; it can only go as fast as the data can be sent across the network.

在这两个例子中,操作系统的无形中断提供了一种并发形式。不过,这种并发仅发生在整个程序的层面上:操作系统中断一个程序以让其他程序完成工作。在许多情况下,因为我们对程序的理解比操作系统要细致得多,所以我们可以发现操作系统看不见的并发机会。

In both of these examples, the operating system’s invisible interrupts provide a form of concurrency. That concurrency happens only at the level of the entire program, though: the operating system interrupts one program to let other programs get work done. In many cases, because we understand our programs at a much more granular level than the operating system does, we can spot opportunities for concurrency that the operating system can’t see.

例如,如果我们正在构建一个管理文件下载的工具,我们应该能够编写我们的程序,使得启动一个下载不会锁定 UI,并且用户应该能够同时开始多个下载。不过,许多用于与网络交互的操作系统 API 是“阻塞 (blocking)”的;也就是说,它们会阻塞程序的进度,直到它们正在处理的数据完全就绪。

For example, if we’re building a tool to manage file downloads, we should be able to write our program so that starting one download won’t lock up the UI, and users should be able to start multiple downloads at the same time. Many operating system APIs for interacting with the network are blocking, though; that is, they block the program’s progress until the data they’re processing is completely ready.

注意:如果你仔细想想,这就是“大多数”函数调用的工作方式。然而,“阻塞”一词通常保留给与文件、网络或计算机上的其他资源交互的函数调用,因为在这些情况下,单个程序会受益于操作是“非”阻塞的。

Note: This is how most function calls work, if you think about it. However, the term blocking is usually reserved for function calls that interact with files, the network, or other resources on the computer, because those are the cases where an individual program would benefit from the operation being non-blocking.

我们可以通过为下载每个文件启动一个专用线程来避免阻塞我们的主线程。然而,这些线程所使用的系统资源的开销最终会成为一个问题。最好是调用最初就不阻塞,相反我们可以定义一些我们希望程序完成的任务,并允许运行时选择运行它们的最佳顺序和方式。

We could avoid blocking our main thread by spawning a dedicated thread to download each file. However, the overhead of the system resources used by those threads would eventually become a problem. It would be preferable if the call didn’t block in the first place, and instead we could define a number of tasks that we’d like our program to complete and allow the runtime to choose the best order and manner in which to run them.

这正是 Rust 的 “async” (asynchronous 的缩写) 抽象带给我们的。在本章中,你将通过以下主题全面了解 async:

  • 如何使用 Rust 的 asyncawait 语法并通过运行时执行异步函数
  • 如何使用异步模型解决我们在第 16 章中看到的一些相同挑战
  • 多线程和异步如何提供互补的解决方案,在许多情况下你可以将它们结合起来

That is exactly what Rust’s async (short for asynchronous) abstraction gives us. In this chapter, you’ll learn all about async as we cover the following topics:

  • How to use Rust’s async and await syntax and execute asynchronous functions with a runtime
  • How to use the async model to solve some of the same challenges we looked at in Chapter 16
  • How multithreading and async provide complementary solutions that you can combine in many cases

不过,在看异步在实践中如何工作之前,我们需要稍作绕道,讨论一下并行和并发之间的区别。

Before we see how async works in practice, though, we need to take a short detour to discuss the differences between parallelism and concurrency.

并行与并发 (Parallelism and Concurrency)

Parallelism and Concurrency

到目前为止,我们大多将并行和并发视为可以互换的。现在我们需要更精确地对它们进行区分,因为随着我们开始工作,差异就会显现出来。

We’ve treated parallelism and concurrency as mostly interchangeable so far. Now we need to distinguish between them more precisely, because the differences will show up as we start working.

考虑一个团队拆分软件项目工作的不同方式。你可以给单个人员分配多个任务,给每个成员分配一个任务,或者混合使用这两种方法。

Consider the different ways a team could split up work on a software project. You could assign a single member multiple tasks, assign each member one task, or use a mix of the two approaches.

当一个人在完成任何任务之前处理几个不同的任务时,这就是“并发 (concurrency)”。实现并发的一种方法类似于在你的电脑上签出了两个不同的项目,当你对一个项目感到无聊或卡住时,你就切换到另一个项目。你只有一个人,所以你无法在完全相同的时间在两个任务上取得进展,但你可以多任务处理,通过在它们之间切换一次在一个任务上取得进展(见图 17-1)。

When an individual works on several different tasks before any of them is complete, this is concurrency. One way to implement concurrency is similar to having two different projects checked out on your computer, and when you get bored or stuck on one project, you switch to the other. You’re just one person, so you can’t make progress on both tasks at the exact same time, but you can multitask, making progress on one at a time by switching between them (see Figure 17-1).

显示了标记为任务 A 和任务 B 的叠加方框,方框中有代表子任务的菱形。箭头从 A1 指向 B1,从 B1 指向 A2,从 A2 指向 B2,从 B2 指向 A3,从 A3 指向 A4,从 A4 指向 B3。子任务之间的箭头穿过了任务 A 和任务 B 之间的方框。
图 17-1:一个并发工作流,在任务 A 和任务 B 之间切换

当团队通过让每个成员承担一项任务并独立完成来拆分一组任务时,这就是“并行 (parallelism)”。团队中的每个人都可以在完全相同的时间取得进展(见图 17-2)。

When the team splits up a group of tasks by having each member take one task and work on it alone, this is parallelism. Each person on the team can make progress at the exact same time (see Figure 17-2).

显示了标记为任务 A 和任务 B 的叠加方框,方框中有代表子任务的菱形。箭头从 A1 指向 A2,从 A2 指向 A3,从 A3 指向 A4,从 B1 指向 B2,从 B2 指向 B3。任务 A 和任务 B 的方框之间没有穿过的箭头。
图 17-2:一个并行工作流,工作在任务 A 和任务 B 上独立进行

在这两种工作流中,你可能都需要在不同任务之间进行协调。也许你认为分配给一个人的任务完全独立于其他人的工作,但它实际上需要团队中的另一个人先完成他们的任务。部分工作可以并行完成,但其中一部分实际上是“串行 (serial)”的:它只能以序列的方式发生,一个任务接一个任务,如图 17-3 所示。

In both of these workflows, you might have to coordinate between different tasks. Maybe you thought the task assigned to one person was totally independent from everyone else’s work, but it actually requires another person on the team to finish their task first. Some of the work could be done in parallel, but some of it was actually serial: it could only happen in a series, one task after the other, as in Figure 17-3.

显示了标记为任务 A 和任务 B 的叠加方框,方框中有代表子任务的菱形。在任务 A 中,箭头从 A1 指向 A2,从 A2 指向一对像“暂停”符号的粗垂直线,再从该符号指向 A3。在任务 B 中,箭头从 B1 指向 B2,从 B2 指向 B3,从 B3 指向 A3,以及从 B3 指向 B4。
图 17-3:一个部分并行的工作流,其中任务 A 和任务 B 独立进行,直到任务 A3 被阻塞在任务 B3 的结果上。

同样,你可能会意识到你自己的一个任务依赖于你的另一个任务。现在你的并发工作也变成了串行的。

Likewise, you might realize that one of your own tasks depends on another of your tasks. Now your concurrent work has also become serial.

并行和并发也可以相互交织。如果你得知一个同事在等你完成你的一个任务之前一直被卡住,你可能会把所有精力都集中在那个任务上以“解除”你同事的阻塞。你和你的同事不再能够并行工作,你也无法再在自己的任务上并发工作。

Parallelism and concurrency can intersect with each other, too. If you learn that a colleague is stuck until you finish one of your tasks, you’ll probably focus all your efforts on that task to “unblock” your colleague. You and your coworker are no longer able to work in parallel, and you’re also no longer able to work concurrently on your own tasks.

同样的动态也发生在软件和硬件上。在只有单个 CPU 核心的机器上,CPU 一次只能执行一个操作,但它仍然可以并发工作。利用线程、进程和异步等工具,计算机可以暂停一项活动并在最终循环回到第一项活动之前切换到其他活动。在具有多个 CPU 核心的机器上,它还可以并行工作。一个核心可以执行一个任务,而另一个核心执行一个完全不相关的任务,这些操作实际上是同时发生的。

The same basic dynamics come into play with software and hardware. On a machine with a single CPU core, the CPU can perform only one operation at a time, but it can still work concurrently. Using tools such as threads, processes, and async, the computer can pause one activity and switch to others before eventually cycling back to that first activity again. On a machine with multiple CPU cores, it can also do work in parallel. One core can be performing one task while another core performs a completely unrelated one, and those operations actually happen at the same time.

在 Rust 中运行异步代码通常是并发发生的。取决于硬件、操作系统以及我们使用的异步运行时(稍后会有更多关于异步运行时的介绍),这种并发在底层也可能使用并行。

Running async code in Rust usually happens concurrently. Depending on the hardware, the operating system, and the async runtime we are using (more on async runtimes shortly), that concurrency may also use parallelism under the hood.

现在,让我们深入了解 Rust 中的异步编程究竟是如何工作的。

Now, let’s dive into how async programming in Rust actually works.

Futures 与 Async 语法 (Futures and the Async Syntax)


x-i18n: generated_at: “2026-03-01T14:44:26Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: dff0af8b0374b505748ded80c3f7656742a8d3a219a6e276ce69478e82f06633 source_path: ch17-01-futures-and-syntax.md workflow: 16

Future 和异步语法 (Futures and the Async Syntax)

Rust 异步编程的关键元素是“future”以及 Rust 的 asyncawait 关键字。

The key elements of asynchronous programming in Rust are futures and Rust’s async and await keywords.

一个 “future” 是一个现在可能尚未就绪,但在未来某个时刻会变得就绪的值。(这个概念在许多语言中都有出现,有时以其他名称出现,如 taskpromise。)Rust 提供了一个 Future 特征作为构建块,以便不同的异步操作可以用不同的数据结构实现,但具有共同的接口。在 Rust 中,future 是实现了 Future 特征的类型。每个 future 都持有其自身关于已取得的进度以及“就绪”意味着什么的信息。

A future is a value that may not be ready now but will become ready at some point in the future. (This same concept shows up in many languages, sometimes under other names such as task or promise.) Rust provides a Future trait as a building block so that different async operations can be implemented with different data structures but with a common interface. In Rust, futures are types that implement the Future trait. Each future holds its own information about the progress that has been made and what “ready” means.

你可以将 async 关键字应用于代码块和函数,以指定它们可以被中断和恢复。在异步代码块或异步函数中,你可以使用 await 关键字来“等待一个 future (await a future)”(即,等待它变得就绪)。在异步代码块或函数中等待一个 future 的任何点,都是该代码块或函数暂停和恢复的潜在位置。向 future 检查其值是否可用的过程称为“轮询 (polling)”。

You can apply the async keyword to blocks and functions to specify that they can be interrupted and resumed. Within an async block or async function, you can use the await keyword to await a future (that is, wait for it to become ready). Any point where you await a future within an async block or function is a potential spot for that block or function to pause and resume. The process of checking with a future to see if its value is available yet is called polling.

其他一些语言(如 C# 和 JavaScript)也使用 asyncawait 关键字进行异步编程。如果你熟悉这些语言,你可能会注意到 Rust 处理该语法的方式存在一些显著差异。这正如我们将看到的,是有充分理由的!

Some other languages, such as C# and JavaScript, also use async and await keywords for async programming. If you’re familiar with those languages, you may notice some significant differences in how Rust handles the syntax. That’s for good reason, as we’ll see!

在编写异步 Rust 代码时,我们大多数时候使用 asyncawait 关键字。Rust 将它们编译成使用 Future 特征的等效代码,就像它将 for 循环编译成使用 Iterator 特征的等效代码一样。不过,由于 Rust 提供了 Future 特征,你也可以在需要时为自己的数据类型实现它。我们在本章中看到的许多函数都会返回具有其自身 Future 实现的类型。我们将在本章末尾回到该特征的定义并深入研究它的工作原理,但这些细节已足以让我们继续前进。

When writing async Rust, we use the async and await keywords most of the time. Rust compiles them into equivalent code using the Future trait, much as it compiles for loops into equivalent code using the Iterator trait. Because Rust provides the Future trait, though, you can also implement it for your own data types when you need to. Many of the functions we’ll see throughout this chapter return types with their own implementations of Future. We’ll return to the definition of the trait at the end of the chapter and dig into more of how it works, but this is enough detail to keep us moving forward.

这一切可能感觉有点抽象,所以让我们编写我们的第一个异步程序:一个小型的 Web 爬虫。我们将从命令行传入两个 URL,并发获取它们,并返回其中第一个完成的那个的结果。这个例子会有相当一部分新语法,但不用担心——我们将边做边解释你需要知道的一切。

This may all feel a bit abstract, so let’s write our first async program: a little web scraper. We’ll pass in two URLs from the command line, fetch both of them concurrently, and return the result of whichever one finishes first. This example will have a fair bit of new syntax, but don’t worry—we’ll explain everything you need to know as we go.

我们的第一个异步程序 (Our First Async Program)

Our First Async Program

为了让本章的重点放在学习异步编程上,而不是应付生态系统的各个部分,我们创建了 trpl crate (trpl 是 “The Rust Programming Language” 的缩写)。它重新导出了你所需的所有类型、特征和函数,主要来自 futurestokio crate。 futures crate 是 Rust 进行异步代码实验的官方场所,它实际上是 Future 特征最初被设计出来的地方。Tokio 是当今 Rust 中使用最广泛的异步运行时,特别是在 Web 应用程序中。还有其他优秀的运行时,它们可能更适合你的用途。我们在 trpl 的底层使用 tokio crate,因为它经过了良好的测试且被广泛使用。

To keep the focus of this chapter on learning async rather than juggling parts of the ecosystem, we’ve created the trpl crate (trpl is short for “The Rust Programming Language”). It re-exports all the types, traits, and functions you’ll need, primarily from the futures and tokio crates. The futures crate is an official home for Rust experimentation for async code, and it’s actually where the Future trait was originally designed. Tokio is the most widely used async runtime in Rust today, especially for web applications. There are other great runtimes out there, and they may be more suitable for your purposes. We use the tokio crate under the hood for trpl because it’s well tested and widely used.

在某些情况下, trpl 还对原始 API 进行了重命名或包装,以便让你专注于本章相关的细节。如果你想了解这个 crate 的作用,我们鼓励你查看它的源代码。你将能够看到每个重新导出源自哪个 crate,并且我们留下了大量的注释来解释这个 crate 的作用。

In some cases, trpl also renames or wraps the original APIs to keep you focused on the details relevant to this chapter. If you want to understand what the crate does, we encourage you to check out its source code. You’ll be able to see what crate each re-export comes from, and we’ve left extensive comments explaining what the crate does.

创建一个名为 hello-async 的新二进制项目,并将 trpl crate 添加为依赖项:

Create a new binary project named hello-async and add the trpl crate as a dependency:

$ cargo new hello-async
$ cd hello-async
$ cargo add trpl

现在我们可以使用 trpl 提供的各个部分来编写我们的第一个异步程序。我们将构建一个小型的命令行工具,用于获取两个网页,从每个网页中提取 <title> 元素,并打印出在那整个过程中第一个完成的页面的标题。

Now we can use the various pieces provided by trpl to write our first async program. We’ll build a little command line tool that fetches two web pages, pulls the <title> element from each, and prints out the title of whichever page finishes that whole process first.

定义 page_title 函数 (Defining the page_title Function)

让我们从编写一个函数开始,它接收一个页面 URL 作为参数,向其发起请求,并返回 <title> 元素的文本(见示例 17-1)。

Let’s start by writing a function that takes one page URL as a parameter, makes a request to it, and returns the text of the <title> element (see Listing 17-1).

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-01/src/main.rs:all}}
}

首先,我们定义一个名为 page_title 的函数,并用 async 关键字标记它。然后我们使用 trpl::get 函数获取传入的任何 URL,并添加 await 关键字来等待响应。为了获取 response 的文本,我们调用它的 text 方法,并再次使用 await 关键字等待它。这两个步骤都是异步的。对于 get 函数,我们必须等待服务器发回其响应的第一部分,其中将包括 HTTP 标头、Cookie 等,并且可以与响应体分开交付。特别是如果正文非常大,那么全部送达可能需要一些时间。因为我们必须等待响应的“全部”送达,所以 text 方法也是异步的。

First, we define a function named page_title and mark it with the async keyword. Then we use the trpl::get function to fetch whatever URL is passed in and add the await keyword to await the response. To get the text of the response, we call its text method and once again await it with the await keyword. Both of these steps are asynchronous. For the get function, we have to wait for the server to send back the first part of its response, which will include HTTP headers, cookies, and so on and can be delivered separately from the response body. Especially if the body is very large, it can take some time for it all to arrive. Because we have to wait for the entirety of the response to arrive, the text method is also async.

我们必须显式地等待这两个 future,因为 Rust 中的 future 是“惰性的 (lazy)”:除非你使用 await 关键字要求它们这样做,否则它们什么都不做。(事实上,如果你不使用 future,Rust 会显示编译器警告。)这可能会让你想起第 13 章“使用迭代器处理一系列项”部分中关于迭代器的讨论。除非你调用它们的 next 方法——无论是直接调用,还是通过使用 for 循环或底层使用 next 的方法(如 map),否则迭代器什么都不做。同样,除非你显式要求,否则 future 什么都不做。这种惰性允许 Rust 避免运行异步代码,直到真正需要它为止。

We have to explicitly await both of these futures, because futures in Rust are lazy: they don’t do anything until you ask them to with the await keyword. (In fact, Rust will show a compiler warning if you don’t use a future.) This might remind you of the discussion of iterators in the “Processing a Series of Items with Iterators” section in Chapter 13. Iterators do nothing unless you call their next method—whether directly or by using for loops or methods such as map that use next under the hood. Likewise, futures do nothing unless you explicitly ask them to. This laziness allows Rust to avoid running async code until it’s actually needed.

注意:这与我们在第 16 章“使用 spawn 创建新线程”部分中看到的行为不同,在那里我们传递给另一个线程的闭包立即开始运行。这也与许多其他语言处理异步的方式不同。但正如迭代器一样,这对 Rust 能够提供其性能保证至关重要。

Note: This is different from the behavior we saw when using thread::spawn in the “Creating a New Thread with spawn” section in Chapter 16, where the closure we passed to another thread started running immediately. It’s also different from how many other languages approach async. But it’s important for Rust to be able to provide its performance guarantees, just as it is with iterators.

一旦我们有了 response_text ,我们就可以使用 Html::parse 将其解析为 Html 类型的实例。现在我们有了一个可以用来将 HTML 处理为更丰富数据结构的数据类型,而不是原始字符串。特别地,我们可以使用 select_first 方法来查找给定 CSS 选择器的第一个实例。通过传入字符串 "title" ,我们将获得文档中的第一个 <title> 元素(如果存在的话)。因为可能没有任何匹配的元素, select_first 返回一个 Option<ElementRef> 。最后,我们使用 Option::map 方法,它让我们能在元素存在时处理它,在不存在时什么都不做。(我们也可以在这里使用 match 表达式,但 map 更加惯用。)在我们提供给 map 的函数体中,我们对 title 调用 inner_html 以获取其内容,内容是一个 String 。到最后,我们就得到了一个 Option<String>

Once we have response_text, we can parse it into an instance of the Html type using Html::parse. Instead of a raw string, we now have a data type we can use to work with the HTML as a richer data structure. In particular, we can use the select_first method to find the first instance of a given CSS selector. By passing the string "title", we’ll get the first <title> element in the document, if there is one. Because there may not be any matching element, select_first returns an Option<ElementRef>. Finally, we use the Option::map method, which lets us work with the item in the Option if it’s present, and do nothing if it isn’t. (We could also use a match expression here, but map is more idiomatic.) In the body of the function we supply to map, we call inner_html on the title to get its content, which is a String. When all is said and done, we have an Option<String>.

请注意,Rust 的 await 关键字位于你正在等待的表达式“之后”,而不是之前。也就是说,它是一个“后缀 (postfix)”关键字。如果你在其他语言中使用过 async ,这可能与你的习惯不同,但在 Rust 中,这使得链式调用方法处理起来更加美观。因此,我们可以更改 page_title 的主体,将 trpl::gettext 函数调用链接在一起,中间用 await 分隔,如示例 17-2 所示。

Notice that Rust’s await keyword goes after the expression you’re awaiting, not before it. That is, it’s a postfix keyword. This may differ from what you’re used to if you’ve used async in other languages, but in Rust it makes chains of methods much nicer to work with. As a result, we could change the body of page_title to chain the trpl::get and text function calls together with await between them, as shown in Listing 17-2.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-02/src/main.rs:chaining}}
}

至此,我们成功编写了我们的第一个异步函数!在我们在 main 中添加一些代码来调用它之前,让我们先多谈谈我们所写的内容以及它的含义。

With that, we have successfully written our first async function! Before we add some code in main to call it, let’s talk a little more about what we’ve written and what it means.

当 Rust 看到一个被标记为 async 关键字的“代码块 (block)”时,它会将其编译成一个实现 Future 特征的独特的、匿名的数据类型。当 Rust 看到一个被标记为 async 的“函数 (function)”时,它会将其编译成一个非异步函数,其主体是一个异步代码块。异步函数的返回类型是编译器为该异步代码块创建的匿名数据类型的类型。

When Rust sees a block marked with the async keyword, it compiles it into a unique, anonymous data type that implements the Future trait. When Rust sees a function marked with async, it compiles it into a non-async function whose body is an async block. An async function’s return type is the type of the anonymous data type the compiler creates for that async block.

因此,编写 async fn 相当于编写一个返回返回类型之 “future” 的函数。对于编译器来说,示例 17-1 中的 async fn page_title 函数定义大致相当于如下定义的非异步函数:

Thus, writing async fn is equivalent to writing a function that returns a future of the return type. To the compiler, a function definition such as the async fn page_title in Listing 17-1 is roughly equivalent to a non-async function defined like this:

#![allow(unused)]
fn main() {
extern crate trpl; // required for mdbook test
use std::future::Future;
use trpl::Html;

fn page_title(url: &str) -> impl Future<Output = Option<String>> {
    async move {
        let text = trpl::get(url).await.text().await;
        Html::parse(&text)
            .select_first("title")
            .map(|title| title.inner_html())
    }
}
}

让我们逐步了解转换后版本的每个部分:

  • 它使用了我们在第 10 章“特征作为参数”部分讨论过的 impl Trait 语法。

  • 返回值实现了 Future 特征,带有一个关联类型 Output 。请注意, Output 类型是 Option<String> ,这与 async fn 版本的 page_title 的原始返回类型相同。

  • 原始函数体中调用的所有代码都被包装在一个 async move 块中。请记住,代码块是表达式。这整个块就是从函数返回的表达式。

  • 如前所述,这个异步块产生一个类型为 Option<String> 的值。该值与返回类型中的 Output 类型相匹配。这就像你见过的其他代码块一样。

  • 由于新函数体使用 url 参数的方式,它是一个 async move 块。(我们将在本章稍后更深入地讨论 asyncasync move 。)

  • It uses the impl Trait syntax we discussed back in Chapter 10 in the “Traits as Parameters” section.

  • The returned value implements the Future trait with an associated type of Output. Notice that the Output type is Option<String>, which is the same as the original return type from the async fn version of page_title.

  • All of the code called in the body of the original function is wrapped in an async move block. Remember that blocks are expressions. This whole block is the expression returned from the function.

  • This async block produces a value with the type Option<String>, as just described. That value matches the Output type in the return type. This is just like other blocks you have seen.

  • The new function body is an async move block because of how it uses the url parameter. (We’ll talk much more about async versus async move later in the chapter.)

现在我们可以在 main 中调用 page_title 了。

Now we can call page_title in main.

通过运行时执行异步函数 (Executing an Async Function with a Runtime)

Executing an Async Function with a Runtime

首先,我们将获取单个页面的标题,如示例 17-3 所示。不幸的是,这段代码目前还无法通过编译。

To start, we’ll get the title for a single page, shown in Listing 17-3. Unfortunately, this code doesn’t compile yet.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-03/src/main.rs:main}}

我们遵循了我们在第 12 章“接收命令行参数”部分中用于获取命令行参数的相同模式。然后我们将 URL 参数传递给 page_title 并等待结果。因为 future 产生的值是一个 Option<String> ,所以我们使用 match 表达式来打印不同的消息,以考虑到页面是否具有 <title>

We follow the same pattern we used to get command line arguments in the “Accepting Command Line Arguments” section in Chapter 12. Then we pass the URL argument to page_title and await the result. Because the value produced by the future is an Option<String>, we use a match expression to print different messages to account for whether the page had a <title>.

我们唯一可以使用 await 关键字的地方是在异步函数或块中,而 Rust 不允许我们将特殊的 main 函数标记为 async

The only place we can use the await keyword is in async functions or blocks, and Rust won’t let us mark the special main function as async.

error[E0752]: `main` function is not allowed to be `async`
 --> src/main.rs:6:1
  |
6 | async fn main() {
  | ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`

(错误[E0752]:不允许 main 函数为 async

main 不能被标记为 async 的原因是异步代码需要一个“运行时 (runtime)”:一个管理执行异步代码细节的 Rust crate。程序的 main 函数可以“初始化”一个运行时,但它“本身”不是一个运行时。(我们稍后会看到为什么是这种情况。)每个执行异步代码的 Rust 程序都至少有一个设置运行未来代码的地方。

The reason main can’t be marked async is that async code needs a runtime: a Rust crate that manages the details of executing asynchronous code. A program’s main function can initialize a runtime, but it’s not a runtime itself. (We’ll see more about why this is the case in a bit.) Every Rust program that executes async code has at least one place where it sets up a runtime that executes the futures.

大多数支持异步的语言都会绑定一个运行时,但 Rust 没有。相反,有许多不同的异步运行时可供选择,每个运行时都做出了适合其目标用例的不同权衡。例如,具有多个 CPU 核心和大量 RAM 的高吞吐量 Web 服务器,与具有单个核心、少量 RAM 且没有堆分配能力的微控制器有着非常不同的需求。提供这些运行时的 crate 通常也会提供常用功能的异步版本,如文件或网络 I/O。

Most languages that support async bundle a runtime, but Rust does not. Instead, there are many different async runtimes available, each of which makes different tradeoffs suitable to the use case it targets. For example, a high-throughput web server with many CPU cores and a large amount of RAM has very different needs than a microcontroller with a single core, a small amount of RAM, and no heap allocation ability. The crates that provide those runtimes also often supply async versions of common functionality such as file or network I/O.

在这里,以及本章的其余部分,我们将使用 trpl crate 中的 block_on 函数,它接收一个 future 作为参数,并阻塞当前线程直到该 future 运行完成。在幕后,调用 block_on 会使用 tokio crate 设置一个运行时,该运行时用于运行传入的 future( trpl crate 的 block_on 行为与其他运行时 crate 的 block_on 函数类似)。一旦 future 完成, block_on 就会返回该 future 产生的任何值。

Here, and throughout the rest of this chapter, we’ll use the block_on function from the trpl crate, which takes a future as an argument and blocks the current thread until this future runs to completion. Behind the scenes, calling block_on sets up a runtime using the tokio crate that’s used to run the future passed in (the trpl crate’s block_on behavior is similar to other runtime crates’ block_on functions). Once the future completes, block_on returns whatever value the future produced.

我们可以将 page_title 返回的 future 直接传递给 block_on ,并在它完成后,像我们在示例 17-3 中尝试做的那样对生成的 Option<String> 进行匹配。然而,对于本章中的大多数示例(以及现实世界中的大多数异步代码),我们将执行不止一个异步函数调用,因此我们将传递一个 async 块并显式等待 page_title 调用的结果,如示例 17-4 所示。

We could pass the future returned by page_title directly to block_on and, once it completed, we could match on the resulting Option<String> as we tried to do in Listing 17-3. However, for most of the examples in the chapter (and most async code in the real world), we’ll be doing more than just one async function call, so instead we’ll pass an async block and explicitly await the result of the page_title call, as in Listing 17-4.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-04/src/main.rs:run}}

当我们运行这段代码时,我们得到了最初预期的行为:

When we run this code, we get the behavior we expected initially:

$ cargo run -- "https://www.rust-lang.org"
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.05s
     Running `target/debug/async_await 'https://www.rust-lang.org'`
The title for https://www.rust-lang.org was
            Rust Programming Language

呼——我们终于有了一些可以工作的异步代码!但在我们添加让两个网站相互竞争的代码之前,让我们简要地将注意力转回到 future 的工作原理上。

Phew—we finally have some working async code! But before we add the code to race two sites against each other, let’s briefly turn our attention back to how futures work.

每一个“等待点 (await point)”——也就是说,代码中每个使用 await 关键字的地方——都代表一个将控制权交还给运行时的位置。为了做到这一点,Rust 需要跟踪异步块中涉及的状态,以便运行时可以启动一些其他工作,然后在准备好再次尝试推进第一个工作时回来。这是一个无形的状态机,就像你编写了一个如下所示的枚举来保存每个等待点的当前状态一样:

Each await point—that is, every place where the code uses the await keyword—represents a place where control is handed back to the runtime. To make that work, Rust needs to keep track of the state involved in the async block so that the runtime could kick off some other work and then come back when it’s ready to try advancing the first one again. This is an invisible state machine, as if you’d written an enum like this to save the current state at each await point:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/no-listing-state-machine/src/lib.rs:enum}}
}

然而,手动编写在每个状态之间转换的代码将是乏味且容易出错的,特别是当你以后需要向代码添加更多功能和更多状态时。幸运的是,Rust 编译器会自动为异步代码创建和管理状态机数据结构。通常围绕数据结构的所有权和借用规则仍然适用,令人高兴的是,编译器还为我们处理了这些检查并提供了有用的错误消息。我们将在本章稍后研究其中的一些例子。

Writing the code to transition between each state by hand would be tedious and error-prone, however, especially when you need to add more functionality and more states to the code later. Fortunately, the Rust compiler creates and manages the state machine data structures for async code automatically. The normal borrowing and ownership rules around data structures all still apply, and happily, the compiler also handles checking those for us and provides useful error messages. We’ll work through a few of those later in the chapter.

最终,必须有东西来执行这个状态机,而那个东西就是运行时。(这就是为什么你在研究运行时的时候可能会遇到关于“执行器 (executors)”的提及:执行器是运行时中负责执行异步代码的部分。)

Ultimately, something has to execute this state machine, and that something is a runtime. (This is why you may come across mentions of executors when looking into runtimes: an executor is the part of a runtime responsible for executing the async code.)

现在你可以理解为什么编译器在示例 17-3 中阻止我们将 main 本身设为异步函数了。如果 main 是一个异步函数,那么就需要其他东西来管理 main 返回的任何 future 的状态机,但 main 是程序的起点!相反,我们在 main 中调用了 trpl::block_on 函数来设置运行时并运行由 async 块返回的 future,直到它完成。

Now you can see why the compiler stopped us from making main itself an async function back in Listing 17-3. If main were an async function, something else would need to manage the state machine for whatever future main returned, but main is the starting point for the program! Instead, we called the trpl::block_on function in main to set up a runtime and run the future returned by the async block until it’s done.

注意:一些运行时提供了宏,以便你可以编写异步的 main 函数。这些宏将 async fn main() { ... } 重写为正常的 fn main ,其作用与我们在示例 17-4 中手动执行的操作相同:调用一个像 trpl::block_on 一样运行 future 直至完成的函数。

Note: Some runtimes provide macros so you can write an async main function. Those macros rewrite async fn main() { … } to be a normal fn main, which does the same thing we did by hand in Listing 17-4: call a function that runs a future to completion the way trpl::block_on does.

现在让我们把这些碎片拼凑起来,看看我们如何编写并发代码。

Now let’s put these pieces together and see how we can write concurrent code.

让两个 URL 并发竞争 (Racing Two URLs Against Each Other Concurrently)

Racing Two URLs Against Each Other Concurrently

在示例 17-5 中,我们对从命令行传入的两个不同 URL 调用 page_title ,并通过选择先完成的那个 future 来让它们竞争。

In Listing 17-5, we call page_title with two different URLs passed in from the command line and race them by selecting whichever future finishes first.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-05/src/main.rs:all}}

我们首先为用户提供的每个 URL 调用 page_title 。我们将生成的 future 保存为 title_fut_1title_fut_2 。请记住,这些目前还没有执行任何操作,因为 future 是惰性的,我们还没有 await 它们。然后我们将这些 future 传递给 trpl::select ,它返回一个值以指示传递给它的哪些 future 先完成。

We begin by calling page_title for each of the user-supplied URLs. We save the resulting futures as title_fut_1 and title_fut_2. Remember, these don’t do anything yet, because futures are lazy and we haven’t yet awaited them. Then we pass the futures to trpl::select, which returns a value to indicate which of the futures passed to it finishes first.

注意:在幕后, trpl::select 是建立在 futures crate 中定义的更通用的 select 函数之上的。 futures crate 的 select 函数可以做很多 trpl::select 函数做不到的事情,但它也具有一些我们目前可以略过的额外复杂性。

Note: Under the hood, trpl::select is built on a more general select function defined in the futures crate. The futures crate’s select function can do a lot of things that the trpl::select function can’t, but it also has some additional complexity that we can skip over for now.

任何一个 future 都可以名正言顺地“获胜”,所以返回 Result 没有意义。相反, trpl::select 返回一个我们以前没见过的类型 trpl::EitherEither 类型在某种程度上类似于 Result ,因为它有两种情况。不过与 Result 不同的是, Either 中没有成功或失败的概念。相反,它使用 LeftRight 来指示“两者之一”:

Either future can legitimately “win,” so it doesn’t make sense to return a Result. Instead, trpl::select returns a type we haven’t seen before, trpl::Either. The Either type is somewhat similar to a Result in that it has two cases. Unlike Result, though, there is no notion of success or failure baked into Either. Instead, it uses Left and Right to indicate “one or the other”:

#![allow(unused)]
fn main() {
enum Either<A, B> {
    Left(A),
    Right(B),
}
}

如果第一个参数获胜, select 函数返回带有该 future 输出的 Left ;如果第二个 future 参数获胜,则返回带有其输出的 Right 。这与调用函数时参数出现的顺序一致:第一个参数在第二个参数的左侧。

The select function returns Left with that future’s output if the first argument wins, and Right with the second future argument’s output if that one wins. This matches the order the arguments appear in when calling the function: the first argument is to the left of the second argument.

我们还更新了 page_title 以返回传入的相同 URL。这样,如果先返回的页面没有我们可以解析的 <title> ,我们仍然可以打印一条有意义的消息。有了这些可用的信息,我们最后更新了 println! 输出,以指示哪个 URL 先完成以及该 URL 对应网页的 <title> 是什么(如果有的话)。

We also update page_title to return the same URL passed in. That way, if the page that returns first does not have a <title> we can resolve, we can still print a meaningful message. With that information available, we wrap up by updating our println! output to indicate both which URL finished first and what, if any, the <title> is for the web page at that URL.

你现在已经构建了一个小型可运行的 Web 爬虫了!选几个 URL 并运行这个命令行工具。你可能会发现某些网站总是比其他网站快,而在其他情况下,较快的网站在每次运行中都不尽相同。更重要的是,你已经学习了使用 future 的基础知识,所以现在我们可以深入研究我们可以用异步做些什么。

You have built a small working web scraper now! Pick a couple URLs and run the command line tool. You may discover that some sites are consistently faster than others, while in other cases the faster site varies from run to run. More importantly, you’ve learned the basics of working with futures, so now we can dig deeper into what we can do with async.

使用 Async 应用并发 (Applying Concurrency with Async)


x-i18n: generated_at: “2026-03-01T14:45:17Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: c839d2eb1a7051a3719a948f4aa972577bd6e3def82e08c6d903931dcb29cad5 source_path: ch17-02-concurrency-with-async.md workflow: 16

使用 Async 应用并发 (Applying Concurrency with Async)

Applying Concurrency with Async

在本节中,我们将异步应用到我们在第 16 章中使用线程处理的一些相同的并发挑战。因为我们在那里已经讨论了很多关键思想,在本节中我们将重点关注线程和 future 之间的不同之处。

In this section, we’ll apply async to some of the same concurrency challenges we tackled with threads in Chapter 16. Because we already talked about a lot of the key ideas there, in this section we’ll focus on what’s different between threads and futures.

在许多情况下,使用异步处理并发的 API 与使用线程的 API 非常相似。在其他情况下,它们最终会大不相同。即使线程和异步之间的 API “看起来”相似,它们通常也有不同的行为——并且它们几乎总是具有不同的性能特征。

In many cases, the APIs for working with concurrency using async are very similar to those for using threads. In other cases, they end up being quite different. Even when the APIs look similar between threads and async, they often have different behavior—and they nearly always have different performance characteristics.

使用 spawn_task 创建新任务 (Creating a New Task with spawn_task)

Creating a New Task with spawn_task

我们在第 16 章“使用 spawn 创建新线程”部分处理的第一项操作是在两个独立的线程上进行计数。让我们使用异步来做同样的事情。 trpl crate 提供了一个看起来与 thread::spawn API 非常相似的 spawn_task 函数,以及一个作为 thread::sleep API 的异步版本的 sleep 函数。我们可以将它们结合起来实现计数示例,如示例 17-6 所示。

The first operation we tackled in the “Creating a New Thread with spawn section in Chapter 16 was counting up on two separate threads. Let’s do the same using async. The trpl crate supplies a spawn_task function that looks very similar to the thread::spawn API, and a sleep function that is an async version of the thread::sleep API. We can use these together to implement the counting example, as shown in Listing 17-6.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-06/src/main.rs:all}}
}

作为起点,我们使用 trpl::block_on 来设置我们的 main 函数,以便我们的顶级函数可以是异步的。

As our starting point, we set up our main function with trpl::block_on so that our top-level function can be async.

注意:从本章的这一点开始,每个示例都将包含这段在 main 中使用 trpl::block_on 进行包裹的完全相同的代码,因此我们通常会像处理 main 一样跳过它。请记住在你的代码中包含它!

Note: From this point forward in the chapter, every example will include this exact same wrapping code with trpl::block_on in main, so we’ll often skip it just as we do with main. Remember to include it in your code!

然后我们在该代码块中编写两个循环,每个循环都包含一个 trpl::sleep 调用,它会等待半秒(500 毫秒)再发送下一条消息。我们将一个循环放在 trpl::spawn_task 的主体中,另一个放在顶级 for 循环中。我们还在 sleep 调用后添加了一个 await

Then we write two loops within that block, each containing a trpl::sleep call, which waits for half a second (500 milliseconds) before sending the next message. We put one loop in the body of a trpl::spawn_task and the other in a top-level for loop. We also add an await after the sleep calls.

这段代码的行为与基于线程的实现类似——包括当你运行它时,你可能会在自己的终端中看到消息以不同的顺序出现:

This code behaves similarly to the thread-based implementation—including the fact that you may see the messages appear in a different order in your own terminal when you run it:

hi number 1 from the second task!
hi number 1 from the first task!
hi number 2 from the first task!
hi number 2 from the second task!
hi number 3 from the first task!
hi number 3 from the second task!
hi number 4 from the first task!
hi number 4 from the second task!
hi number 5 from the first task!

由于由 spawn_task 生成的任务在 main 函数结束时被关闭,所以这个版本在主异步块主体中的 for 循环结束时就会停止。如果你想让它一直运行到任务完成,你需要使用联接句柄 (join handle) 来等待第一个任务完成。对于线程,我们使用了 join 方法来“阻塞”直到线程运行结束。在示例 17-7 中,我们可以使用 await 执行相同的操作,因为任务句柄本身就是一个 future。它的 Output 类型是一个 Result ,所以我们在等待它之后也对其进行了 unwrap。

This version stops as soon as the for loop in the body of the main async block finishes, because the task spawned by spawn_task is shut down when the main function ends. If you want it to run all the way to the task’s completion, you will need to use a join handle to wait for the first task to complete. With threads, we used the join method to “block” until the thread was done running. In Listing 17-7, we can use await to do the same thing, because the task handle itself is a future. Its Output type is a Result, so we also unwrap it after awaiting it.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-07/src/main.rs:handle}}
}

这个更新后的版本会一直运行到“两个”循环都结束:

This updated version runs until both loops finish:

hi number 1 from the second task!
hi number 1 from the first task!
hi number 2 from the first task!
hi number 2 from the second task!
hi number 3 from the first task!
hi number 3 from the second task!
hi number 4 from the first task!
hi number 4 from the second task!
hi number 5 from the first task!
hi number 6 from the first task!
hi number 7 from the first task!
hi number 8 from the first task!
hi number 9 from the first task!

到目前为止,看起来异步和线程给了我们类似的结果,只是语法不同:使用 await 而不是在联接句柄上调用 join ,以及等待 sleep 调用。

So far, it looks like async and threads give us similar outcomes, just with different syntax: using await instead of calling join on the join handle, and awaiting the sleep calls.

更大的区别在于,我们不需要为了执行此操作而产生另一个操作系统线程。事实上,我们甚至不需要在这里生成任务。因为异步块会编译成匿名 future,我们可以将每个循环放在一个异步块中,并让运行时使用 trpl::join 函数让它们都运行到完成。

The bigger difference is that we didn’t need to spawn another operating system thread to do this. In fact, we don’t even need to spawn a task here. Because async blocks compile to anonymous futures, we can put each loop in an async block and have the runtime run them both to completion using the trpl::join function.

在第 16 章“等待所有线程完成”部分中,我们展示了如何在你调用 std::thread::spawn 时返回的 JoinHandle 类型上使用 join 方法。 trpl::join 函数类似,但是针对 future 的。当你给它两个 future 时,它会产生一个新的单一 future,一旦你传入的两个 future “都”完成了,它的输出就是一个包含每个 future 输出的元组。因此,在示例 17-8 中,我们使用 trpl::join 来等待 fut1fut2 结束。我们“不”等待 fut1fut2 ,而是等待由 trpl::join 产生的新 future。我们忽略输出,因为它只是一个包含两个单元值的元组。

In the “Waiting for All Threads to Finish” section in Chapter 16, we showed how to use the join method on the JoinHandle type returned when you call std::thread::spawn. The trpl::join function is similar, but for futures. When you give it two futures, it produces a single new future whose output is a tuple containing the output of each future you passed in once they both complete. Thus, in Listing 17-8, we use trpl::join to wait for both fut1 and fut2 to finish. We do not await fut1 and fut2 but instead the new future produced by trpl::join. We ignore the output, because it’s just a tuple containing two unit values.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-08/src/main.rs:join}}
}

当我们运行此代码时,我们看到两个 future 都运行到了完成:

When we run this, we see both futures run to completion:

hi number 1 from the first task!
hi number 1 from the second task!
hi number 2 from the first task!
hi number 2 from the second task!
hi number 3 from the first task!
hi number 3 from the second task!
hi number 4 from the first task!
hi number 4 from the second task!
hi number 5 from the first task!
hi number 6 from the first task!
hi number 7 from the first task!
hi number 8 from the first task!
hi number 9 from the first task!

现在,你每次都会看到完全相同的顺序,这与我们通过线程以及通过示例 17-7 中的 trpl::spawn_task 看到的情况非常不同。这是因为 trpl::join 函数是“公平的 (fair)”,这意味着它同等地检查每个 future,在它们之间交替,并且如果另一个 future 就绪,绝不让其中一个跑在前面。对于线程,由操作系统决定检查哪个线程以及让它运行多久。对于异步 Rust,由运行时决定检查哪个任务。(在实践中,细节变得很复杂,因为异步运行时可能会在底层使用操作系统线程作为其管理并发的一部分,因此保证公平性对于运行时来说可能需要更多工作——但仍然是可能的!)运行时不必保证任何给定操作的公平性,它们通常提供不同的 API 来让你选择是否需要公平性。

Now, you’ll see the exact same order every time, which is very different from what we saw with threads and with trpl::spawn_task in Listing 17-7. That is because the trpl::join function is fair, meaning it checks each future equally often, alternating between them, and never lets one race ahead if the other is ready. With threads, the operating system decides which thread to check and how long to let it run. With async Rust, the runtime decides which task to check. (In practice, the details get complicated because an async runtime might use operating system threads under the hood as part of how it manages concurrency, so guaranteeing fairness can be more work for a runtime—but it’s still possible!) Runtimes don’t have to guarantee fairness for any given operation, and they often offer different APIs to let you choose whether or not you want fairness.

尝试一些这些在等待 future 上的变体,看看它们会产生什么效果:

  • 移除其中一个或两个循环周围的异步块。
  • 在定义每个异步块后立即 await 它。
  • 仅将第一个循环包装在异步块中,并在第二个循环体之后 await 生成的 future。

Try some of these variations on awaiting the futures and see what they do:

  • Remove the async block from around either or both of the loops.
  • Await each async block immediately after defining it.
  • Wrap only the first loop in an async block, and await the resulting future after the body of second loop.

为了增加挑战性,看看你是否能在运行代码“之前”弄清楚每种情况下的输出会是什么!

For an extra challenge, see if you can figure out what the output will be in each case before running the code!

使用消息传递在两个任务之间发送数据 (Sending Data Between Two Tasks Using Message Passing)

Sending Data Between Two Tasks Using Message Passing

在 future 之间共享数据也会感觉很熟悉:我们将再次使用消息传递,但这次使用的是类型和函数的异步版本。我们将采取与第 16 章“通过消息传递在线程间转移数据”部分略有不同的路径,以说明基于线程和基于 future 的并发之间的一些关键区别。在示例 17-9 中,我们将仅从单个异步块开始——“不”像产生单独线程那样产生一个单独的任务。

Sharing data between futures will also be familiar: we’ll use message passing again, but this time with async versions of the types and functions. We’ll take a slightly different path than we did in the “Transfer Data Between Threads with Message Passing” section in Chapter 16 to illustrate some of the differences between thread-based and futures-based concurrency. In Listing 17-9, we’ll begin with just a single async block—not spawning a separate task as we spawned a separate thread.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-09/src/main.rs:channel}}
}

在这里,我们使用 trpl::channel ,这是我们在第 16 章中与线程一起使用的多生产者单消费者通道 API 的异步版本。该 API 的异步版本与基于线程的版本只有一点点不同:它使用的是可变的而非不可变的接收端 rx ,并且它的 recv 方法产生一个我们需要 await 的 future,而不是直接产生值。现在我们可以从发送端向接收端发送消息。请注意,我们不必产生单独的线程甚至任务;我们只需要 await rx.recv 调用。

Here, we use trpl::channel, an async version of the multiple-producer, single-consumer channel API we used with threads back in Chapter 16. The async version of the API is only a little different from the thread-based version: it uses a mutable rather than an immutable receiver rx, and its recv method produces a future we need to await rather than producing the value directly. Now we can send messages from the sender to the receiver. Notice that we don’t have to spawn a separate thread or even a task; we merely need to await the rx.recv call.

std::mpsc::channel 中的同步 Receiver::recv 方法会一直阻塞直到收到消息。 trpl::Receiver::recv 方法则不会,因为它是异步的。它不是阻塞,而是将控制权交还给运行时,直到收到消息或通道的发送端关闭。相比之下,我们不等待 send 调用,因为它不会阻塞。它不需要阻塞,因为我们要发送到的通道是无界的。

The synchronous Receiver::recv method in std::mpsc::channel blocks until it receives a message. The trpl::Receiver::recv method does not, because it is async. Instead of blocking, it hands control back to the runtime until either a message is received or the send side of the channel closes. By contrast, we don’t await the send call, because it doesn’t block. It doesn’t need to, because the channel we’re sending it into is unbounded.

注意:因为所有这些异步代码都运行在 trpl::block_on 调用中的异步块内,所以其中的一切都可以避免阻塞。然而,在此“之外”的代码将阻塞在 block_on 函数返回处。这就是 trpl::block_on 函数的全部意义:它让你“选择”在某组异步代码上的何处阻塞,以及在何处在同步和异步代码之间进行切换。

Note: Because all of this async code runs in an async block in a trpl::block_on call, everything within it can avoid blocking. However, the code outside it will block on the block_on function returning. That’s the whole point of the trpl::block_on function: it lets you choose where to block on some set of async code, and thus where to transition between sync and async code.

注意这个例子的两点。首先,消息会立即到达。其次,虽然我们在这里使用了 future,但目前还没有并发。清单中的所有内容都是按顺序发生的,就像没有涉及 future 一样。

Notice two things about this example. First, the message will arrive right away. Second, although we use a future here, there’s no concurrency yet. Everything in the listing happens in sequence, just as it would if there were no futures involved.

让我们通过发送一系列消息并在它们之间休眠来解决第一部分,如示例 17-10 所示。

Let’s address the first part by sending a series of messages and sleeping in between them, as shown in Listing 17-10.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-10/src/main.rs:many-messages}}

除了发送消息,我们还需要接收它们。在这种情况下,因为我们知道会有多少条消息到来,我们可以手动调用 rx.recv().await 四次。但在现实世界中,我们通常会等待某种“未知”数量的消息,所以我们需要一直等待,直到我们确定不再有消息为止。

In addition to sending the messages, we need to receive them. In this case, because we know how many messages are coming in, we could do that manually by calling rx.recv().await four times. In the real world, though, we’ll generally be waiting on some unknown number of messages, so we need to keep waiting until we determine that there are no more messages.

在示例 16-10 中,我们使用 for 循环处理从同步通道接收的所有项。然而,Rust 目前还没有一种方法将 for 循环与“异步产生”的一系列项一起使用,因此我们需要使用一种我们以前没见过的循环: while let 条件循环。这是我们在第 6 章“使用 if letlet...else 的简洁控制流”部分中看到的 if let 结构的循环版本。只要它指定的模式继续与该值匹配,循环就会继续执行。

In Listing 16-10, we used a for loop to process all the items received from a synchronous channel. Rust doesn’t yet have a way to use a for loop with an asynchronously produced series of items, however, so we need to use a loop we haven’t seen before: the while let conditional loop. This is the loop version of the if let construct we saw back in the “Concise Control Flow with if let and let...else section in Chapter 6. The loop will continue executing as long as the pattern it specifies continues to match the value.

rx.recv 调用产生一个 future,我们 await 它。运行时将暂停该 future 直到它就绪。一旦消息到达,该 future 将解析为 Some(message) ,次数与消息到达的次数相同。当通道关闭时,无论是否“有”任何消息到达,该 future 都将解析为 None ,以指示不再有值,因此我们应该停止轮询——也就是说,停止等待。

The rx.recv call produces a future, which we await. The runtime will pause the future until it is ready. Once a message arrives, the future will resolve to Some(message) as many times as a message arrives. When the channel closes, regardless of whether any messages have arrived, the future will instead resolve to None to indicate that there are no more values and thus we should stop polling—that is, stop awaiting.

while let 循环将这一切结合在一起。如果调用 rx.recv().await 的结果是 Some(message) ,我们就可以访问该消息,并可以在循环体中使用它,就像使用 if let 一样。如果结果是 None ,循环结束。每次循环完成,它都会再次命中等待点,因此运行时会再次暂停它,直到另一条消息到达。

The while let loop pulls all of this together. If the result of calling rx.recv().await is Some(message), we get access to the message and we can use it in the loop body, just as we could with if let. If the result is None, the loop ends. Every time the loop completes, it hits the await point again, so the runtime pauses it again until another message arrives.

代码现在成功地发送和接收了所有消息。不幸的是,仍然存在几个问题。一方面,消息并不是每隔半秒到达一次。它们在启动程序 2 秒(2,000 毫秒)后一次性到达。另一方面,这个程序也永远不会退出!相反,它永远在等待新消息。你需要使用 ctrl-C 关闭它。

The code now successfully sends and receives all of the messages. Unfortunately, there are still a couple of problems. For one thing, the messages do not arrive at half-second intervals. They arrive all at once, 2 seconds (2,000 milliseconds) after we start the program. For another, this program also never exits! Instead, it waits forever for new messages. You will need to shut it down using ctrl-C.

单个异步块内的代码线性执行 (Code Within One Async Block Executes Linearly)

让我们首先研究一下为什么消息会在延迟结束时一次性到达,而不是在每条消息之间都有延迟。在给定的异步块内, await 关键字在代码中出现的顺序也是程序运行时执行它们的顺序。

Let’s start by examining why the messages come in all at once after the full delay, rather than coming in with delays between each one. Within a given async block, the order in which await keywords appear in the code is also the order in which they’re executed when the program runs.

示例 17-10 中只有一个异步块,所以其中的一切都线性运行。仍然没有并发。所有的 tx.send 调用都会发生,并穿插着所有的 trpl::sleep 调用及其关联的等待点。只有到那时, while let 循环才能通过 recv 调用上的任何 await 点。

There’s only one async block in Listing 17-10, so everything in it runs linearly. There’s still no concurrency. All the tx.send calls happen, interspersed with all of the trpl::sleep calls and their associated await points. Only then does the while let loop get to go through any of the await points on the recv calls.

为了获得我们想要的行为,即在每条消息之间发生休眠延迟,我们需要将 txrx 操作放在它们自己的异步块中,如示例 17-11 所示。然后运行时可以使用 trpl::join 分别执行它们,就像在示例 17-8 中一样。我们再次等待调用 trpl::join 的结果,而不是单个 future。如果我们按顺序等待单个 future,我们最终只会回到顺序流——这正是我们“不”想做的。

To get the behavior we want, where the sleep delay happens between each message, we need to put the tx and rx operations in their own async blocks, as shown in Listing 17-11. Then the runtime can execute each of them separately using trpl::join, just as in Listing 17-8. Once again, we await the result of calling trpl::join, not the individual futures. If we awaited the individual futures in sequence, we would just end up back in a sequential flow—exactly what we’re trying not to do.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-11/src/main.rs:futures}}

使用示例 17-11 中更新后的代码,消息以 500 毫秒的间隔打印出来,而不是在 2 秒后全部匆忙打印。

With the updated code in Listing 17-11, the messages get printed at 500-millisecond intervals, rather than all in a rush after 2 seconds.

将所有权移动到异步块中 (Moving Ownership Into an Async Block)

然而,由于 while let 循环与 trpl::join 交互的方式,程序仍然永远不会退出:

  • trpl::join 返回的 future 仅在传递给它的“两个” future 都完成后才完成。
  • tx_fut 这个 future 在发送 vals 中的最后一条消息后完成休眠时完成。
  • rx_fut 这个 future 在 while let 循环结束前不会完成。
  • while let 循环在 await rx.recv 产生 None 之前不会结束。
  • 只有当通道的另一端关闭时,await rx.recv 才会返回 None
  • 只有当我们调用 rx.close 或者当发送端 tx 被丢弃时,通道才会关闭。
  • 我们没有在任何地方调用 rx.close ,并且直到传递给 trpl::block_on 的最外层异步块结束, tx 才会被丢弃。
  • 该代码块无法结束,因为它正被阻塞在 trpl::join 完成处,这又把我们带回了这份清单的顶部。

The program still never exits, though, because of the way the while let loop interacts with trpl::join:

  • The future returned from trpl::join completes only once both futures passed to it have completed.
  • The tx_fut future completes once it finishes sleeping after sending the last message in vals.
  • The rx_fut future won’t complete until the while let loop ends.
  • The while let loop won’t end until awaiting rx.recv produces None.
  • Awaiting rx.recv will return None only once the other end of the channel is closed.
  • The channel will close only if we call rx.close or when the sender side, tx, is dropped.
  • We don’t call rx.close anywhere, and tx won’t be dropped until the outermost async block passed to trpl::block_on ends.
  • The block can’t end because it is blocked on trpl::join completing, which takes us back to the top of this list.

现在,我们发送消息的异步块只是“借用”了 tx ,因为发送消息不需要所有权,但如果我们可以将 tx “移动 (move)”到该异步块中,它就会在那个块结束时被丢弃。在第 13 章的“捕获引用或移动所有权”部分,你学习了如何对闭包使用 move 关键字,并且如第 16 章“在线程中使用 move 闭包”部分所述,我们在处理线程时通常需要将数据移动到闭包中。相同的基本动态也适用于异步块,因此 move 关键字在异步块上的工作方式与在闭包上的工作方式相同。

Right now, the async block where we send the messages only borrows tx because sending a message doesn’t require ownership, but if we could move tx into that async block, it would be dropped once that block ends. In the “Capturing References or Moving Ownership” section in Chapter 13, you learned how to use the move keyword with closures, and, as discussed in the “Using move Closures with Threads” section in Chapter 16, we often need to move data into closures when working with threads. The same basic dynamics apply to async blocks, so the move keyword works with async blocks just as it does with closures.

在示例 17-12 中,我们将用于发送消息的代码块从 async 更改为 async move

In Listing 17-12, we change the block used to send messages from async to async move.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-12/src/main.rs:with-move}}
}

当我们运行“这个”版本的代码时,它会在最后一条消息被发送和接收后优雅地关闭。接下来,让我们看看为了从多个 future 发送数据需要做出哪些更改。

When we run this version of the code, it shuts down gracefully after the last message is sent and received. Next, let’s see what would need to change to send data from more than one future.

使用 join! 宏联接多个 Future (Joining a Number of Futures with the join! Macro)

Joining a Number of Futures with the join! Macro

这个异步通道也是一个多生产者通道,所以如果我们想从多个 future 发送消息,我们可以在 tx 上调用 clone ,如示例 17-13 所示。

This async channel is also a multiple-producer channel, so we can call clone on tx if we want to send messages from multiple futures, as shown in Listing 17-13.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-13/src/main.rs:here}}
}

首先,我们克隆 tx ,在第一个异步块之外创建 tx1 。我们像之前对 tx 所做的那样,将 tx1 移动到该代码块中。然后,在后面,我们将原始的 tx 移动到一个“新”的异步块中,在那里我们以稍慢的延迟发送更多消息。我们恰好将这个新的异步块放在接收消息的异步块之后,但放在它之前也同样可以。关键是 future 被等待的顺序,而不是它们被创建的顺序。

First, we clone tx, creating tx1 outside the first async block. We move tx1 into that block just as we did before with tx. Then, later, we move the original tx into a new async block, where we send more messages on a slightly slower delay. We happen to put this new async block after the async block for receiving messages, but it could go before it just as well. The key is the order in which the futures are awaited, not in which they’re created.

两个发送消息的异步块都需要是 async move 块,这样 txtx1 都会在这些块结束时被丢弃。否则,我们将最终回到我们一开始所处的那个无限循环。

Both of the async blocks for sending messages need to be async move blocks so that both tx and tx1 get dropped when those blocks finish. Otherwise, we’ll end up back in the same infinite loop we started out in.

最后,我们从 trpl::join 切换到 trpl::join! 来处理额外的 future: join! 宏可以等待任意数量的 future,前提是我们在编译时知道 future 的数量。我们将在本章稍后讨论如何等待未知数量的 future 集合。

Finally, we switch from trpl::join to trpl::join! to handle the additional future: the join! macro awaits an arbitrary number of futures where we know the number of futures at compile time. We’ll discuss awaiting a collection of an unknown number of futures later in this chapter.

现在我们看到了来自两个发送端 future 的所有消息,并且因为发送端 future 在发送后使用了略有不同的延迟,消息也以这些不同的间隔被接收:

Now we see all the messages from both sending futures, and because the sending futures use slightly different delays after sending, the messages are also received at those different intervals:

received 'hi'
received 'more'
received 'from'
received 'the'
received 'messages'
received 'future'
received 'for'
received 'you'

我们已经探索了如何使用消息传递在 future 之间发送数据,异步块内的代码是如何顺序运行的,如何将所有权移动到异步块中,以及如何联接多个 future。接下来,让我们讨论如何以及为什么要告诉运行时它可以切换到另一个任务。

We’ve explored how to use message passing to send data between futures, how code within an async block runs sequentially, how to move ownership into an async block, and how to join multiple futures. Next, let’s discuss how and why to tell the runtime it can switch to another task.

处理任意数量的 Futures (Working With Any Number of Futures)


x-i18n: generated_at: “2026-03-01T14:45:52Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f9ab52571b5926c51076018f6b0657f75e6b14d40afac769bf79f883ec12ec4d source_path: ch17-03-more-futures.md workflow: 16

向运行时交出控制权 (Yielding Control to the Runtime)

回想“我们的第一个异步程序”一节,在每个等待点处,如果被等待的 future 尚未就绪,Rust 会给运行时一个暂停任务并切换到另一个任务的机会。反之亦然:Rust “仅”在等待点处暂停异步块并将控制权交还给运行时。等待点之间的所有内容都是同步的。

Recall from the “Our First Async Program” section that at each await point, Rust gives a runtime a chance to pause the task and switch to another one if the future being awaited isn’t ready. The inverse is also true: Rust only pauses async blocks and hands control back to a runtime at an await point. Everything between await points is synchronous.

这意味着如果你在异步块中执行一堆没有等待点的工作,那个 future 将会阻塞任何其他 future 取得进展。你可能有时会听到这被称为一个 future “饿死 (starving)”了其他 future。在某些情况下,这可能不是什么大问题。然而,如果你正在执行某种昂贵的设置或长时间运行的工作,或者如果你有一个会无限期持续执行某个特定任务的 future,你就需要考虑何时以及在何处将控制权交还给运行时。

That means if you do a bunch of work in an async block without an await point, that future will block any other futures from making progress. You may sometimes hear this referred to as one future starving other futures. In some cases, that may not be a big deal. However, if you are doing some kind of expensive setup or long-running work, or if you have a future that will keep doing some particular task indefinitely, you’ll need to think about when and where to hand control back to the runtime.

让我们模拟一个长时间运行的操作来阐述饥饿问题,然后探索如何解决它。示例 17-14 引入了一个 slow 函数。

Let’s simulate a long-running operation to illustrate the starvation problem, then explore how to solve it. Listing 17-14 introduces a slow function.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-14/src/main.rs:slow}}
}

这段代码使用 std::thread::sleep 而不是 trpl::sleep ,因此调用 slow 会阻塞当前线程若干毫秒。我们可以使用 slow 来代表现实世界中既长时间运行又是阻塞的操作。

This code uses std::thread::sleep instead of trpl::sleep so that calling slow will block the current thread for some number of milliseconds. We can use slow to stand in for real-world operations that are both long-running and blocking.

在示例 17-15 中,我们使用 slow 来模拟在一对 future 中执行这类 CPU 密集型工作。

In Listing 17-15, we use slow to emulate doing this kind of CPU-bound work in a pair of futures.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-15/src/main.rs:slow-futures}}
}

每个 future 仅在执行完一堆慢速操作“之后”才将控制权交还给运行时。如果你运行这段代码,你将看到如下输出:

Each future hands control back to the runtime only after carrying out a bunch of slow operations. If you run this code, you will see this output:

'a' started.
'a' ran for 30ms
'a' ran for 10ms
'a' ran for 20ms
'b' started.
'b' ran for 75ms
'b' ran for 10ms
'b' ran for 15ms
'b' ran for 350ms
'a' finished.

与示例 17-5 中我们使用 trpl::select 来竞争获取两个 URL 的 future 一样, select 仍然在 a 完成时立即结束。不过,这两个 future 中对 slow 的调用之间没有交错。 a 这个 future 执行其所有工作直到 trpl::sleep 调用被 await,然后 b 这个 future 执行其所有工作直到它自己的 trpl::sleep 调用被 await,最后 a 这个 future 完成。为了允许两个 future 在它们的慢速任务之间取得进展,我们需要等待点,以便我们可以将控制权交还给运行时。这意味着我们需要一些可以 await 的东西!

As with Listing 17-5 where we used trpl::select to race futures fetching two URLs, select still finishes as soon as a is done. There’s no interleaving between the calls to slow in the two futures, though. The a future does all of its work until the trpl::sleep call is awaited, then the b future does all of its work until its own trpl::sleep call is awaited, and finally the a future completes. To allow both futures to make progress between their slow tasks, we need await points so we can hand control back to the runtime. That means we need something we can await!

我们已经在示例 17-15 中看到了这种交回控制权的情况:如果我们移除 a future 末尾的 trpl::sleep ,它会在 b future “根本没有”运行的情况下完成。让我们尝试使用 trpl::sleep 函数作为起点,让操作轮流取得进展,如示例 17-16 所示。

We can already see this kind of handoff happening in Listing 17-15: if we removed the trpl::sleep at the end of the a future, it would complete without the b future running at all. Let’s try using the trpl::sleep function as a starting point for letting operations switch off making progress, as shown in Listing 17-16.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-16/src/main.rs:here}}
}

我们在每次对 slow 的调用之间添加了带有等待点的 trpl::sleep 调用。现在这两个 future 的工作交错进行了:

We’ve added trpl::sleep calls with await points between each call to slow. Now the two futures’ work is interleaved:

'a' started.
'a' ran for 30ms
'b' started.
'b' ran for 75ms
'a' ran for 10ms
'b' ran for 10ms
'a' ran for 20ms
'b' ran for 15ms
'a' finished.

a 这个 future 在将控制权交给 b 之前仍然运行了一会儿,因为它在调用 trpl::sleep 之前先调用了 slow ,但在此之后,每当其中一个命中等待点时,这两个 future 就会来回切换。在本例中,我们在每次调用 slow 之后都这样做,但我们可以以任何对我们最有意义的方式来分解工作。

The a future still runs for a bit before handing off control to b, because it calls slow before ever calling trpl::sleep, but after that the futures swap back and forth each time one of them hits an await point. In this case, we have done that after every call to slow, but we could break up the work in whatever way makes the most sense to us.

然而,我们并不是真的想在这里“休眠 (sleep)”:我们想尽可能快地取得进展。我们只需要将控制权交还给运行时。我们可以直接使用 trpl::yield_now 函数来实现这一点。在示例 17-17 中,我们将所有这些 trpl::sleep 调用替换为 trpl::yield_now

We don’t really want to sleep here, though: we want to make progress as fast as we can. We just need to hand back control to the runtime. We can do that directly, using the trpl::yield_now function. In Listing 17-17, we replace all those trpl::sleep calls with trpl::yield_now.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-17/src/main.rs:yields}}
}

这段代码不仅更清晰地表达了实际意图,而且可以比使用 sleep 快得多,因为像 sleep 使用的计时器通常对精细度有限制。例如,我们正在使用的 sleep 版本,即使我们传递一个 1 纳秒的 Duration ,它也总是会休眠至少 1 毫秒。再说一次,现代计算机是“非常快”的:它们在 1 毫秒内可以做很多事情!

This code is both clearer about the actual intent and can be significantly faster than using sleep, because timers such as the one used by sleep often have limits on how granular they can be. The version of sleep we are using, for example, will always sleep for at least a millisecond, even if we pass it a Duration of one nanosecond. Again, modern computers are fast: they can do a lot in one millisecond!

这意味着即使对于计算密集型任务,异步也是有用的,这取决于你的程序还在做其他什么事情,因为它提供了一个有用的工具来组织程序不同部分之间的关系(但要以异步状态机的开销为代价)。这是一种“协作式多任务处理 (cooperative multitasking)”,每个 future 都有权通过等待点决定何时移交控制权。因此,每个 future 也有责任避免阻塞太长时间。在某些基于 Rust 的嵌入式操作系统中,这是“唯一”一种多任务处理方式!

That means that async can be useful even for compute-bound tasks, depending on what else your program is doing, because it provides a useful tool for structuring the relationships between different parts of the program (but at a cost of the overhead of the async state machine). This is a form of cooperative multitasking, where each future has the power to determine when it hands over control via await points. Each future therefore also has the responsibility to avoid blocking for too long. In some Rust-based embedded operating systems, this is the only kind of multitasking!

当然,在实际代码中,你通常不会在每一行都将函数调用与等待点交替。虽然以这种方式交出控制权相对便宜,但它并不是免费的。在许多情况下,尝试拆分一个计算密集型任务可能会使其显著变慢,因此有时为了“整体”性能,让一个操作短暂阻塞会更好。始终进行测量,看看代码实际的性能瓶颈在哪里。不过,如果你“确实”看到大量预期会并发发生的工作实际上是串行发生的,那么请务必记住这一底层动态!

In real-world code, you won’t usually be alternating function calls with await points on every single line, of course. While yielding control in this way is relatively inexpensive, it’s not free. In many cases, trying to break up a compute-bound task might make it significantly slower, so sometimes it’s better for overall performance to let an operation block briefly. Always measure to see what your code’s actual performance bottlenecks are. The underlying dynamic is important to keep in mind, though, if you are seeing a lot of work happening in serial that you expected to happen concurrently!

构建我们自己的异步抽象 (Building Our Own Async Abstractions)

Building Our Own Async Abstractions

我们还可以将 future 组合在一起以创建新的模式。例如,我们可以使用现有的异步构建块构建一个 timeout 函数。完成后,结果将成为我们可以用来创建更多异步抽象的另一个构建块。

We can also compose futures together to create new patterns. For example, we can build a timeout function with async building blocks we already have. When we’re done, the result will be another building block we could use to create still more async abstractions.

示例 17-18 展示了我们期望这个 timeout 如何与一个慢速 future 配合工作。

Listing 17-18 shows how we would expect this timeout to work with a slow future.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-18/src/main.rs:here}}

让我们来实现它!首先,让我们考虑一下 timeout 的 API:

  • 它本身需要是一个异步函数,以便我们可以 await 它。
  • 它的第一个参数应该是一个要运行的 future。我们可以将其设为泛型,以允许它与任何 future 配合工作。
  • 它的第二个参数将是等待的最长时间。如果我们使用 Duration ,那将很容易传递给 trpl::sleep
  • 它应该返回一个 Result 。如果 future 成功完成, Result 将是带有 future 产生值的 Ok 。如果超时先结束, Result 将是带有超时等待时长的 Err

Let’s implement this! To begin, let’s think about the API for timeout:

  • It needs to be an async function itself so we can await it.
  • Its first parameter should be a future to run. We can make it generic to allow it to work with any future.
  • Its second parameter will be the maximum time to wait. If we use a Duration, that will make it easy to pass along to trpl::sleep.
  • It should return a Result. If the future completes successfully, the Result will be Ok with the value produced by the future. If the timeout elapses first, the Result will be Err with the duration that the timeout waited for.

示例 17-19 显示了这个声明。

Listing 17-19 shows this declaration.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-19/src/main.rs:declaration}}

这满足了我们对类型的目标。现在让我们考虑一下我们需要的“行为 (behavior)”:我们想让传入的 future 与时长进行竞争。我们可以使用 trpl::sleep 根据时长创建一个计时器 future,并使用 trpl::select 让该计时器与调用者传入的 future 一起运行。

That satisfies our goals for the types. Now let’s think about the behavior we need: we want to race the future passed in against the duration. We can use trpl::sleep to make a timer future from the duration, and use trpl::select to run that timer with the future the caller passes in.

在示例 17-20 中,我们通过对 await trpl::select 的结果进行匹配来实现 timeout

In Listing 17-20, we implement timeout by matching on the result of awaiting trpl::select.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-20/src/main.rs:implementation}}
}

trpl::select 的实现不是公平的:它总是按照参数传入的顺序进行轮询(其他 select 实现会随机选择先轮询哪个参数)。因此,我们先将 future_to_try 传递给 select ,这样即使 max_time 是一个非常短的时长,它也有机会完成。如果 future_to_try 先完成, select 将返回带有 future_to_try 输出的 Left 。如果 timer 先完成, select 将返回带有计时器输出 ()Right

The implementation of trpl::select is not fair: it always polls arguments in the order in which they are passed (other select implementations will randomly choose which argument to poll first). Thus, we pass future_to_try to select first so it gets a chance to complete even if max_time is a very short duration. If future_to_try finishes first, select will return Left with the output from future_to_try. If timer finishes first, select will return Right with the timer’s output of ().

如果 future_to_try 成功并且我们得到了一个 Left(output) ,我们返回 Ok(output) 。如果休眠计时器先结束,我们得到了一个 Right(()) ,我们就用 _ 忽略 () 并返回 Err(max_time)

If the future_to_try succeeds and we get a Left(output), we return Ok(output). If the sleep timer elapses instead and we get a Right(()), we ignore the () with _ and return Err(max_time) instead.

至此,我们已经拥有一个由另外两个异步辅助工具构建而成的可运行的 timeout 。如果我们运行代码,它将在超时后打印失败模式:

With that, we have a working timeout built out of two other async helpers. If we run our code, it will print the failure mode after the timeout:

Failed after 2 seconds

因为 future 可以与其他 future 组合,所以你可以使用更小的异步构建块构建出真正强大的工具。例如,你可以使用相同的方法将超时与重试结合起来,并依次将这些功能与网络调用等操作结合使用(例如示例 17-5 中的那些)。

Because futures compose with other futures, you can build really powerful tools using smaller async building blocks. For example, you can use this same approach to combine timeouts with retries, and in turn use those with operations such as network calls (such as those in Listing 17-5).

在实践中,你通常会直接使用 asyncawait ,其次是诸如 select 之类的函数以及诸如 join! 宏之类的宏,来控制最外层 future 的执行方式。

In practice, you’ll usually work directly with async and await, and secondarily with functions such as select and macros such as the join! macro to control how the outermost futures are executed.

我们现在已经看到了多种同时处理多个 future 的方法。接下来,我们将通过“流 (streams)”来看看我们如何处理随时间推移按顺序排列的多个 future。

We’ve now seen a number of ways to work with multiple futures at the same time. Up next, we’ll look at how we can work with multiple futures in a sequence over time with streams.

Streams:序列中的 Futures (Streams: Futures in Sequence)


x-i18n: generated_at: “2026-03-01T14:46:41Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: b494f9019a1e9a79992db4c056377995227764d2822bb8cd0f86d51ce4a08655 source_path: ch17-04-streams.md workflow: 16

流:顺序排列的 Future (Streams: Futures in Sequence)

回想一下在本章前面的“消息传递”一节中我们如何为异步通道使用接收端。异步 recv 方法会随时间产生一系列项。这是一个更通用模式的一个实例,称为“流 (stream)”。许多概念都可以自然地表示为流:队列中可用的项、当完整数据集对于计算机内存来说太大时从文件系统增量拉取的数据块,或者随时间通过网络到达的数据。因为流是 future,所以我们可以将它们与任何其他种类的 future 一起使用,并以有趣的方式组合它们。例如,我们可以批量处理事件以避免触发过多的网络调用,为一系列长时间运行的操作设置超时,或者限制用户界面事件以避免做无谓的工作。

Recall how we used the receiver for our async channel earlier in this chapter in the “Message Passing” section. The async recv method produces a sequence of items over time. This is an instance of a much more general pattern known as a stream. Many concepts are naturally represented as streams: items becoming available in a queue, chunks of data being pulled incrementally from the filesystem when the full data set is too large for the computer’s memory, or data arriving over the network over time. Because streams are futures, we can use them with any other kind of future and combine them in interesting ways. For example, we can batch up events to avoid triggering too many network calls, set timeouts on sequences of long-running operations, or throttle user interface events to avoid doing needless work.

我们在第 13 章Iterator 特征和 next 方法”一节中看到过一系列项,但迭代器和异步通道接收端之间有两个区别。第一个区别是时间:迭代器是同步的,而通道接收端是异步的。第二个区别是 API。当直接处理 Iterator 时,我们调用它的同步 next 方法。特别地,对于 trpl::Receiver 流,我们调用了一个异步 recv 方法。除此之外,这些 API 感觉非常相似,而且这种相似性并非巧合。流就像是迭代的一种异步形式。不过,虽然 trpl::Receiver 特别用于等待接收消息,但通用的流 API 则广泛得多:它像 Iterator 那样提供下一个项,但是是异步的。

We saw a sequence of items back in Chapter 13, when we looked at the Iterator trait in “The Iterator Trait and the next Method” section, but there are two differences between iterators and the async channel receiver. The first difference is time: iterators are synchronous, while the channel receiver is asynchronous. The second difference is the API. When working directly with Iterator, we call its synchronous next method. With the trpl::Receiver stream in particular, we called an asynchronous recv method instead. Otherwise, these APIs feel very similar, and that similarity isn’t a coincidence. A stream is like an asynchronous form of iteration. Whereas the trpl::Receiver specifically waits to receive messages, though, the general-purpose stream API is much broader: it provides the next item the way Iterator does, but asynchronously.

Rust 中迭代器和流之间的相似性意味着我们实际上可以从任何迭代器创建一个流。与迭代器一样,我们可以通过调用流的 next 方法然后 await 输出处理流,如示例 17-21 所示,这段代码目前还无法编译。

The similarity between iterators and streams in Rust means we can actually create a stream from any iterator. As with an iterator, we can work with a stream by calling its next method and then awaiting the output, as in Listing 17-21, which won’t compile yet.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-21/src/main.rs:stream}}

我们从一个数字数组开始,将其转换为迭代器,然后调用 map 将所有值翻倍。然后我们使用 trpl::stream_from_iter 函数将该迭代器转换为流。接下来,我们使用 while let 循环在该流中的项到达时对其进行遍历。

We start with an array of numbers, which we convert to an iterator and then call map on to double all the values. Then we convert the iterator into a stream using the trpl::stream_from_iter function. Next, we loop over the items in the stream as they arrive with the while let loop.

不幸的是,当我们尝试运行这段代码时,它无法编译,而是报告没有可用的 next 方法:

Unfortunately, when we try to run the code, it doesn’t compile but instead reports that there’s no next method available:

error[E0599]: no method named `next` found for struct `tokio_stream::iter::Iter` in the current scope
  --> src/main.rs:10:40
   |
10 |         while let Some(value) = stream.next().await {
   |                                        ^^^^
   |
   = help: items from traits can only be used if the trait is in scope
help: the following traits which provide `next` are implemented but not in scope; perhaps you want to import one of them
   |
1  + use crate::trpl::StreamExt;
   |
1  + use futures_util::stream::stream::StreamExt;
   |
1  + use std::iter::Iterator;
   |
1  + use std::str::pattern::Searcher;
   |
help: there is a method `try_next` with a similar name
   |
10 |         while let Some(value) = stream.try_next().await {
   |                                        ~~~~~~~~

(错误[E0599]:在当前作用域内,结构体 tokio_stream::iter::Iter 中找不到名为 next 的方法)

正如这份输出所解释的,编译器错误的原因是我们需要将正确的特征引入作用域,才能使用 next 方法。鉴于我们到目前为止的讨论,你可能会理所当然地认为那个特征是 Stream ,但它实际上是 StreamExt 。作为 extension 的缩写, Ext 是 Rust 社区中用一个特征扩展另一个特征的一种常见模式。

As this output explains, the reason for the compiler error is that we need the right trait in scope to be able to use the next method. Given our discussion so far, you might reasonably expect that trait to be Stream, but it’s actually StreamExt. Short for extension, Ext is a common pattern in the Rust community for extending one trait with another.

Stream 特征定义了一个有效地结合了 IteratorFuture 特征的底层接口。 StreamExtStream 之上提供了一组更高级别的 API,包括 next 方法以及类似于 Iterator 特征提供的其他工具方法。 StreamStreamExt 尚未成为 Rust 标准库的一部分,但大多数生态系统 crate 使用类似的定义。

The Stream trait defines a low-level interface that effectively combines the Iterator and Future traits. StreamExt supplies a higher-level set of APIs on top of Stream, including the next method as well as other utility methods similar to those provided by the Iterator trait. Stream and StreamExt are not yet part of Rust’s standard library, but most ecosystem crates use similar definitions.

解决编译器错误的方法是为 trpl::StreamExt 添加一个 use 语句,如示例 17-22 所示。

The fix to the compiler error is to add a use statement for trpl::StreamExt, as in Listing 17-22.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-22/src/main.rs:all}}
}

将所有这些部分拼凑在一起,这段代码就能按我们想要的方式工作了!而且,既然我们将 StreamExt 引入了作用域,我们就可以使用它的所有工具方法,就像使用迭代器一样。

With all those pieces put together, this code works the way we want! What’s more, now that we have StreamExt in scope, we can use all of its utility methods, just as with iterators.

深入了解 Async 相关 Traits (A Closer Look at the Traits for Async)


x-i18n: generated_at: “2026-03-01T14:48:35Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: c1539161fea534a89af45f1f47fad213f951a212bc7f5b41280a17394d8e0223 source_path: ch17-05-traits-for-async.md workflow: 16

深入了解异步相关的特征 (A Closer Look at the Traits for Async)

在本章中,我们以多种方式使用了 FutureStreamStreamExt 特征。然而,到目前为止,我们一直避免深入研究它们的工作原理或它们如何结合在一起的细节,这对于你日常的 Rust 工作来说通常是没问题的。但有时你会遇到一些需要更多地了解这些特征细节的情况,连同 Pin 类型和 Unpin 特征。在本节中,我们将进行足够的挖掘以在这些场景中提供帮助,而更深层次的研究仍留给其他文档。

Throughout the chapter, we’ve used the Future, Stream, and StreamExt traits in various ways. So far, though, we’ve avoided getting too far into the details of how they work or how they fit together, which is fine most of the time for your day-to-day Rust work. Sometimes, though, you’ll encounter situations where you’ll need to understand a few more of these traits’ details, along with the Pin type and the Unpin trait. In this section, we’ll dig in just enough to help in those scenarios, still leaving the really deep dive for other documentation.

Future 特征 (The Future Trait)

让我们首先仔细研究一下 Future 特征是如何工作的。以下是 Rust 对它的定义:

#![allow(unused)]
fn main() {
use std::pin::Pin;
use std::task::{Context, Poll};

pub trait Future {
    type Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
}

该特征定义包含了一堆新类型,还有一些我们以前没见过的语法,所以让我们逐一分析这个定义。

That trait definition includes a bunch of new types and also some syntax we haven’t seen before, so let’s walk through the definition piece by piece.

首先, Future 的关联类型 Output 说明了 future 解析后的结果。这类似于 Iterator 特征的 Item 关联类型。其次, Future 具有 poll 方法,它为其 self 参数接收一个特殊的 Pin 引用,以及一个对 Context 类型的可变引用,并返回一个 Poll<Self::Output> 。我们稍后会更多地讨论 PinContext 。现在,让我们关注该方法的返回值,即 Poll 类型:

First, Future’s associated type Output says what the future resolves to. This is analogous to the Item associated type for the Iterator trait. Second, Future has the poll method, which takes a special Pin reference for its self parameter and a mutable reference to a Context type, and returns a Poll<Self::Output>. We’ll talk more about Pin and Context in a moment. For now, let’s focus on what the method returns, the Poll type:

#![allow(unused)]
fn main() {
pub enum Poll<T> {
    Ready(T),
    Pending,
}
}

这个 Poll 类型类似于 Option 。它有一个带有值的变体 Ready(T) 和一个没有值的变体 Pending 。不过, Poll 的含义与 Option 截然不同! Pending 变体表示 future 仍有工作要做,因此调用者稍后需要再次检查。 Ready 变体表示 Future 已经完成了它的工作,并且 T 值可用了。

This Poll type is similar to an Option. It has one variant that has a value, Ready(T), and one that does not, Pending. Poll means something quite different from Option, though! The Pending variant indicates that the future still has work to do, so the caller will need to check again later. The Ready variant indicates that the Future has finished its work and the T value is available.

注意:很少需要直接调用 poll ,但如果你确实需要,请记住,对于大多数 future,调用者在 future 返回 Ready 后不应再次调用 poll 。许多 future 如果在就绪后再被轮询,将会引发恐慌。可以安全再次轮询的 future 会在其文档中明确说明。这类似于 Iterator::next 的行为。

Note: It’s rare to need to call poll directly, but if you do need to, keep in mind that with most futures, the caller should not call poll again after the future has returned Ready. Many futures will panic if polled again after becoming ready. Futures that are safe to poll again will say so explicitly in their documentation. This is similar to how Iterator::next behaves.

当你看到使用 await 的代码时,Rust 会在底层将其编译为调用 poll 的代码。如果你回顾示例 17-4,我们在其中打印了单个 URL 解析后的页面标题,Rust 会将其编译成类似(尽管不完全是)这样的代码:

When you see code that uses await, Rust compiles it under the hood to code that calls poll. If you look back at Listing 17-4, where we printed out the page title for a single URL once it resolved, Rust compiles it into something kind of (although not exactly) like this:

match page_title(url).poll() {
    Ready(page_title) => match page_title {
        Some(title) => println!("The title for {url} was {title}"),
        None => println!("{url} had no title"),
    }
    Pending => {
        // 但这里应该放什么呢?
    }
}

当 future 仍处于 Pending 状态时,我们该怎么办?我们需要某种方法重试,再重试,一直重试,直到 future 最终就绪。换句话说,我们需要一个循环:

What should we do when the future is still Pending? We need some way to try again, and again, and again, until the future is finally ready. In other words, we need a loop:

let mut page_title_fut = page_title(url);
loop {
    match page_title_fut.poll() {
        Ready(value) => match page_title {
            Some(title) => println!("The title for {url} was {title}"),
            None => println!("{url} had no title"),
        }
        Pending => {
            // 继续循环
        }
    }
}

然而,如果 Rust 将其编译成完全那样的代码,那么每一个 await 都会是阻塞的——这恰恰与我们的初衷相反!相反,Rust 确保循环可以将控制权交给某个东西,而那个东西可以暂停该 future 的工作去处理其他 future,并在稍后再次检查这个 future。正如我们所见,那个东西就是一个异步运行时,而这种调度和协调工作是它的主要职责之一。

If Rust compiled it to exactly that code, though, every await would be blocking—exactly the opposite of what we were going for! Instead, Rust ensures that the loop can hand off control to something that can pause work on this future to work on other futures and then check this one again later. As we’ve seen, that something is an async runtime, and this scheduling and coordination work is one of its main jobs.

“使用消息传递在两个任务之间发送数据”一节中,我们描述了在 rx.recv 上的等待。 recv 调用返回一个 future,等待该 future 即是对其进行轮询。我们注意到,运行时将暂停该 future,直到它就绪,结果为 Some(message) 或通道关闭时的 None 。随着我们对 Future 特征,特别是 Future::poll 的深入理解,我们可以看到它是如何工作的。当 future 返回 Poll::Pending 时,运行时知道它还没就绪。反之,当 poll 返回 Poll::Ready(Some(message))Poll::Ready(None) 时,运行时知道 future “已”就绪并推进它。

In the “Sending Data Between Two Tasks Using Message Passing” section, we described waiting on rx.recv. The recv call returns a future, and awaiting the future polls it. We noted that a runtime will pause the future until it’s ready with either Some(message) or None when the channel closes. With our deeper understanding of the Future trait, and specifically Future::poll, we can see how that works. The runtime knows the future isn’t ready when it returns Poll::Pending. Conversely, the runtime knows the future is ready and advances it when poll returns Poll::Ready(Some(message)) or Poll::Ready(None).

关于运行时如何做到这一点的确切细节超出了本书的范围,但关键是要看到 future 的基本机制:运行时对其负责的每个 future 进行“轮询 (polls)”,在 future 尚未就绪时将其放回休眠状态。

The exact details of how a runtime does that are beyond the scope of this book, but the key is to see the basic mechanics of futures: a runtime polls each future it is responsible for, putting the future back to sleep when it is not yet ready.

Pin 类型与 Unpin 特征 (The Pin Type and the Unpin Trait)

回到示例 17-13,我们使用 trpl::join! 宏来等待三个 future。然而,拥有一个包含一定数量 future(直到运行时才确定)的集合(如向量)是很常见的。让我们将示例 17-13 更改为示例 17-23 中的代码,将三个 future 放入一个向量并改为调用 trpl::join_all 函数,这段代码目前还无法编译。

Back in Listing 17-13, we used the trpl::join! macro to await three futures. However, it’s common to have a collection such as a vector containing some number futures that won’t be known until runtime. Let’s change Listing 17-13 to the code in Listing 17-23 that puts the three futures into a vector and calls the trpl::join_all function instead, which won’t compile yet.

{{#rustdoc_include ../listings/ch17-async-await/listing-17-23/src/main.rs:here}}

我们将每个 future 放在一个 Box 中,使它们成为“特征对象 (trait objects)”,就像我们在第 12 章的“从 run 返回错误”一节中所做的那样。(我们将在第 18 章详细介绍特征对象。)使用特征对象让我们能够将这些类型产生的每个匿名 future 视为相同的类型,因为它们都实现了 Future 特征。

We put each future within a Box to make them into trait objects, just as we did in the “Returning Errors from run” section in Chapter 12. (We’ll cover trait objects in detail in Chapter 18.) Using trait objects lets us treat each of the anonymous futures produced by these types as the same type, because all of them implement the Future trait.

这可能令人惊讶。毕竟,这些异步块都没有返回任何内容,所以每个异步块都产生一个 Future<Output = ()> 。请记住, Future 是一个特征,并且编译器为每个异步块创建一个唯一的枚举,即使它们具有相同的输出类型。就像你不能在 Vec 中放入两个不同的手写结构体一样,你也不能混合编译器生成的枚举。

This might be surprising. After all, none of the async blocks returns anything, so each one produces a Future<Output = ()>. Remember that Future is a trait, though, and that the compiler creates a unique enum for each async block, even when they have identical output types. Just as you can’t put two different handwritten structs in a Vec, you can’t mix compiler-generated enums.

然后我们将 future 集合传递给 trpl::join_all 函数并 await 结果。然而,这段代码无法编译;以下是错误消息的相关部分。

Then we pass the collection of futures to the trpl::join_all function and await the result. However, this doesn’t compile; here’s the relevant part of the error messages.

error[E0277]: `dyn Future<Output = ()>` cannot be unpinned
  --> src/main.rs:48:33
   |
48 |         trpl::join_all(futures).await;
   |                                 ^^^^^ the trait `Unpin` is not implemented for `dyn Future<Output = ()>`
   |
   = note: consider using the `pin!` macro
           consider using `Box::pin` if you need to access the pinned value outside of the current scope
   = note: required for `Box<dyn Future<Output = ()>>` to implement `Future`
note: required by a bound in `futures_util::future::join_all::JoinAll`
  --> file:///home/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/futures-util-0.3.30/src/future/join_all.rs:29:8
   |
27 | pub struct JoinAll<F>
   |            ------- required by a bound in this struct
28 | where
29 |     F: Future,
   |        ^^^^^^ required by this bound in `JoinAll`

此错误消息中的提示告诉我们,我们应该使用 pin! 宏来“固定 (pin)”这些值,这意味着将它们放入 Pin 类型中,以保证这些值在内存中不会被移动。错误消息显示需要固定是因为 dyn Future<Output = ()> 需要实现 Unpin 特征,而它目前还没有实现。

The note in this error message tells us that we should use the pin! macro to pin the values, which means putting them inside the Pin type that guarantees the values won’t be moved in memory. The error message says pinning is required because dyn Future<Output = ()> needs to implement the Unpin trait and it currently does not.

trpl::join_all 函数返回一个名为 JoinAll 的结构体。该结构体对类型 F 是泛型的,且 F 被约束为实现 Future 特征。直接使用 await 等待一个 future 会隐式地固定该 future。这就是为什么我们不需要在想要 await future 的每个地方都使用 pin!

The trpl::join_all function returns a struct called JoinAll. That struct is generic over a type F, which is constrained to implement the Future trait. Directly awaiting a future with await pins the future implicitly. That’s why we don’t need to use pin! everywhere we want to await futures.

然而,我们这里并不是直接等待一个 future。相反,我们通过将 future 集合传递给 join_all 函数来构造一个新的 future,即 JoinAll。 join_all 的签名要求集合中各项的类型都实现 Future 特征,而 Box<T> 仅在它包裹的 T 是实现了 Unpin 特征的 future 时才实现 Future

However, we’re not directly awaiting a future here. Instead, we construct a new future, JoinAll, by passing a collection of futures to the join_all function. The signature for join_all requires that the types of the items in the collection all implement the Future trait, and Box<T> implements Future only if the T it wraps is a future that implements the Unpin trait.

需要消化的东西真多!为了真正理解它,让我们进一步深入了解 Future 特征究竟是如何工作的,特别是围绕“固定 (pinning)”。再次查看 Future 特征的定义:

That’s a lot to absorb! To really understand it, let’s dive a little further into how the Future trait actually works, in particular around pinning. Look again at the definition of the Future trait:

#![allow(unused)]
fn main() {
use std::pin::Pin;
use std::task::{Context, Poll};

pub trait Future {
    type Output;

    // 所需方法
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
}

cx 参数及其 Context 类型是运行时在保持惰性的同时真正知道何时检查任何给定 future 的关键。同样,该过程如何工作的细节超出了本章的范围,通常只有在编写自定义 Future 实现时才需要考虑这一点。我们将重点放在 self 的类型上,因为这是我们第一次见到 self 带有类型标注的方法。对 self 的类型标注与对其他函数参数的类型标注类似,但有两个关键区别:

The cx parameter and its Context type are the key to how a runtime actually knows when to check any given future while still being lazy. Again, the details of how that works are beyond the scope of this chapter, and you generally only need to think about this when writing a custom Future implementation. We’ll focus instead on the type for self, as this is the first time we’ve seen a method where self has a type annotation. A type annotation for self works like type annotations for other function parameters but with two key differences:

  • 它告诉 Rust 调用该方法时 self 必须是什么类型。

  • 它不能是随便任何类型。它仅限于实现该方法的类型、该类型的引用或智能指针,或者是包裹了该类型引用的 Pin

  • It tells Rust what type self must be for the method to be called.

  • It can’t be just any type. It’s restricted to the type on which the method is implemented, a reference or smart pointer to that type, or a Pin wrapping a reference to that type.

我们将在第 18 章中看到更多关于此语法的内容。目前,只需知道如果我们想轮询一个 future 来检查它是 Pending 还是 Ready(Output) ,我们需要一个包裹了该类型的可变引用的 Pin

We’ll see more on this syntax in Chapter 18. For now, it’s enough to know that if we want to poll a future to check whether it is Pending or Ready(Output), we need a Pin-wrapped mutable reference to the type.

Pin 是对指针类类型(如 &&mutBoxRc )的包装。(从技术上讲, Pin 适用于实现了 DerefDerefMut 特征的类型,但这实际上等同于仅处理引用和智能指针。) Pin 本身不是指针,并且不像 RcArc 那样具有引用计数的行为;它纯粹是编译器用来强制执行指针使用约束的工具。

Pin is a wrapper for pointer-like types such as &, &mut, Box, and Rc. (Technically, Pin works with types that implement the Deref or DerefMut traits, but this is effectively equivalent to working only with references and smart pointers.) Pin is not a pointer itself and doesn’t have any behavior of its own like Rc and Arc do with reference counting; it’s purely a tool the compiler can use to enforce constraints on pointer usage.

回想一下 await 是根据对 poll 的调用实现的,这开始解释了我们之前看到的错误消息,但那是关于 Unpin 的,而不是 Pin 。那么 Pin 究竟与 Unpin 有什么关系,为什么 Future 需要 self 处于 Pin 类型中才能调用 poll 呢?

Recalling that await is implemented in terms of calls to poll starts to explain the error message we saw earlier, but that was in terms of Unpin, not Pin. So how exactly does Pin relate to Unpin, and why does Future need self to be in a Pin type to call poll?

请记住本章前面的内容:future 中一系列的等待点会被编译成一个状态机,并且编译器会确保该状态机遵循 Rust 关于安全性的所有常规规则,包括借用和所有权。为了做到这一点,Rust 会查看一个等待点与下一个等待点或异步块结束之间需要哪些数据。然后它在编译后的状态机中创建一个相应的变体。每个变体都获得了它所需的访问该源代码部分将使用的数据的权限,无论是通过获取该数据的所有权还是获取其可变或不可变引用。

Remember from earlier in this chapter that a series of await points in a future get compiled into a state machine, and the compiler makes sure that state machine follows all of Rust’s normal rules around safety, including borrowing and ownership. To make that work, Rust looks at what data is needed between one await point and either the next await point or the end of the async block. It then creates a corresponding variant in the compiled state machine. Each variant gets the access it needs to the data that will be used in that section of the source code, whether by taking ownership of that data or by getting a mutable or immutable reference to it.

到目前为止一切顺利:如果我们弄错了给定异步块中的所有权或引用,借用检查器会告诉我们。当我们想要移动与该块相对应的 future 时——比如将其移动到一个 Vec 中传递给 join_all ——事情就变得棘手了。

So far, so good: if we get anything wrong about the ownership or references in a given async block, the borrow checker will tell us. When we want to move around the future that corresponds to that block—like moving it into a Vec to pass to join_all—things get trickier.

当我们移动一个 future 时——无论是通过将其推入数据结构中作为迭代器与 join_all 一起使用,还是通过从函数返回它——这实际上意味着移动 Rust 为我们创建的状态机。与 Rust 中的大多数其他类型不同,Rust 为异步块创建的 future 最终可能会在其任何给定变体的字段中包含对自身的引用,如图 17-4 的简化插图所示。

When we move a future—whether by pushing it into a data structure to use as an iterator with join_all or by returning it from a function—that actually means moving the state machine Rust creates for us. And unlike most other types in Rust, the futures Rust creates for async blocks can end up with references to themselves in the fields of any given variant, as shown in the simplified illustration in Figure 17-4.

一个单列三行的表格代表一个 future fut1,它在前两行中具有数据值 0 和 1,并且有一个从第三行指向第二行的箭头,代表 future 内部的一个引用。
图 17-4:一个自引用数据类型

然而,默认情况下,任何具有自引用的对象移动起来都是不安全的,因为引用始终指向它们所引用内容的实际内存地址(见图 17-5)。如果你移动数据结构本身,那些内部引用将仍指向旧位置。然而,那个内存位置现在是无效的。一方面,当你对数据结构进行更改时,它的值将不会更新。另一方面——更重要的一点是——计算机现在可以自由地将该内存用于其他目的!你稍后可能会读到完全不相关的数据。

By default, though, any object that has a reference to itself is unsafe to move, because references always point to the actual memory address of whatever they refer to (see Figure 17-5). If you move the data structure itself, those internal references will be left pointing to the old location. However, that memory location is now invalid. For one thing, its value will not be updated when you make changes to the data structure. For another—more important—thing, the computer is now free to reuse that memory for other purposes! You could end up reading completely unrelated data later.

两个表格描绘了两个 future fut1 和 fut2,每个表格都有一列和三行,代表将一个 future 从 fut1 移动到 fut2 的结果。第一个 fut1 变灰了,每个索引中都有一个问号,代表未知内存。第二个 fut2 在第一行和第二行中有 0 和 1,并且有一个从它的第三行指回 fut1 第二行的箭头,代表一个指向 future 移动前在内存中旧位置的指针。
图 17-5:移动自引用数据类型的不安全结果

从理论上讲,Rust 编译器可以尝试在对象每次被移动时更新它的每一个引用,但这可能会增加大量的性能开销,特别是如果需要更新整个引用网络。如果我们能确保所讨论的数据结构“在内存中不移动”,我们就不用更新任何引用了。这正是 Rust 借用检查器的用途:在安全代码中,它会阻止你移动任何带有一个活动引用的项。

Theoretically, the Rust compiler could try to update every reference to an object whenever it gets moved, but that could add a lot of performance overhead, especially if a whole web of references needs updating. If we could instead make sure the data structure in question doesn’t move in memory, we wouldn’t have to update any references. This is exactly what Rust’s borrow checker is for: in safe code, it prevents you from moving any item with an active reference to it.

Pin 在此基础上为我们提供了我们需要的精确保证。当我们通过将指向某个值的指针包装在 Pin 中来“固定 (pin)”该值时,它就不再能移动。因此,如果你拥有 Pin<Box<SomeType>> ,你实际上固定的是 SomeType 值,而“不是” Box 指针。图 17-6 说明了这个过程。

Pin builds on that to give us the exact guarantee we need. When we pin a value by wrapping a pointer to that value in Pin, it can no longer move. Thus, if you have Pin<Box<SomeType>>, you actually pin the SomeType value, not the Box pointer. Figure 17-6 illustrates this process.

三个方框并排摆放。第一个标记为“Pin”,第二个标记为“b1”,第三个标记为“pinned”。在“pinned”中是一个标记为“fut”的表格,只有一列;它代表一个 future,其中有数据结构各部分的单元格。它的第一个单元格值为“0”,第二个单元格有一个从中出来的箭头,指向第四个也是最后一个单元格,该单元格中值为“1”,第三个单元格有虚线和省略号,表示数据结构可能还有其他部分。总的来说,“fut”表格代表一个自引用的 future。一个箭头从标记为“Pin”的方框出发,穿过标记为“b1”的方框,并在“pinned”方框内的“fut”表格处终止。
图 17-6:固定一个指向自引用 future 类型的 `Box`

实际上, Box 指针仍然可以自由移动。记住:我们关心的是确保最终被引用的数据保持在原位。如果指针移动了,但它指向的数据仍在同一个地方,如图 17-7 所示,那么就没有潜在问题。(作为一项独立练习,查看这些类型的文档以及 std::pin 模块,并尝试弄清楚你将如何使用包裹 BoxPin 来做到这一点。)关键是自引用类型本身不能移动,因为它仍然是被固定的。

In fact, the Box pointer can still move around freely. Remember: we care about making sure the data ultimately being referenced stays in place. If a pointer moves around, but the data it points to is in the same place, as in Figure 17-7, there’s no potential problem. (As an independent exercise, look at the docs for the types as well as the std::pin module and try to work out how you’d do this with a Pin wrapping a Box.) The key is that the self-referential type itself cannot move, because it is still pinned.

四个方框摆放在大致三列中,与前一个图表相同,只是第二列发生了变化。现在第二列中有两个方框,分别标记为“b1”和“b2”,“b1”变灰了,从“Pin”发出的箭头穿过“b2”而不是“b1”,表明指针已经从“b1”移动到了“b2”,但“pinned”中的数据没有移动。
图 17-7:移动指向自引用 future 类型的 `Box`

然而,大多数类型在移动时是完全安全的,即使它们恰好位于 Pin 指针之后。我们只需要在项具有内部引用时考虑固定。原始值(如数字和布尔值)是安全的,因为它们显然没有任何内部引用。你在 Rust 中通常使用的大多数类型也一样。例如,你可以放心地移动 Vec 。鉴于我们目前所见,如果你有一个 Pin<Vec<String>> ,你将不得不通过 Pin 提供的安全但有限制的 API 来执行所有操作,尽管在没有其他引用的情况下, Vec<String> 移动起来总是安全的。我们需要一种方法告诉编译器,在类似这样的情况下移动项是可以的——这就是 Unpin 发挥作用的地方。

However, most types are perfectly safe to move around, even if they happen to be behind a Pin pointer. We only need to think about pinning when items have internal references. Primitive values such as numbers and Booleans are safe because they obviously don’t have any internal references. Neither do most types you normally work with in Rust. You can move around a Vec, for example, without worrying. Given what we have seen so far, if you have a Pin<Vec<String>>, you’d have to do everything via the safe but restrictive APIs provided by Pin, even though a Vec<String> is always safe to move if there are no other references to it. We need a way to tell the compiler that it’s fine to move items around in cases like this—and that’s where Unpin comes into play.

Unpin 是一个标记特征,类似于我们在第 16 章中看到的 SendSync 特征,因此它本身没有功能。标记特征的存在只是为了告诉编译器在特定上下文中使用实现该特征的类型是安全的。 Unpin 通知编译器,给定类型“不需要”遵守任何关于所讨论的值是否可以安全移动的保证。

Unpin is a marker trait, similar to the Send and Sync traits we saw in Chapter 16, and thus has no functionality of its own. Marker traits exist only to tell the compiler it’s safe to use the type implementing a given trait in a particular context. Unpin informs the compiler that a given type does not need to uphold any guarantees about whether the value in question can be safely moved.

就像 SendSync 一样,对于所有编译器可以证明其安全的类型,编译器都会自动实现 Unpin 。一个特殊情况(同样类似于 SendSync )是“未”为某种类型实现 Unpin 的情况。其记法是 impl !Unpin for SomeType ,其中 SomeType 是一个在 Pin 中使用该类型的指针时“确实”需要遵守这些保证才能保持安全的类型名称。

Just as with Send and Sync, the compiler implements Unpin automatically for all types where it can prove it is safe. A special case, again similar to Send and Sync, is where Unpin is not implemented for a type. The notation for this is impl !Unpin for SomeType, where SomeType is the name of a type that does need to uphold those guarantees to be safe whenever a pointer to that type is used in a Pin.

换句话说,关于 PinUnpin 之间的关系,有两点需要记住。首先, Unpin 是“正常”情况,而 !Unpin 是特殊情况。其次,一个类型实现的是 Unpin 还是 !Unpin ,只有当你使用指向该类型的固定指针(如 Pin<&mut SomeType> )时才有意义。

In other words, there are two things to keep in mind about the relationship between Pin and Unpin. First, Unpin is the “normal” case, and !Unpin is the special case. Second, whether a type implements Unpin or !Unpin only matters when you’re using a pinned pointer to that type like Pin<&mut SomeType>.

具体来说,想一想 String :它具有长度和组成它的 Unicode 字符。我们可以将 String 包装在 Pin 中,如图 17-8 所示。然而, String 会自动实现 Unpin ,正如 Rust 中的大多数其他类型一样。

To make that concrete, think about a String: it has a length and the Unicode characters that make it up. We can wrap a String in Pin, as seen in Figure 17-8. However, String automatically implements Unpin, as do most other types in Rust.

左边是一个标记为“Pin”的方框,有一个箭头从它指向右边一个标记为“String”的方框。“String”方框包含数据 5usize(代表字符串长度),以及字母“h”、“e”、“l”、“l”和“o”(代表该 String 实例中存储的字符串“hello”的字符)。虚线矩形包围了“String”方框及其标签,但没有包围“Pin”方框。
图 17-8:固定一个 `String` ;虚线表示 `String` 实现了 `Unpin` 特征,因此它没有被固定

结果是,我们可以做一些如果 String 实现的是 !Unpin 则会非法的事情,例如在内存中的完全相同位置将一个字符串替换为另一个字符串,如图 17-9 所示。这并没有违反 Pin 合同,因为 String 没有使其在移动时变得不安全的内部引用。这正是为什么它实现的是 Unpin 而不是 !Unpin 的原因。

As a result, we can do things that would be illegal if String implemented !Unpin instead, such as replacing one string with another at the exact same location in memory as in Figure 17-9. This doesn’t violate the Pin contract, because String has no internal references that make it unsafe to move around. That is precisely why it implements Unpin rather than !Unpin.

来自前一个例子的相同“hello”字符串数据,现在标记为“s1”并变灰了。前一个例子中的“Pin”方框现在指向一个不同的 String 实例,该实例标记为“s2”,它是有效的,长度为 7usize,包含字符串“goodbye”的字符。s2 被虚线矩形包围,因为它也实现了 Unpin 特征。
图 17-9:在内存中用一个完全不同的 `String` 替换该 `String`

现在我们有足够的知识来理解示例 17-23 中那个 join_all 调用所报告的错误了。我们最初尝试将由异步块产生的 future 移动到 Vec<Box<dyn Future<Output = ()>>> 中,但正如我们所见,那些 future 可能具有内部引用,因此它们不会自动实现 Unpin 。一旦我们将它们固定,我们就可以将生成的 Pin 类型传递到 Vec 中,确信 future 中的底层数据将“不”被移动。示例 17-24 展示了如何通过在定义三个 future 的地方调用 pin! 宏并调整特征对象类型来修复代码。

Now we know enough to understand the errors reported for that join_all call from back in Listing 17-23. We originally tried to move the futures produced by async blocks into a Vec<Box<dyn Future<Output = ()>>>, but as we’ve seen, those futures may have internal references, so they don’t automatically implement Unpin. Once we pin them, we can pass the resulting Pin type into the Vec, confident that the underlying data in the futures will not be moved. Listing 17-24 shows how to fix the code by calling the pin! macro where each of the three futures are defined and adjusting the trait object type.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-24/src/main.rs:here}}
}

这个例子现在可以编译并运行了,我们可以动态地向向量添加或从中移除 future 并将它们全部联接。

This example now compiles and runs, and we could add or remove futures from the vector at runtime and join them all.

相对于日常的 Rust 代码, PinUnpin 主要在构建底层库或构建运行时本身时才显得重要。不过,现在当你在错误消息中看到这些特征时,你应该对如何修复代码有了更好的想法!

Pin and Unpin are mostly important for building lower-level libraries, or when you’re building a runtime itself, rather than for day-to-day Rust code. When you see these traits in error messages, though, now you’ll have a better idea of how to fix your code!

注意: PinUnpin 的这种组合使得在 Rust 中安全地实现一整类复杂的类型成为可能,否则这些类型由于自引用而会极具挑战。需要 Pin 的类型在当今的异步 Rust 中最常出现,但偶尔你也会在其他上下文中看到它们。

关于 PinUnpin 如何工作以及它们被要求遵守的规则的细节,在 std::pin 的 API 文档中得到了广泛的涵盖,所以如果你有兴趣了解更多,那是一个绝佳的起点。

如果你想更详细地了解底层工作原理,请参阅《Rust 异步编程》中的第 2 章第 4 章

Note: This combination of Pin and Unpin makes it possible to safely implement a whole class of complex types in Rust that would otherwise prove challenging because they’re self-referential. Types that require Pin show up most commonly in async Rust today, but every once in a while, you might see them in other contexts, too.

The specifics of how Pin and Unpin work, and the rules they’re required to uphold, are covered extensively in the API documentation for std::pin, so if you’re interested in learning more, that’s a great place to start.

If you want to understand how things work under the hood in even more detail, see Chapters 2 and 4 of Asynchronous Programming in Rust.

Stream 特征 (The Stream Trait)

The Stream Trait

现在你已经对 FuturePinUnpin 特征有了更深入的了解,我们可以将注意力转向 Stream 特征了。正如你在本章前面学到的,流类似于异步迭代器。然而,与 IteratorFuture 不同的是,截至撰写本文时, Stream 在标准库中还没有定义,但在整个生态系统中都有使用来自 futures crate 的一个非常通用的定义。

Now that you have a deeper grasp on the Future, Pin, and Unpin traits, we can turn our attention to the Stream trait. As you learned earlier in the chapter, streams are similar to asynchronous iterators. Unlike Iterator and Future, however, Stream has no definition in the standard library as of this writing, but there is a very common definition from the futures crate used throughout the ecosystem.

在研究 Stream 特征可能如何将它们融合在一起之前,让我们先回顾一下 IteratorFuture 特征的定义。从 Iterator 来看,我们有了序列的概念:它的 next 方法提供一个 Option<Self::Item> 。从 Future 来看,我们有了随时间就绪的概念:它的 poll 方法提供一个 Poll<Self::Output> 。为了代表随时间变得就绪的一系列项,我们定义了一个将这些特性结合在一起的 Stream 特征:

Let’s review the definitions of the Iterator and Future traits before looking at how a Stream trait might merge them together. From Iterator, we have the idea of a sequence: its next method provides an Option<Self::Item>. From Future, we have the idea of readiness over time: its poll method provides a Poll<Self::Output>. To represent a sequence of items that become ready over time, we define a Stream trait that puts those features together:

#![allow(unused)]
fn main() {
use std::pin::Pin;
use std::task::{Context, Poll};

trait Stream {
    type Item;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>
    ) -> Poll<Option<Self::Item>>;
}
}

Stream 特征为由该流产生的项类型定义了一个名为 Item 的关联类型。这类似于 Iterator ,可能有零到多个项,而不像 Future ,总是有单个 Output ,即使它是单元类型 ()

The Stream trait defines an associated type called Item for the type of the items produced by the stream. This is similar to Iterator, where there may be zero to many items, and unlike Future, where there is always a single Output, even if it’s the unit type ().

Stream 还定义了一个获取这些项的方法。我们称之为 poll_next ,以明确它以与 Future::poll 相同的方式进行轮询,并以与 Iterator::next 相同的方式产生一系列项。它的返回类型结合了 PollOption 。外部类型是 Poll ,因为它必须像 future 一样检查就绪状态。内部类型是 Option ,因为它需要像迭代器一样发出是否还有更多消息的信号。

Stream also defines a method to get those items. We call it poll_next, to make it clear that it polls in the same way Future::poll does and produces a sequence of items in the same way Iterator::next does. Its return type combines Poll with Option. The outer type is Poll, because it has to be checked for readiness, just as a future does. The inner type is Option, because it needs to signal whether there are more messages, just as an iterator does.

与此定义非常相似的东西很可能会最终成为 Rust 标准库的一部分。与此同时,它是大多数运行时工具包的一部分,因此你可以依赖它,接下来我们介绍的一切通常都适用!

Something very similar to this definition will likely end up as part of Rust’s standard library. In the meantime, it’s part of the toolkit of most runtimes, so you can rely on it, and everything we cover next should generally apply!

不过,在我们在“流:顺序排列的 Future”一节中看到的例子中,我们没有使用 poll_nextStream ,而是使用了 nextStreamExt 。当然,我们可以通过手写我们自己的 Stream 状态机直接根据 poll_next API 工作,就像我们可以通过 future 的 poll 方法直接与它们交互一样。然而,使用 await 会美观得多,而 StreamExt 特征提供了 next 方法,这样我们就可以做到这一点:

In the examples we saw in the “Streams: Futures in Sequence” section, though, we didn’t use poll_next or Stream, but instead used next and StreamExt. We could work directly in terms of the poll_next API by hand-writing our own Stream state machines, of course, just as we could work with futures directly via their poll method. Using await is much nicer, though, and the StreamExt trait supplies the next method so we can do just that:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/no-listing-stream-ext/src/lib.rs:here}}
}

注意:我们在本章前面使用的实际定义看起来与此略有不同,因为它支持尚不支持在特征中使用异步函数的 Rust 版本。因此,它看起来像这样:

fn next(&mut self) -> Next<'_, Self> where Self: Unpin;

那个 Next 类型是一个实现了 Futurestruct ,并允许我们通过 Next<'_, Self> 为对 self 的引用命名生命周期,以便 await 可以与该方法配合工作。

Note: The actual definition we used earlier in the chapter looks slightly different than this, because it supports versions of Rust that did not yet support using async functions in traits. As a result, it looks like this:

fn next(&mut self) -> Next<'_, Self> where Self: Unpin;

That Next type is a struct that implements Future and allows us to name the lifetime of the reference to self with Next<'_, Self>, so that await can work with this method.

StreamExt 特征也是所有可供流使用的有趣方法的归宿。 StreamExt 会为每个实现 Stream 的类型自动实现,但这些特征是分开定义的,以便社区能够迭代便利 API 而不影响基础特征。

The StreamExt trait is also the home of all the interesting methods available to use with streams. StreamExt is automatically implemented for every type that implements Stream, but these traits are defined separately to enable the community to iterate on convenience APIs without affecting the foundational trait.

trpl crate 中使用的 StreamExt 版本中,该特征不仅定义了 next 方法,还提供了一个正确处理调用 Stream::poll_next 细节的 next 默认实现。这意味着即使当你需要编写自己的流数据类型时,你“仅”需要实现 Stream ,然后任何使用你数据类型的人都可以自动使用 StreamExt 及其方法。

In the version of StreamExt used in the trpl crate, the trait not only defines the next method but also supplies a default implementation of next that correctly handles the details of calling Stream::poll_next. This means that even when you need to write your own streaming data type, you only have to implement Stream, and then anyone who uses your data type can use StreamExt and its methods with it automatically.

关于这些特征底层细节的内容我们就讲到这里。为了总结一下,让我们考虑一下 future(包括流)、任务和线程是如何配合在一起的!

That’s all we’re going to cover for the lower-level details on these traits. To wrap up, let’s consider how futures (including streams), tasks, and threads all fit together!

Futures、任务与线程 (Futures, Tasks, and Threads)


x-i18n: generated_at: “2026-03-01T14:48:54Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: e8c64d4048eb471389f65ba6cae78f56faf6017c2a733fb5ff9811bf9a01afd1 source_path: ch17-06-futures-tasks-threads.md workflow: 16

综合应用:Future、任务与线程 (Putting It All Together: Futures, Tasks, and Threads)

正如我们在第 16 章中看到的,线程提供了一种并发方法。我们在本章中看到了另一种方法:将异步与 future 和 stream 结合使用。如果你想知道什么时候该选择哪种方法,答案是:视情况而定!而且在许多情况下,选择不是线程“或”异步,而是线程“与”异步。

As we saw in Chapter 16, threads provide one approach to concurrency. We’ve seen another approach in this chapter: using async with futures and streams. If you’re wondering when to choose one method over the other, the answer is: it depends! And in many cases, the choice isn’t threads or async but rather threads and async.

许多操作系统提供基于线程的并发模型已经有几十年了,因此许多编程语言都支持它们。然而,这些模型并非没有权衡。在许多操作系统上,每个线程都会占用相当多的内存。只有在你的操作系统和硬件支持时,线程才是一个可选项。与主流桌面和移动计算机不同,一些嵌入式系统根本没有操作系统,因此它们也没有线程。

Many operating systems have supplied threading-based concurrency models for decades now, and many programming languages support them as a result. However, these models are not without their tradeoffs. On many operating systems, they use a fair bit of memory for each thread. Threads are also only an option when your operating system and hardware support them. Unlike mainstream desktop and mobile computers, some embedded systems don’t have an OS at all, so they also don’t have threads.

异步模型提供了一组不同的——并且最终是互补的——权衡。在异步模型中,并发操作不需要它们自己的线程。相反,它们可以在“任务 (tasks)”上运行,就像我们在流那一节中使用 trpl::spawn_task 从同步函数启动工作时那样。一个任务类似于一个线程,但它不是由操作系统管理的,而是由库级代码管理的:运行时。

The async model provides a different—and ultimately complementary—set of tradeoffs. In the async model, concurrent operations don’t require their own threads. Instead, they can run on tasks, as when we used trpl::spawn_task to kick off work from a synchronous function in the streams section. A task is similar to a thread, but instead of being managed by the operating system, it’s managed by library-level code: the runtime.

产生线程和产生任务的 API 如此相似是有原因的。线程充当一组同步操作的边界;并发可以在线程“之间”实现。任务充当一组“异步”操作的边界;并发既可以在任务“之间”实现,也可以在任务“之内”实现,因为任务可以在其主体中的 future 之间切换。最后,future 是 Rust 最细粒度的并发单元,每个 future 可能代表其他 future 的一棵树。运行时——特别是它的执行器——管理任务,而任务管理 future。在这一点上,任务类似于轻量级的、由运行时管理的线程,具有由运行时而非操作系统管理所带来的额外功能。

There’s a reason the APIs for spawning threads and spawning tasks are so similar. Threads act as a boundary for sets of synchronous operations; concurrency is possible between threads. Tasks act as a boundary for sets of asynchronous operations; concurrency is possible both between and within tasks, because a task can switch between futures in its body. Finally, futures are Rust’s most granular unit of concurrency, and each future may represent a tree of other futures. The runtime—specifically, its executor—manages tasks, and tasks manage futures. In that regard, tasks are similar to lightweight, runtime-managed threads with added capabilities that come from being managed by a runtime instead of by the operating system.

这并不意味着异步任务总是优于线程(或反之亦然)。线程并发在某些方面是比 async 并发更简单的编程模型。这既可以是优势也可以是弱点。线程在某种程度上是“发射后不管 (fire and forget)”的;它们没有 native 对应于 future 的东西,因此它们只是运行到完成而不会被中断,除非被操作系统本身中断。

This doesn’t mean that async tasks are always better than threads (or vice versa). Concurrency with threads is in some ways a simpler programming model than concurrency with async. That can be a strength or a weakness. Threads are somewhat “fire and forget”; they have no native equivalent to a future, so they simply run to completion without being interrupted except by the operating system itself.

事实证明,线程和任务通常能很好地配合工作,因为任务(至少在某些运行时中)可以在线程之间移动。事实上,在底层,我们一直使用的运行时——包括 spawn_blockingspawn_task 函数——默认就是多线程的!许多运行时使用一种称为“工作窃取 (work stealing)”的方法,根据线程当前的利用情况,在线程之间透明地移动任务,以提高系统的整体性能。这种方法实际上需要线程“与”任务,以及 future。

And it turns out that threads and tasks often work very well together, because tasks can (at least in some runtimes) be moved around between threads. In fact, under the hood, the runtime we’ve been using—including the spawn_blocking and spawn_task functions—is multithreaded by default! Many runtimes use an approach called work stealing to transparently move tasks around between threads, based on how the threads are currently being utilized, to improve the system’s overall performance. That approach actually requires threads and tasks, and therefore futures.

在考虑何时使用哪种方法时,请参考以下经验法则:

  • 如果工作是“高度可并行的”(即 CPU 密集型),例如处理一堆可以各部分分开处理的数据,线程是更好的选择。
  • 如果工作是“高度并发的”(即 I/O 密集型),例如处理来自一堆不同来源的消息,这些消息可能以不同的间隔或不同的速率到来,那么异步是更好的选择。

When thinking about which method to use when, consider these rules of thumb:

  • If the work is very parallelizable (that is, CPU-bound), such as processing a bunch of data where each part can be processed separately, threads are a better choice.
  • If the work is very concurrent (that is, I/O-bound), such as handling messages from a bunch of different sources that may come in at different intervals or different rates, async is a better choice.

如果你既需要并行又需要并发,你不必在线程和异步之间做出选择。你可以自由地将它们结合使用,让各自发挥所长。例如,示例 17-25 显示了现实世界 Rust 代码中这种混合方式的一个相当常见的例子。

And if you need both parallelism and concurrency, you don’t have to choose between threads and async. You can use them together freely, letting each play the part it’s best at. For example, Listing 17-25 shows a fairly common example of this kind of mix in real-world Rust code.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch17-async-await/listing-17-25/src/main.rs:all}}
}

我们首先创建一个异步通道,然后产生一个线程,使用 move 关键字获取该通道发送端的所有权。在该线程内,我们发送数字 1 到 10,每个数字之间休眠一秒。最后,我们运行一个通过异步块创建并传递给 trpl::block_on 的 future,就像我们在本章中一直做的那样。在那个 future 中,我们 await 那些消息,就像我们在见过的其他消息传递示例中那样。

We begin by creating an async channel, then spawning a thread that takes ownership of the sender side of the channel using the move keyword. Within the thread, we send the numbers 1 through 10, sleeping for a second between each. Finally, we run a future created with an async block passed to trpl::block_on just as we have throughout the chapter. In that future, we await those messages, just as in the other message-passing examples we have seen.

回到本章开头的场景,想象一下使用专用线程运行一组视频编码任务(因为视频编码是计算密集型的),但使用异步通道通知 UI 那些操作已完成。在现实世界的用例中,这种组合的例子数不胜数。

To return to the scenario we opened the chapter with, imagine running a set of video encoding tasks using a dedicated thread (because video encoding is compute-bound) but notifying the UI that those operations are done with an async channel. There are countless examples of these kinds of combinations in real-world use cases.

总结 (Summary)

这不是你在本书中最后一次看到并发。 第 21 章中的项目将会在比这里讨论的简单示例更实际的场景中应用这些概念,并更直接地比较使用线程与任务和 future 解决问题的方法。

This isn’t the last you’ll see of concurrency in this book. The project in Chapter 21 will apply these concepts in a more realistic situation than the simpler examples discussed here and compare problem-solving with threading versus tasks and futures more directly.

无论你选择这些方法中的哪一种,Rust 都会为你提供编写安全、快速、并发代码所需的工具——无论是对于高吞吐量的 Web 服务器还是嵌入式操作系统。

No matter which of these approaches you choose, Rust gives you the tools you need to write safe, fast, concurrent code—whether for a high-throughput web server or an embedded operating system.

接下来,我们将讨论随着你的 Rust 程序变大,对问题建模和构建解决方案的惯用方式。此外,我们还将讨论 Rust 的惯用法如何与你可能熟悉的面向对象编程惯用法相关联。

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.

面向对象编程特性 (Object Oriented Programming Features)


x-i18n: generated_at: “2026-03-01T14:49:32Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 422a0ab9c4e755eb30c3b057632d51cd76ee3b4983239bc215ae65e9a2d850c7 source_path: ch18-00-oop.md workflow: 16

面向对象编程特性 (Object-Oriented Programming Features)

Object-Oriented Programming Features

面向对象编程 (Object-oriented programming, OOP) 是一种为程序建模的方式。对象作为编程概念最早在 20 世纪 60 年代的 Simula 编程语言中引入。这些对象影响了艾伦·凯 (Alan Kay) 的编程架构,即对象之间相互传递消息。为了描述这种架构,他在 1967 年创造了“面向对象编程”一词。许多竞争性的定义描述了 OOP 是什么,根据其中一些定义,Rust 是面向对象的,但根据另一些定义,它则不是。在本章中,我们将探讨一些通常被认为是面向对象的特征,以及这些特征如何转化为地道的 Rust。然后,我们将向你展示如何在 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.

面向对象语言的特征 (Characteristics of Object-Oriented Languages)


x-i18n: generated_at: “2026-03-01T14:50:50Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 09efdf84fb2fd7197a221e8bdd8df24fb7b0a25468b2c84a01a9d71e537f6526 source_path: ch18-01-what-is-oo.md workflow: 16

面向对象语言的特征 (Characteristics of Object-Oriented Languages)

Characteristics of Object-Oriented Languages

编程社区对于一门语言必须具备哪些特性才能被视为面向对象并没有达成共识。Rust 受到了许多编程范式的影响,包括 OOP;例如,我们在第 13 章探讨了源自函数式编程的特性。可以说,OOP 语言共享某些共同特征——即对象、封装和继承。让我们来看看这些特征各自意味着什么,以及 Rust 是否支持它们。

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.

对象包含数据和行为 (Objects Contain Data and Behavior)

Objects Contain Data and Behavior

由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides 合著的《设计模式:可复用面向对象软件的基础》(Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994) 一书(俗称“四人帮” (The Gang of Four) 之书)是面向对象设计模式的目录。它这样定义 OOP:

The book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1994), colloquially referred to as The Gang of Four book, is a catalog of object-oriented design patterns. It defines OOP in this way:

面向对象的程序是由对象组成的。对象包装了数据以及操作这些数据的过程。这些过程通常被称为方法操作

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.

根据这个定义,Rust 是面向对象的:结构体和枚举拥有数据,而 impl 块在结构体和枚举上提供方法。尽管带有方法的结构体和枚举不被“称为”对象,但根据“四人帮”对对象的定义,它们提供了相同的功能。

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.

隐藏实现细节的封装 (Encapsulation That Hides Implementation Details)

Encapsulation That Hides Implementation Details

通常与 OOP 相关的另一个方面是“封装 (encapsulation)”的想法,这意味着对象的实现细节对于使用该对象的代码是不可访问的。因此,与对象交互的唯一方式是通过其公有 API;使用对象的代码不应该能够直接触及对象的内部并更改数据或行为。这使得程序员能够更改和重构对象的内部,而无需更改使用对象的代码。

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.

我们在第 7 章讨论了如何控制封装:我们可以使用 pub 关键字来决定代码中哪些模块、类型、函数和方法应该是公有的,而默认情况下其他一切都是私有的。例如,我们可以定义一个结构体 AveragedCollection ,它有一个包含 i32 值向量的字段。该结构体还可以有一个包含向量中值平均值的字段,这意味着平均值不必在任何人需要时按需计算。换句话说, AveragedCollection 将为我们缓存计算出的平均值。示例 18-1 包含了 AveragedCollection 结构体的定义。

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 18-1 has the definition of the AveragedCollection struct.

{{#rustdoc_include ../listings/ch18-oop/listing-18-01/src/lib.rs}}

该结构体被标记为 pub 以便其他代码可以使用它,但结构体内部的字段仍然是私有的。在这种情况下这很重要,因为我们想确保每当向列表中添加或移除值时,平均值也会更新。我们通过在结构体上实现 addremoveaverage 方法来实现这一点,如示例 18-2 所示。

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 18-2.

{{#rustdoc_include ../listings/ch18-oop/listing-18-02/src/lib.rs:here}}

公有方法 addremoveaverage 是访问或修改 AveragedCollection 实例中数据的唯一方式。当使用 add 方法向 list 添加项或使用 remove 方法移除项时,两者的实现都会调用私有的 update_average 方法,该方法负责同时更新 average 字段。

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.

我们将 listaverage 字段保留为私有,这样外部代码就无法直接向 list 字段添加或从中移除项;否则,当 list 改变时, average 字段可能会变得不同步。 average 方法返回 average 字段中的值,允许外部代码读取平均值但不能修改它。

We leave the list and average fields private so that 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.

由于我们已经封装了结构体 AveragedCollection 的实现细节,我们可以很容易地在将来更改诸如数据结构之类的方面。例如,我们可以为 list 字段使用 HashSet<i32> 而不是 Vec<i32> 。只要 addremoveaverage 公有方法的签名保持不变,使用 AveragedCollection 的代码就不需要更改。如果我们改为将 list 设为公有,情况就不一定如此了: HashSet<i32>Vec<i32> 具有不同的添加和移除项的方法,因此如果外部代码直接修改 list ,它可能就不得不进行更改。

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 stayed the same, code using AveragedCollection wouldn’t need to change. 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.

如果封装是语言被视为面向对象的一个必要方面,那么 Rust 满足了这一要求。对不同部分的代码选择使用 pub 与否实现了对实现细节的封装。

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.

继承作为类型系统和代码共享 (Inheritance as a Type System and as Code Sharing)

Inheritance as a Type System and as Code Sharing

“继承 (Inheritance)”是一种机制,通过它,一个对象可以继承另一个对象定义中的元素,从而获得父对象的数据和行为,而无需你再次定义它们。

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.

如果一门语言必须具有继承才能被称为面向对象,那么 Rust 就不属于此类语言。如果不使用宏,就无法定义一个继承父结构体字段和方法实现的结构体。

If a language must have inheritance to be object oriented, then Rust is not such a language. 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 代码中,你可以通过特征方法的默认实现以有限的方式做到这一点,正如你在示例 10-14 中看到的,当时我们在 Summary 特征上添加了 summarize 方法的默认实现。任何实现 Summary 特征的类型都无需更多代码即可使用 summarize 方法。这类似于父类有一个方法的实现,而继承的子类也具有该方法的实现。当实现 Summary 特征时,我们还可以覆盖 summarize 方法的默认实现,这类似于子类覆盖从父类继承的方法实现。

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.

使用继承的另一个原因与类型系统有关:使子类型能够在与父类型相同的地方使用。这也被称为“多态 (polymorphism)”,这意味着如果多个对象共享某些特征,你可以在运行时相互替换它们。

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)

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 则使用泛型来对不同的可能类型进行抽象,并使用特征约束来对这些类型必须提供的内容施加限制。这有时被称为“有限制的参数多态 (bounded parametric polymorphism)”。

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 通过不提供继承而选择了一组不同的权衡。继承往往面临共享超出必要代码的风险。子类不应该总是共享其父类的所有特征,但使用继承时却会如此。这可能使程序的设计缺乏灵活性。它还引入了在子类上调用没有意义或由于方法不适用于子类而导致错误的可能性。此外,有些语言只允许“单继承”(意味着子类只能继承自一个类),进一步限制了程序设计的灵活性。

Rust has chosen a different set of trade-offs by not offering inheritance. Inheritance is 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.

出于这些原因,Rust 采取了不同的方法,使用特征对象而不是继承来实现运行时的多态性。让我们来看看特征对象是如何工作的。

For these reasons, Rust takes the different approach of using trait objects instead of inheritance to achieve polymorphism at runtime. Let’s look at how trait objects work.

使用 Trait 对象为共享行为抽象 (Using Trait Objects to Abstract over Shared Behavior)


x-i18n: generated_at: “2026-03-01T14:51:59Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: be159095c388554e8bdd41791f73f86cb4ecad440ee78f6226bbf556bff865ba source_path: ch18-02-trait-objects.md workflow: 16

使用特征对象实现不同类型间的抽象行为

Using Trait Objects to Abstract over Shared Behavior

在第 8 章中,我们提到向量的一个局限是它们只能存储单一类型的元素。我们在示例 8-9 中创建了一个变通方法,定义了一个 SpreadsheetCell 枚举,它具有持有整数、浮点数和文本的变体。这意味着我们可以在每个单元格中存储不同类型的数据,并且仍然拥有一个代表一单元格行的向量。当我们的互换项是一组我们在编译代码时已知的固定类型时,这是一个非常好的解决方案。

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.

然而,有时我们希望我们的库用户能够扩展在特定情况下有效的类型集合。为了展示如何实现这一点,我们将创建一个图形用户界面 (GUI) 工具的示例,它遍历一个项列表,对每个项调用 draw 方法将其绘制到屏幕上——这是 GUI 工具的一种常用技术。我们将创建一个名为 gui 的库 crate,它包含一个 GUI 库的结构。这个 crate 可能包含一些供人们使用的类型,如 ButtonTextField 。此外, gui 的用户会想要创建他们自己可以被绘制的类型:例如,一个程序员可能会添加一个 Image ,而另一个可能会添加一个 SelectBox

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 方法。它不需要确切知道调用 draw 方法时会发生什么,只需要知道该值将具有可供我们调用的该方法。

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.

要在具有继承性质的语言中做到这一点,我们可能会定义一个名为 Component 的类,它上面有一个名为 draw 的方法。其他类,如 ButtonImageSelectBox ,将继承自 Component 从而继承 draw 方法。它们可以各自覆盖 draw 方法以定义其自定义行为,但框架可以将所有类型都视为 Component 实例并对它们调用 draw 。但因为 Rust 没有继承,我们需要另一种方式来构建 gui 库,以允许用户创建与库兼容的新类型。

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 create new types compatible with the library.

为共同行为定义特征

Defining a Trait for Common Behavior

为了实现我们希望 gui 具有的行为,我们将定义一个名为 Draw 的特征,它将有一个名为 draw 的方法。然后,我们可以定义一个接收特征对象的向量。一个“特征对象 (trait object)”同时指向一个实现了我们指定特征的类型的实例,以及一个在运行时用于查找该类型上特征方法的表。我们通过指定某种类型的指针(如引用或 Box<T> 智能指针),然后是 dyn 关键字,再指定相关的特征,来创建一个特征对象。(我们将在第 20 章的“动态大小类型与 Sized 特征”中讨论特征对象必须使用指针的原因。)我们可以使用特征对象来替代泛型或具体类型。在任何我们使用特征对象的地方,Rust 的类型系统都会在编译时确保在该上下文中使用的任何值都将实现该特征对象的特征。因此,我们不需要在编译时知道所有可能的类型。

To implement the behavior that 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 “Dynamically Sized Types and the Sized Trait” in Chapter 20.) 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.

我们已经提到过,在 Rust 中,我们避免将结构体和枚举称为“对象”,以便将它们与其他语言的对象区分开来。在结构体或枚举中,结构体字段中的数据和 impl 块中的行为是分开的,而在其他语言中,将数据和行为结合在一起的一个概念通常被标记为对象。特征对象与显式对象不同之处在于,我们不能向特征对象添加数据。特征对象不像其他语言中的对象那样具有普遍的用途:它们的特定目的是允许对共同行为进行抽象。

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. Trait objects differ from objects in other languages 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.

示例 18-3 展示了如何定义一个名为 Draw 的特征,其中包含一个名为 draw 的方法。

Listing 18-3 shows how to define a trait named Draw with one method named draw.

{{#rustdoc_include ../listings/ch18-oop/listing-18-03/src/lib.rs}}

这种语法对于我们第 10 章中关于如何定义特征的讨论来说应该是熟悉的。接下来是一些新语法:示例 18-4 定义了一个名为 Screen 的结构体,它持有一个名为 components 的向量。这个向量的类型是 Box<dyn Draw> ,这是一个特征对象;它是 Box 内任何实现了 Draw 特征的类型的替身。

This syntax should look familiar from our discussions on how to define traits in Chapter 10. Next comes some new syntax: Listing 18-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.

{{#rustdoc_include ../listings/ch18-oop/listing-18-04/src/lib.rs:here}}

Screen 结构体上,我们将定义一个名为 run 的方法,该方法将对其每个 components 调用 draw 方法,如示例 18-5 所示。

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 18-5.

{{#rustdoc_include ../listings/ch18-oop/listing-18-05/src/lib.rs:here}}

这与定义使用带有特征约束的泛型类型参数的结构体不同。泛型类型参数一次只能替换为一个具体类型,而特征对象允许在运行时填充多个具体类型。例如,我们可以使用泛型类型和特征约束来定义 Screen 结构体,如示例 18-6 所示。

This works differently from defining a struct that uses a generic type parameter with trait bounds. A generic type parameter can be substituted with only 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 18-6.

{{#rustdoc_include ../listings/ch18-oop/listing-18-06/src/lib.rs:here}}

这限制了我们使用的 Screen 实例只能拥有一组全部为 Button 类型或全部为 TextField 类型的组件列表。如果你永远只会有同质集合,那么使用泛型和特征约束是更佳的选择,因为定义将在编译时被单态化以使用具体类型。

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 实例可以持有包含 Box<Button> 以及 Box<TextField>Vec<T> 。让我们来看看这是如何工作的,然后我们将讨论运行时的性能影响。

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.

实现特征

Implementing the Trait

现在我们将添加一些实现 Draw 特征的类型。我们将提供 Button 类型。同样,实际实现一个 GUI 库超出了本书的范围,所以 draw 方法体内不会有任何有用的实现。为了想象实现可能的样子, Button 结构体可能具有 widthheightlabel 字段,如示例 18-7 所示。

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 18-7.

{{#rustdoc_include ../listings/ch18-oop/listing-18-07/src/lib.rs:here}}

Button 上的 widthheightlabel 字段将与其他组件上的字段不同;例如, TextField 类型可能具有这些相同的字段外加一个 placeholder 字段。我们要绘制在屏幕上的每个类型都将实现 Draw 特征,但会在 draw 方法中使用不同的代码来定义如何绘制该特定类型,就像这里的 Button 一样(如前所述,没有实际的 GUI 代码)。例如, Button 类型可能有一个额外的 impl 块,包含与用户点击按钮时发生的事情相关的方法。这类方法并不适用于像 TextField 这样的类型。

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.

如果使用我们库的人决定实现一个具有 widthheightoptions 字段的 SelectBox 结构体,他们也会在 SelectBox 类型上实现 Draw 特征,如示例 18-8 所示。

If someone using our library decides to implement a SelectBox struct that has width, height, and options fields, they would implement the Draw trait on the SelectBox type as well, as shown in Listing 18-8.

{{#rustdoc_include ../listings/ch18-oop/listing-18-08/src/main.rs:here}}

我们库的用户现在可以编写他们的 main 函数来创建一个 Screen 实例。对于这个 Screen 实例,他们可以通过将 SelectBoxButton 分别放入 Box<T> 中使其成为特征对象来添加它们。然后他们可以在 Screen 实例上调用 run 方法,这将对每个组件调用 draw 。示例 18-9 展示了这一实现。

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 18-9 shows this implementation.

{{#rustdoc_include ../listings/ch18-oop/listing-18-09/src/main.rs:here}}

当我们编写库时,我们并不知道有人会添加 SelectBox 类型,但我们的 Screen 实现能够操作新类型并绘制它,因为 SelectBox 实现了 Draw 特征,这意味着它实现了 draw 方法。

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.

这种概念——即只关注一个值响应的消息,而不是该值的具体类型——类似于动态类型语言中的“鸭子类型 (duck typing)”概念:如果它走起来像鸭子,叫起来像鸭子,那么它就一定是鸭子!在示例 18-5 中 Screen 上的 run 实现中, run 不需要知道每个组件的具体类型。它不检查一个组件是 Button 还是 SelectBox 的实例,它只是调用该组件上的 draw 方法。通过将 Box<dyn Draw> 指定为 components 向量中值的类型,我们已经定义了 Screen 需要的是我们可以调用 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 18-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.

使用特征对象和 Rust 的类型系统来编写类似于使用鸭子类型的代码的优势在于,我们永远不需要在运行时检查一个值是否实现了特定的方法,或者担心如果我们调用了一个值没有实现的方法但我们还是调用了它而出现错误。如果值没有实现特征对象所需的特征,Rust 就不会编译我们的代码。

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.

例如,示例 18-10 展示了如果我们尝试创建一个以 String 为组件的 Screen 会发生什么。

{{#rustdoc_include ../listings/ch18-oop/listing-18-10/src/main.rs}}

我们将得到这个错误,因为 String 没有实现 Draw 特征:

We’ll get this error because String doesn’t implement the Draw trait:

{{#include ../listings/ch18-oop/listing-18-10/output.txt}}

这个错误让我们知道,我们要么是向 Screen 传递了我们本不打算传递的东西,因此应该传递不同的类型,要么是我们应该在 String 上实现 Draw ,以便 Screen 能够对其调用 draw

This error lets us know that either we’re passing something to Screen that 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.

执行动态分派 (Performing Dynamic Dispatch)

Performing Dynamic Dispatch

回想第 10 章“使用泛型的代码的性能”中关于编译器对泛型执行的单态化过程的讨论:编译器为我们用来替换泛型类型参数的每个具体类型生成函数和方法的非泛型实现。由单态化产生的代码正在执行“静态分派 (static dispatch)”,即编译器在编译时就知道你调用的是什么方法。这与“动态分派 (dynamic dispatch)”相对,动态分派是指编译器在编译时无法判断你调用的是哪个方法。在动态分派的情况下,编译器发出的代码将在运行时知道调用哪个方法。

Recall in “Performance of Code Using Generics” in Chapter 10 our discussion on the monomorphization process performed on generics by the compiler: 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 know which method to call.

当我们使用特征对象时,Rust 必须使用动态分派。编译器并不知道所有可能与使用特征对象的代码一起使用的类型,因此它不知道该调用在哪个类型上实现的哪个方法。相反,在运行时,Rust 使用特征对象内部的指针来确定调用哪个方法。这种查找会产生静态分派中不会发生的运行时成本。动态分派还会阻止编译器选择内联方法代码,这反过来又阻止了一些优化,并且 Rust 关于在哪里可以使用和不能使用动态分派有一些规则,称为“dyn 安全性 (dyn compatibility)”。这些规则超出了本次讨论的范围,但你可以在 参考手册中阅读更多相关内容。然而,我们在示例 18-5 中编写的代码以及在示例 18-9 中能够支持的代码确实获得了额外的灵活性,所以这是一个需要考虑的权衡。

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, and Rust has some rules about where you can and cannot use dynamic dispatch, called dyn compatibility. Those rules are beyond the scope of this discussion, but you can read more about them in the reference. However, we did get extra flexibility in the code that we wrote in Listing 18-5 and were able to support in Listing 18-9, so it’s a trade-off to consider.

实现面向对象设计模式 (Implementing an Object-Oriented Design Pattern)


x-i18n: generated_at: “2026-03-01T14:53:38Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 2f87e2bda9a748c973642b0c7f9ded2ac0467059a708aecabe7bd11e08eb305a source_path: ch18-03-oo-design-patterns.md workflow: 16

实现面向对象的设计模式 (Implementing an Object-Oriented Design Pattern)

Implementing an Object-Oriented Design Pattern

“状态模式 (state pattern)”是一种面向对象的设计模式。该模式的要点是,我们定义一个值内部可以拥有的一组状态。状态由一组“状态对象 (state objects)”表示,并且值的行为根据其状态而改变。我们将通过一个博客文章结构体的例子来演示,该结构体有一个字段来持有其状态,状态将是“草稿 (draft)”、“审核中 (review)”或“已发布 (published)”状态集中的一个状态对象。

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.”

状态对象共享功能:当然,在 Rust 中,我们使用结构体和特征而不是对象和继承。每个状态对象负责其自身的行为,并管理何时应转变为另一种状态。持有状态对象的值对状态的不同行为或何时在状态之间切换一无所知。

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.

使用状态模式的优势在于,当程序的业务需求发生变化时,我们不需要更改持有状态的值的代码或使用该值的代码。我们只需要更新其中一个状态对象内部的代码来更改其规则,或者添加更多的状态对象。

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.

首先,我们将以一种更传统的面向对象方式实现状态模式。然后,我们将使用一种在 Rust 中更自然的方法。让我们开始逐步使用状态模式实现博客文章的工作流。

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 implement a blog post workflow using the state pattern.

最终的功能将如下所示:

  1. 一篇博客文章从空白草稿开始。
  2. 草稿完成后,请求对文章进行审核。
  3. 文章获批后,即被发布。
  4. 只有已发布的博客文章才会返回要打印的内容,这样未获批的文章就不会被意外发布。

The final functionality will look like this:

  1. A blog post starts as an empty draft.
  2. When the draft is done, a review of the post is requested.
  3. When the post is approved, it gets published.
  4. Only published blog posts return content to print so that 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.

尝试传统的面向对象风格 (Attempting Traditional Object-Oriented Style)

Attempting Traditional Object-Oriented Style

解决同一个问题有无数种构建代码的方式,每种方式都有不同的权衡。本节的实现更多的是一种传统的面向对象风格,这在 Rust 中是可以写出来的,但没有利用 Rust 的一些优势。稍后,我们将演示另一种解决方案,它仍然使用面向对象的设计模式,但其结构对于具有面向对象经验的程序员来说可能不那么熟悉。我们将比较这两种解决方案,以体验以不同于其他语言的方式设计 Rust 代码的权衡。

There are infinite ways to structure code to solve the same problem, each with different trade-offs. This section’s implementation is more of a traditional object-oriented style, which is possible to write in Rust, but doesn’t take advantage of some of Rust’s strengths. Later, we’ll demonstrate a different solution that still uses the object-oriented design pattern but is structured in a way that might look less familiar to programmers with object-oriented experience. We’ll compare the two solutions to experience the trade-offs of designing Rust code differently than code in other languages.

示例 18-11 以代码形式展示了这种工作流:这是我们将要在名为 blog 的库 crate 中实现的 API 的示例用法。这目前还无法编译,因为我们还没有实现 blog crate。

Listing 11-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.

{{#rustdoc_include ../listings/ch18-oop/listing-18-11/src/main.rs:all}}

我们希望允许用户通过 Post::new 创建一个新的博客文章草稿。我们希望允许向博客文章添加文本。如果我们尝试在获批之前立即获取文章内容,我们不应该得到任何文本,因为文章仍处于草稿状态。为了演示目的,我们在代码中添加了 assert_eq! 。对此的一个极佳的单元测试是断言博客文章草稿从 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.

接下来,我们希望能够请求对文章进行审核,并且我们希望在等待审核期间 content 仍返回一个空字符串。当文章获得批准后,它应该被发布,这意味着在调用 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.

请注意,我们与之交互的 crate 中的唯一类型是 Post 类型。该类型将使用状态模式,并持有一个值,该值将是代表文章可能处于的三种状态(草稿、审核中或已发布)之一的状态对象。从一个状态切换到另一个状态将在 Post 类型内部进行管理。状态会响应库用户在 Post 实例上调用的方法而改变,但用户不必直接管理状态改变。此外,用户不会在状态上犯错,例如在审核之前发布文章。

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, 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, such as publishing a post before it’s reviewed.

定义 Post 并创建新实例 (Defining Post and Creating a New Instance)

让我们开始库的实现!我们知道我们需要一个持有某些内容的公共 Post 结构体,所以我们将从结构体的定义和用于创建 Post 实例的关联公共 new 函数开始,如示例 18-12 所示。我们还将创建一个私有的 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 18-12. We’ll also make a private State trait that will define the behavior that all state objects for a Post must have.

然后, Post 将在私有字段 state 中持有 Option<T> 内部的一个 Box<dyn State> 特征对象,以此持有状态对象。稍后你就会明白为什么 Option<T> 是必要的。

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.

{{#rustdoc_include ../listings/ch18-oop/listing-18-12/src/lib.rs}}

State 特征定义了不同文章状态共享的行为。状态对象是 DraftPendingReviewPublished ,它们都将实现 State 特征。目前,该特征没有任何方法,我们将从仅定义 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.

当我们创建一个新的 Post 时,我们将其 state 字段设置为一个持有 BoxSome 值。这个 Box 指向 Draft 结构体的一个新实例。这确保了每当我们创建一个新的 Post 实例时,它都将以草稿开始。因为 Poststate 字段是私有的,所以没有办法以任何其他状态创建一个 Post !在 Post::new 函数中,我们将 content 字段设置为一个新的空 String

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 that 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.

存储文章内容的文本 (Storing the Text of the Post Content)

我们在示例 18-11 中看到,我们希望能够调用一个名为 add_text 的方法并向其传递一个 &str ,该字符串随后被添加为博客文章的文本内容。我们将其实现为方法,而不是将 content 字段暴露为 pub ,这样以后我们就可以实现一个方法来控制如何读取 content 字段的数据。 add_text 方法非常简单,所以让我们在 impl Post 块中添加示例 18-13 的实现。

We saw in Listing 18-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 18-13 to the impl Post block.

{{#rustdoc_include ../listings/ch18-oop/listing-18-13/src/lib.rs:here}}

add_text 方法接收一个对 self 的可变引用,因为我们正在更改调用 add_textPost 实例。然后我们对 content 中的 String 调用 push_str ,并将 text 参数传递给它以添加到已保存的 content 中。此行为不依赖于文章所处的状态,因此它不是状态模式的一部分。 add_text 方法根本不与 state 字段交互,但它是我们想要支持的行为的一部分。

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.

确保草稿文章的内容为空 (Ensuring That the Content of a Draft Post Is Empty)

即使在调用了 add_text 并在文章中添加了一些内容之后,我们仍然希望 content 方法返回一个空字符串切片,因为文章仍处于草稿状态,如示例 18-11 中的第一个 assert_eq! 所示。目前,让我们用能满足这一要求的最简单方式来实现 content 方法:始终返回一个空字符串切片。稍后一旦我们实现了更改文章状态以便它可以发布的功能,我们就会更改此方法。到目前为止,文章只能处于草稿状态,所以文章内容应始终为空。示例 18-14 展示了这个占位符实现。

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 by the first assert_eq! in Listing 18-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 that it can be published. So far, posts can only be in the draft state, so the post content should always be empty. Listing 18-14 shows this placeholder implementation.

{{#rustdoc_include ../listings/ch18-oop/listing-18-14/src/lib.rs:here}}

有了这个新增的 content 方法,示例 18-11 中直到第一个 assert_eq! 的所有内容都能按预期工作了。

With this added content method, everything in Listing 18-11 through the first assert_eq! works as intended.

请求审核,这会改变文章状态 (Requesting a Review, Which Changes the Post’s State)

接下来,我们需要添加请求审核文章的功能,这应该将其状态从 Draft 更改为 PendingReview 。示例 18-15 显示了这段代码。

Next, we need to add functionality to request a review of a post, which should change its state from Draft to PendingReview. Listing 18-15 shows this code.

{{#rustdoc_include ../listings/ch18-oop/listing-18-15/src/lib.rs:here}}

我们给 Post 提供一个名为 request_review 的公共方法,它将接收一个对 self 的可变引用。然后,我们在 Post 的当前状态上调用一个内部的 request_review 方法,而这第二个 request_review 方法消耗当前状态并返回一个新状态。

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.

我们将 request_review 方法添加到 State 特征中;现在所有实现该特征的类型都需要实现 request_review 方法。请注意,该方法的第一个参数不是 self&self&mut self ,而是 self: Box<Self> 。这种语法意味着该方法仅在对持有该类型的 Box 调用时才有效。这种语法获取了 Box<Self> 的所有权,使旧状态失效,以便 Post 的状态值可以转换为新状态。

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 that the state value of the Post can transform into a new state.

为了消耗旧状态, request_review 方法需要获得状态值的所有权。这就是 Poststate 字段中的 Option 发挥作用的地方:我们调用 take 方法将 Some 值从 state 字段中取出,并在其位置留下一个 None ,因为 Rust 不允许我们在结构体中留有未填充的字段。这让我们可以将状态值移出 Post 而不是借用它。然后,我们将文章的 state 值设置为该操作的结果。

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.

我们需要暂时将 state 设置为 None ,而不是直接用类似 self.state = self.state.request_review(); 的代码来设置它,以便获得状态值的所有权。这确保了 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 that Post can’t use the old state value after we’ve transformed it into a new state.

Draft 上的 request_review 方法返回一个新的、装箱的 PendingReview 结构体实例,该结构体代表文章正在等待审核的状态。 PendingReview 结构体也实现了 request_review 方法,但不执行任何转换。相反,它返回自身,因为当我们对已经处于 PendingReview 状态的文章请求审核时,它应该保持在 PendingReview 状态。

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.

现在我们可以开始看到状态模式的优势了: Post 上的 request_review 方法无论其 state 值是什么都是相同的。每个状态负责其自身的规则。

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 上的 content 方法不变,仍然返回一个空字符串切片。我们现在可以拥有处于 PendingReview 状态以及 Draft 状态的 Post ,但我们希望在 PendingReview 状态下具有相同的行为。示例 18-11 现在可以运行到第二个 assert_eq! 调用了!

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 18-11 now works up to the second assert_eq! call!

添加 approve 以改变 content 的行为 (Adding approve to Change content’s Behavior)

approve 方法将类似于 request_review 方法:它将 state 设置为当前状态认为在批准该状态时应具有的值,如示例 18-16 所示。

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 18-16.

{{#rustdoc_include ../listings/ch18-oop/listing-18-16/src/lib.rs:here}}

我们将 approve 方法添加到 State 特征中,并添加一个新的实现 State 的结构体,即 Published 状态。

We add the approve method to the State trait and add a new struct that implements State, the Published state.

类似于 PendingReview 上的 request_review 的工作方式,如果我们对 Draft 调用 approve 方法,它将没有任何效果,因为 approve 将返回 self 。当我们在 PendingReview 上调用 approve 时,它返回一个新的、装箱的 Published 结构体实例。 Published 结构体实现了 State 特征,对于 request_review 方法和 approve 方法,它都返回自身,因为在这些情况下文章应该保持在 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.

现在我们需要更新 Post 上的 content 方法。我们希望从 content 返回的值取决于 Post 的当前状态,所以我们将让 Post 委托给定义在其 state 上的 content 方法,如示例 18-17 所示。

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 18-17.

{{#rustdoc_include ../listings/ch18-oop/listing-18-17/src/lib.rs:here}}

因为目标是将所有这些规则保持在实现 State 的结构体内部,所以我们在 state 中的值上调用一个 content 方法,并传递文章实例(即 self )作为参数。然后,我们返回在使用 state 值上的 content 方法后返回的值。

Because the goal is to keep all of 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.

我们在 Option 上调用 as_ref 方法,因为我们需要对 Option 内部值的引用,而不是值的所有权。因为 state 是一个 Option<Box<dyn State>> ,当我们调用 as_ref 时,会返回一个 Option<&Box<dyn State>> 。如果我们不调用 as_ref ,我们将得到一个错误,因为我们不能将 state 移出函数参数中借用的 &self

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.

然后我们调用 unwrap 方法,我们知道它永远不会引发恐慌,因为我们知道 Post 上的方法确保了当这些方法完成时 state 始终包含一个 Some 值。这是我们在第 9 章“当你拥有比编译器更多信息时”部分讨论过的情况之一,即虽然编译器无法理解这一点,但我们知道 None 值是不可能出现的。

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 “When 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.

此时,当我们在 &Box<dyn State> 上调用 content 时,解引用强制转换将在 &Box 上生效,以便最终对实现 State 特征的类型调用 content 方法。这意味着我们需要将 content 添加到 State 特征定义中,并在此放置根据我们所处的状态返回什么内容的逻辑,如示例 18-18 所示。

At this point, when we call content on the &Box<dyn State>, deref coercion will take effect on the & and the Box so that 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 18-18.

{{#rustdoc_include ../listings/ch18-oop/listing-18-18/src/lib.rs:here}}

我们为 content 方法添加了一个返回空字符串切片的默认实现。这意味着我们不需要在 DraftPendingReview 结构体上实现 contentPublished 结构体将覆盖 content 方法并返回 post.content 中的值。虽然方便,但让 State 上的 content 方法确定 Post 的内容,模糊了 State 的职责和 Post 的职责之间的界限。

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. While convenient, having the content method on State determine the content of the Post is blurring the lines between the responsibility of State and the responsibility of Post.

请注意,正如我们在第 10 章中讨论的那样,我们需要在该方法上标注生命周期。我们将对 post 的引用作为参数,并返回对该 post 一部分的引用,因此返回引用的生命周期与 post 参数的生命周期相关联。

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.

大功告成——示例 18-11 的所有内容现在都可以运行了!我们已经根据博客文章工作流的规则实现了状态模式。与规则相关的逻辑存在于状态对象中,而不是散布在整个 Post 中。

And we’re done—all of Listing 18-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.

为什么不用枚举?

Why Not An Enum?

你可能一直在想,为什么我们不使用带有不同可能文章状态作为变体的枚举呢。这当然是一个可能的解决方案;试一试并比较最终结果,看看你更喜欢哪种!使用枚举的一个缺点是,每个检查枚举值的地方都需要一个 match 表达式或类似结构来处理每个可能的变体。这可能比这种特征对象解决方案更具重复性。

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 that 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.

对状态模式的评价 (Evaluating the State Pattern)

Evaluating the State Pattern

我们已经展示了 Rust 能够实现面向对象的状态模式,以封装文章在每个状态下应具有的不同种类的行为。 Post 上的方法对各种行为一无所知。由于我们组织代码的方式,我们要想知道已发布的文章表现出的不同方式,只需要看一个地方: Published 结构体上 State 特征的实现。

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. Because of 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.

如果我们要创建一个不使用状态模式的替代实现,我们可能会在 Post 的方法中甚至在检查文章状态并据此改变行为的 main 代码中使用 match 表达式。那将意味着我们必须查看多个地方才能了解文章处于已发布状态的所有影响。

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.

使用状态模式, Post 的方法和我们使用 Post 的地方不需要 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 in one location.

使用状态模式的实现很容易扩展以添加更多功能。为了看到维护使用状态模式的代码的简单性,请尝试以下几个建议:

  • 添加一个 reject 方法,将文章的状态从 PendingReview 变回 Draft
  • 要求两次调用 approve 才能将状态更改为 Published
  • 仅允许用户在文章处于 Draft 状态时添加文本内容。提示:让状态对象负责内容可能发生的变化,但不负责修改 Post

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 from PendingReview back to Draft.
  • Require two calls to approve before the state can be changed to 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 the Post.

状态模式的一个缺点是,因为状态实现了状态之间的转换,某些状态之间是相互耦合的。如果我们向 PendingReviewPublished 之间添加另一个状态,例如 Scheduled ,我们就必须更改 PendingReview 中的代码以改为转换到 Scheduled 。如果 PendingReview 不需要随着新状态的增加而改变,工作量就会减少,但那意味着需要切换到另一种设计模式。

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.

另一个缺点是我们重复了一些逻辑。为了消除一些重复,我们可能会尝试在 State 特征上为返回 selfrequest_reviewapprove 方法制作默认实现。然而,这行不通:当使用 State 作为特征对象时,特征并不知道具体的 self 到底是什么,因此返回类型在编译时是未知的。(这是前面提到的 dyn 安全性规则之一。)

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 wouldn’t work: When using State as a trait object, the trait doesn’t know what the concrete self will be exactly, so the return type isn’t known at compile time. (This is one of the dyn compatibility rules mentioned earlier.)

其他的重复包括 Postrequest_reviewapprove 方法的类似实现。这两个方法都对 Poststate 字段使用 Option::take ,如果 stateSome ,它们就委托给包裹值的相同方法的实现,并将 state 字段的新值设置为结果。如果我们 Post 上有很多遵循这种模式的方法,我们可能会考虑定义一个宏来消除重复(见第 20 章“宏”部分)。

Other duplication includes the similar implementations of the request_review and approve methods on Post. Both methods use Option::take with the state field of Post, and if state is Some, they delegate to the wrapped value’s implementation of the same method 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 20).

通过完全按照为面向对象语言定义的方式来实现状态模式,我们并没有充分利用 Rust 的优势。让我们看看可以对 blog crate 做的一些更改,这些更改可以将无效的状态和转换变成编译时错误。

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.

将状态和行为编码为类型 (Encoding States and Behavior as Types)

我们将向你展示如何重新思考状态模式以获得一组不同的权衡。与其完全封装状态和转换使得外部代码对它们一无所知,我们将把状态编码到不同的类型中。因此,Rust 的类型检查系统将通过发出编译器错误来防止在仅允许已发布文章的地方尝试使用草稿文章。

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 that 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.

让我们考虑示例 18-11 中 main 的第一部分:

{{#rustdoc_include ../listings/ch18-oop/listing-18-11/src/main.rs:here}}

我们仍然支持使用 Post::new 创建草稿状态下的新文章,以及向文章内容添加文本的能力。但我们不再在草稿文章上提供一个返回空字符串的 content 方法,我们将使其根本不具有 content 方法。这样,如果我们尝试获取草稿文章的内容,我们将得到一个告诉我们方法不存在的编译器错误。结果是,我们将不可能在生产环境中意外显示草稿文章内容,因为那段代码根本无法通过编译。示例 18-19 展示了 Post 结构体和 DraftPost 结构体的定义,以及各自的方法。

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 that 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 18-19 shows the definition of a Post struct and a DraftPost struct, as well as methods on each.

{{#rustdoc_include ../listings/ch18-oop/listing-18-19/src/lib.rs}}

PostDraftPost 结构体都有一个存储博客文章文本的私有 content 字段。这些结构体不再具有 state 字段,因为我们将状态的编码移动到了结构体的类型中。 Post 结构体将代表已发布的文章,它有一个返回 contentcontent 方法。

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::new 函数,但它不再返回 Post 实例,而是返回一个 DraftPost 实例。因为 content 是私有的,且没有任何返回 Post 的函数,所以现在不可能创建一个 Post 实例。

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.

DraftPost 结构体有一个 add_text 方法,所以我们可以像以前一样向 content 添加文本,但请注意 DraftPost 没有定义 content 方法!所以现在程序确保所有文章都以草稿文章开始,并且草稿文章的内容无法用于显示。任何尝试绕过这些约束的行为都会导致编译器错误。

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 that 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.

那么,我们如何获得一篇已发布的文章呢?我们想强制执行这样一条规则:草稿文章必须经过审核和批准才能发布。处于等待审核状态的文章仍不应显示任何内容。让我们通过添加另一个结构体 PendingReviewPost ,在 DraftPost 上定义返回 PendingReviewPostrequest_review 方法,以及在 PendingReviewPost 上定义返回 Postapprove 方法来实现这些约束,如示例 18-20 所示。

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 18-20.

{{#rustdoc_include ../listings/ch18-oop/listing-18-20/src/lib.rs:here}}

request_reviewapprove 方法获取 self 的所有权,从而消耗 DraftPostPendingReviewPost 实例,并将它们分别转换为 PendingReviewPost 和已发布的 Post 。这样,在我们调用了 request_review 之后,就不会再有残留的 DraftPost 实例,以此类推。 PendingReviewPost 结构体上没有定义 content 方法,因此尝试读取其内容会导致编译器错误,就像 DraftPost 一样。因为获得定义了 content 方法的已发布 Post 实例的唯一方法是对 PendingReviewPost 调用 approve 方法,而获得 PendingReviewPost 的唯一方法是对 DraftPost 调用 request_review 方法,所以我们现在已经将博客文章工作流编码到了类型系统中。

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.

但我们也必须对 main 进行一些小改动。 request_reviewapprove 方法返回新实例,而不是修改它们被调用的结构体,所以我们需要添加更多的 let post = 遮蔽赋值来保存返回的实例。我们也不再需要(也无法拥有)关于草稿和待审核文章内容为空字符串的断言:我们再也无法编译尝试使用这些状态下文章内容的代码了。更新后的 main 代码如示例 18-21 所示。

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 18-21.

{{#rustdoc_include ../listings/ch18-oop/listing-18-21/src/main.rs}}

我们需要对 main 进行重新分配 post 的更改,这意味着此实现不再完全遵循面向对象的状态模式:状态之间的转换不再完全封装在 Post 实现内部。然而,我们的收获是,由于类型系统和在编译时发生的类型检查,无效状态现在是不可能的了!这确保了某些 bug,例如显示未发布文章的内容,将在它们进入生产环境之前就被发现。

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.

尝试在本节开始时建议的针对 blog crate 的任务(如示例 18-21 之后所示),看看你对这个版本的代码设计有何看法。请注意,在这个设计中,有些任务可能已经完成了。

Try the tasks suggested at the start of this section on the blog crate as it is after Listing 18-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.

我们已经看到,尽管 Rust 能够实现面向对象的设计模式,但在 Rust 中也可以使用其他模式,例如将状态编码到类型系统中。这些模式具有不同的权衡。虽然你可能非常熟悉面向对象的模式,但重新思考问题以利用 Rust 的特性可以提供诸如在编译时防止某些 bug 之类的好处。由于某些特性(如所有权)是面向对象语言所不具备的,面向对象模式在 Rust 中并不总是最佳解决方案。

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.

总结 (Summary)

无论你在读完本章后是否认为 Rust 是一门面向对象的语言,你现在都知道了可以使用特征对象在 Rust 中获得一些面向对象的特性。动态分派可以给你的代码提供一些灵活性,以换取一点运行时性能。你可以利用这种灵活性来实现面向对象模式,从而有助于代码的可维护性。Rust 还有其他特性,如所有权,是面向对象语言所不具备的。面向对象模式并不总是利用 Rust 优势的最佳方式,但它是一个可用的选项。

Regardless of whether 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 it is an available option.

接下来,我们将研究“模式 (patterns)”,这是 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!

模式与匹配 (Patterns and Matching)


x-i18n: generated_at: “2026-03-01T14:53:45Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 6fcb23c2cc53ff1a4ea10ae3ba914a75678fa6b3cfc56645b22b1893b4fabb6d source_path: ch19-00-patterns.md workflow: 16

模式与匹配 (Patterns and Matching)

Patterns and Matching

模式是 Rust 中一种特殊的语法,用于匹配复杂或简单类型的结构。将模式与 match 表达式和其他结构结合使用,可以让你更好地控制程序的执行流。一个模式由以下内容的某种组合组成:

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:

  • 字面量 (Literals)
  • 解构的数组、枚举、结构体或元组 (Destructured arrays, enums, structs, or tuples)
  • 变量 (Variables)
  • 通配符 (Wildcards)
  • 占位符 (Placeholders)

模式的一些例子包括 x(a, 3)Some(Color::Red) 。在模式有效的上下文中,这些组件描述了数据的形状。然后我们的程序将值与模式进行匹配,以确定它是否具有正确形状的数据来继续运行特定的代码片段。

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.

要使用模式,我们将其与某个值进行比较。如果模式与该值匹配,我们就在代码中使用该值的部分。回想一下第 6 章中使用了模式的 match 表达式,例如硬币分拣机的例子。如果值符合模式的形状,我们就可以使用命名的部分。如果不符合,与该模式关联的代码将不会运行。

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.

本章是关于模式相关所有内容的参考。我们将涵盖使用模式的有效位置、可反驳模式与不可反驳模式之间的区别,以及你可能会看到的各种不同种类的模式语法。到本章结束时,你将知道如何使用模式以清晰的方式表达许多概念。

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)


x-i18n: generated_at: “2026-03-01T14:54:56Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 6d7fcf955b94ce6424d13e912688b6ba4536fb9c2cb7c5d08b8384f44d090921 source_path: ch19-01-all-the-places-for-patterns.md workflow: 16

模式可以使用的所有地方 (All the Places Patterns Can Be Used)

模式在 Rust 的许多地方都会出现,你其实一直在大量使用它们,只是没意识到而已!本节讨论所有模式有效的地方。

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.

match 分支 (match Arms)

正如第 6 章中所讨论的,我们在 match 表达式的分支中使用模式。正式地, match 表达式被定义为关键字 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:

match VALUE {
    PATTERN => EXPRESSION,
    PATTERN => EXPRESSION,
    PATTERN => EXPRESSION,
}

例如,这里是示例 6-5 中的 match 表达式,它匹配变量 x 中的 Option<i32> 值:

For example, here’s the match expression from Listing 6-5 that matches on an Option<i32> value in the variable x:

match x {
    None => None,
    Some(i) => Some(i + 1),
}

这个 match 表达式中的模式是每个箭头左侧的 NoneSome(i)

The patterns in this match expression are the None and Some(i) to the left of each arrow.

match 表达式的一个要求是它们必须是穷尽的,即 match 表达式中值的所有可能性都必须考虑到。确保覆盖了每种可能性的一种方法是在最后一个分支中使用一个通配模式:例如,一个匹配任何值的变量名永远不会失败,从而覆盖了所有剩余的情况。

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 that you’ve covered every possibility is to have a catch-all pattern for the last arm: For example, a variable name matching any value can never fail and thus covers every remaining case.

特殊的模式 _ 会匹配任何内容,但它从不绑定到变量,因此它经常用于最后一个 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 “Ignoring Values in a Pattern” later in this chapter.

let 语句 (let Statements)

在本章之前,我们只明确讨论了在 matchif let 中使用模式,但实际上,我们也在其他地方使用了模式,包括在 let 语句中。例如,考虑这个直接使用 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:

#![allow(unused)]
fn main() {
let x = 5;
}

每当你像这样使用 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 PATTERN = EXPRESSION;

在像 let x = 5; 这样模式位置为变量名的语句中,变量名只是一种特别简单的模式形式。Rust 将表达式与模式进行比较,并分配它找到的任何名称。所以,在 let x = 5; 的例子中, x 是一个模式,意思是“将这里匹配到的内容绑定到变量 x ”。因为名称 x 是整个模式,所以这个模式实际上意味着“无论值是什么,都将其绑定到变量 x ”。

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 的模式匹配方面,请考虑示例 19-1,它使用 let 的模式来解构一个元组。

To see the pattern-matching aspect of let more clearly, consider Listing 19-1, which uses a pattern with let to destructure a tuple.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-01/src/main.rs:here}}
}

在这里,我们将一个元组与一个模式进行匹配。Rust 将值 (1, 2, 3) 与模式 (x, y, z) 进行比较,发现该值与模式匹配——也就是说,它发现两者的元素数量相同——因此 Rust 将 1 绑定到 x2 绑定到 y3 绑定到 z 。你可以将这个元组模式看作是在其内部嵌套了三个单独的变量模式。

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—that is, it sees that the number of elements is the same in both—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.

如果模式中的元素数量与元组中的元素数量不匹配,则整体类型将不匹配,我们将得到编译器错误。例如,示例 19-2 显示了尝试将一个具有三个元素的元组解构为两个变量的情况,这是行不通的。

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 19-2 shows an attempt to destructure a tuple with three elements into two variables, which won’t work.

{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-02/src/main.rs:here}}

尝试编译这段代码会导致如下类型错误:

Attempting to compile this code results in this type error:

{{#include ../listings/ch19-patterns-and-matching/listing-19-02/output.txt}}

要修复此错误,我们可以使用 _.. 来忽略元组中的一个或多个值,如你将在“忽略模式中的值”一节中看到的那样。如果问题是模式中的变量太多,解决方案是通过移除变量使类型匹配,从而使变量数量等于元组中的元素数量。

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 that the number of variables equals the number of elements in the tuple.

条件 if let 表达式 (Conditional if let Expressions)

在第 6 章中,我们讨论了如何使用 if let 表达式,主要是作为编写仅匹配一种情况的 match 的简写方式。可选地, if let 可以有一个对应的 else ,其中包含在 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.

示例 19-3 显示了混合匹配 if letelse ifelse if let 表达式也是可能的。这样做比只能表达一个值与模式进行比较的 match 表达式更具灵活性。此外,Rust 不要求一系列 if letelse ifelse if let 分支中的条件彼此相关。

Listing 19-3 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, and else if let arms relate to each other.

示例 19-3 中的代码根据对多个条件的一系列检查来确定背景颜色。在这个例子中,我们创建了具有硬编码值的变量,实际程序可能会从用户输入中接收这些值。

The code in Listing 19-3 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-03/src/main.rs}}
}

如果用户指定了喜欢的颜色,则使用该颜色作为背景。如果没有指定喜欢的颜色且今天是星期二,则背景颜色为绿色。否则,如果用户以字符串形式指定了他们的年龄,且我们可以成功将其解析为数字,则颜色根据数字的值为紫色或橙色。如果这些条件都不适用,背景颜色为蓝色。

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.

这种条件结构让我们能支持复杂的需求。根据我们这里的硬编码值,本示例将打印 Using purple as the background color

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.

你可以看到 if let 也可以像 match 分支那样引入遮蔽现有变量的新变量:行 if let Ok(age) = age 引入了一个包含 Ok 变体内的新 age 变量,遮蔽了现有的 age 变量。这意味着我们需要将 if age > 30 条件放在该代码块内:我们不能将这两个条件合并为 if let Ok(age) = age && age > 30 。我们要与 30 比较的新 age 直到以花括号开头的新作用域开始时才有效。

You can see that if let can also introduce new variables that shadow existing variables in the same way that match arms can: The line if let Ok(age) = age introduces a new age variable that contains the value inside the Ok variant, shadowing the existing age variable. 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 new age we want to compare to 30 isn’t valid until the new scope starts with the curly bracket.

使用 if let 表达式的缺点是编译器不会检查穷尽性,而 match 表达式会检查。如果我们省略了最后的 else 块,从而漏掉了某些情况,编译器将不会提醒我们可能存在的逻辑 bug。

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.

while let 条件循环 (while let Conditional Loops)

while let 条件循环在结构上与 if let 类似,它允许 while 循环只要模式继续匹配就运行。在示例 19-4 中,我们展示了一个 while let 循环,它等待在线程间发送的消息,但在这种情况下检查的是 Result 而非 Option

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 19-4, we show a while let loop that waits on messages sent between threads, but in this case checking a Result instead of an Option.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-04/src/main.rs:here}}
}

本例打印 12 ,然后是 3recv 方法从通道的接收端取出第一条消息,并返回一个 Ok(value) 。当我们最初在第 16 章看到 recv 时,我们要么直接解包错误,要么使用 for 循环将其作为迭代器进行交互。如示例 19-4 所示,我们也可以使用 while let ,因为只要发送端存在, recv 方法在每次消息到达时都会返回一个 Ok ,而一旦发送端断开连接,就会产生一个 Err

This example prints 1, 2, and then 3. The recv method takes the first message out of the receiver side of the channel and returns an Ok(value). When we first saw recv back in Chapter 16, we unwrapped the error directly, or we interacted with it as an iterator using a for loop. As Listing 19-4 shows, though, we can also use while let, because the recv method returns an Ok each time a message arrives, as long as the sender exists, and then produces an Err once the sender side disconnects.

for 循环 (for Loops)

for 循环中,直接跟在关键字 for 后面的值就是一个模式。例如,在 for x in y 中, x 就是模式。示例 19-5 演示了如何在 for 循环中使用模式来解构一个元组,作为 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 19-5 demonstrates how to use a pattern in a for loop to destructure, or break apart, a tuple as part of the for loop.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-05/src/main.rs:here}}
}

示例 19-5 中的代码将打印以下内容:

The code in Listing 19-5 will print the following:

{{#include ../listings/ch19-patterns-and-matching/listing-19-05/output.txt}}

我们使用 enumerate 方法适配一个迭代器,使其产生一个值以及该值的索引,并放入一个元组中。产生的第一个值是元组 (0, 'a') 。当此值与模式 (index, value) 匹配时,index 将是 0 ,value 将是 'a' ,从而打印出输出的第一行。

We adapt an iterator using the enumerate method so that 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.

函数参数 (Function Parameters)

函数参数也可以是模式。示例 19-6 中的代码声明了一个名为 foo 的函数,它接收一个 i32 类型的名为 x 的参数,现在看起来应该很熟悉了。

Function parameters can also be patterns. The code in Listing 19-6, which declares a function named foo that takes one parameter named x of type i32, should by now look familiar.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-06/src/main.rs:here}}
}

x 部分就是一个模式!就像我们对 let 所做的那样,我们可以在函数的参数中将一个元组与模式进行匹配。示例 19-7 在将元组传递给函数时拆分了其中的值。

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 19-7 splits the values in a tuple as we pass it to a function.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-07/src/main.rs}}
}

这段代码打印 Current location: (3, 5) 。值 &(3, 5) 与模式 &(x, y) 匹配,所以 x 是值 3y 是值 5

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.

我们也可以在闭包参数列表中以与函数参数列表相同的方式使用模式,因为闭包类似于函数,正如在第 13 章中讨论的那样。

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.

到目前为止,你已经看到了几种使用模式的方式,但模式在我们可以使用它们的每个地方的工作方式并不相同。在某些地方,模式必须是不可反驳的;而在其他情况下,它们可以是可反驳的。我们接下来将讨论这两个概念。

At this point, you’ve seen several ways to use 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)


x-i18n: generated_at: “2026-03-01T14:55:44Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 59e75e2673e39e4006f1f07b5c12a9df5b5c0d33f6f2d0515f756ca6c134a01c source_path: ch19-02-refutability.md workflow: 16

可反驳性:模式是否可能匹配失败 (Refutability: Whether a Pattern Might Fail to Match)

Refutability: Whether a Pattern Might Fail to Match

模式有两种形式:可反驳的 (refutable) 和不可反驳的 (irrefutable)。对于任何可能的传入值都能匹配成功的模式是“不可反驳的”。例如 let x = 5; 语句中的 x ,因为 x 可以匹配任何内容,因此不会匹配失败。对于某些可能的值会匹配失败的模式是“可反驳的”。例如 if let Some(x) = a_value 表达式中的 Some(x) ,因为如果 a_value 变量中的值是 None 而不是 Some ,模式 Some(x) 就不会匹配成功。

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 语句和 for 循环只能接受不可反驳的模式,因为当值不匹配时,程序无法执行任何有意义的操作。 if letwhile let 表达式以及 let...else 语句接受可反驳和不可反驳的模式,但编译器会针对不可反驳的模式发出警告,因为根据定义,它们是旨在处理可能失败的情况的:条件结构的意义在于它能够根据成功或失败执行不同的操作。

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 and the let...else statement 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.

通常情况下,你不需要担心可反驳模式和不可反驳模式之间的区别;然而,你确实需要熟悉可反驳性的概念,以便在错误消息中看到它时做出响应。在这些情况下,你需要根据代码的预期行为,更改模式或使用该模式的结构。

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 that 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.

让我们看一个例子,看看当我们尝试在 Rust 要求不可反驳模式的地方使用可反驳模式时会发生什么,反之亦然。示例 19-8 显示了一个 let 语句,但对于模式,我们指定了 Some(x) ,这是一个可反驳模式。正如你所料,这段代码将无法编译。

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 19-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.

{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-08/src/main.rs:here}}

如果 some_option_valueNone 值,它将无法匹配模式 Some(x) ,这意味着该模式是可反驳的。然而, let 语句只能接受不可反驳的模式,因为对于 None 值,代码无法执行任何有效的操作。在编译时,Rust 会抱怨我们尝试在需要不可反驳模式的地方使用了可反驳模式:

If some_option_value were 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:

{{#include ../listings/ch19-patterns-and-matching/listing-19-08/output.txt}}

因为我们没有(也无法!)用 Some(x) 模式覆盖每一个有效值,所以 Rust 理所当然地产生了一个编译器错误。

Because we didn’t cover (and couldn’t cover!) every valid value with the pattern Some(x), Rust rightfully produces a compiler error.

如果我们有一个需要不可反驳模式的地方却使用了可反驳模式,我们可以通过更改使用该模式的代码来修复它:不使用 let ,我们可以使用 let...else 。然后,如果模式不匹配,花括号中的代码将处理该值。示例 19-9 展示了如何修复示例 19-8 中的代码。

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 let...else. Then, if the pattern doesn’t match, the code in the curly brackets will handle the value. Listing 19-9 shows how to fix the code in Listing 19-8.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-09/src/main.rs:here}}
}

我们给了代码一个出路!这段代码是完全有效的,尽管这意味着我们不能在不接收警告的情况下使用不可反驳模式。如果我们给 let...else 一个总是会匹配的模式,例如 x ,如示例 19-10 所示,编译器会给出警告。

We’ve given the code an out! This code is perfectly valid, although it means we cannot use an irrefutable pattern without receiving a warning. If we give let...else a pattern that will always match, such as x, as shown in Listing 19-10, the compiler will give a warning.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-10/src/main.rs:here}}
}

Rust 抱怨将 let...else 用于不可反驳模式没有意义:

{{#include ../listings/ch19-patterns-and-matching/listing-19-10/output.txt}}

由于这个原因,match 分支必须使用可反驳模式,除了最后一个分支,它应该使用不可反驳模式匹配任何剩余的值。Rust 允许我们在只有单个分支的 match 中使用不可反驳模式,但这种语法并不是特别有用,并且可以用更简单的 let 语句代替。

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.

既然你已经知道了在哪里使用模式以及可反驳和不可反驳模式之间的区别,让我们来看看所有可以用来创建模式的语法。

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)


x-i18n: generated_at: “2026-03-01T14:57:37Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: cc8b098538391d5e5f28e66c126209262e9aaf55d12f99056950be043d748679 source_path: ch19-03-pattern-syntax.md workflow: 16

模式语法 (Pattern Syntax)

在本节中,我们收集了模式中所有有效的语法,并讨论了你可能想要使用每种语法的理由和时机。

In this section, we gather all the syntax that is valid in patterns and discuss why and when you might want to use each one.

匹配字面量 (Matching Literals)

正如你在第 6 章中看到的,你可以直接将模式与字面量进行匹配。以下代码提供了一些示例:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/no-listing-01-literals/src/main.rs:here}}
}

这段代码打印 one ,因为 x 中的值是 1 。当你希望代码在获得特定具体值时采取行动时,这种语法很有用。

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.

匹配命名变量 (Matching Named Variables)

命名变量是匹配任何值的不可反驳模式,我们在本书中已经多次使用过它们。然而,当你在 matchif letwhile let 表达式中使用命名变量时,情况会变得复杂。因为这些种类的表达式中的每一个都会开启一个新作用域,所以这些表达式内部作为模式一部分声明的变量将遮蔽结构外部同名的变量,就像所有变量的情况一样。在示例 19-11 中,我们声明了一个名为 x 的变量,其值为 Some(5) ,以及一个名为 y 的变量,其值为 10 。然后我们对值 x 创建一个 match 表达式。在运行此代码或进一步阅读之前,请看 match 分支中的模式和末尾的 println! ,尝试弄清楚代码会打印什么。

Named variables are irrefutable patterns that match any value, and we’ve used them many times in this book. However, there is a complication when you use named variables in match, if let, or while let expressions. Because each of these kinds of expressions starts a new scope, variables declared as part of a pattern inside these expressions will shadow those with the same name outside the constructs, as is the case with all variables. In Listing 19-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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-11/src/main.rs:here}}
}

让我们逐步了解 match 表达式运行时会发生什么。第一个 match 分支中的模式与 x 的定义值不匹配,因此代码继续运行。

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 分支中的模式引入了一个名为 y 的新变量,它将匹配 Some 值内部的任何值。因为我们处于 match 表达式内部的一个新作用域中,这是一个新的 y 变量,而不是我们在开头声明的且值为 10 的那个 y 。这个新的 y 绑定将匹配 Some 内部的任何值,这正是我们在 x 中拥有的。因此,这个新的 y 绑定到 xSome 的内部值。那个值是 5 ,所以该分支的表达式执行并打印 Matched, y = 5

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.

如果 x 是一个 None 值而不是 Some(5) ,前两个分支中的模式将不匹配,因此该值将匹配到下划线。我们没有在下划线分支的模式中引入 x 变量,因此表达式中的 x 仍然是未被遮蔽的外部 x 。在这种假设的情况下, match 将打印 Default case, x = None

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.

match 表达式执行完毕后,它的作用域结束,内部 y 的作用域也随之结束。最后一条 println! 产生 at the end: x = Some(5), y = 10

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.

要创建一个比较外部 xy 值的 match 表达式,而不是引入一个遮蔽现有 y 变量的新变量,我们需要改用 match 守卫 (match guard) 条件。我们将在稍后的“使用 match 守卫添加条件”一节中讨论 match 守卫。

To create a match expression that compares the values of the outer x and y, rather than introducing a new variable that shadows the existing y variable, we would need to use a match guard conditional instead. We’ll talk about match guards later in the “Adding Conditionals with Match Guards” section.

匹配多个模式 (Matching Multiple Patterns)

match 表达式中,你可以使用 | 语法匹配多个模式,这是模式“或 (or)”运算符。例如,在以下代码中,我们将 x 的值与 match 分支进行匹配,其中第一个分支有一个“或”选项,这意味着如果 x 的值匹配该分支中的任一值,该分支的代码就会运行:

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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs:here}}
}

这段代码打印 one or two

This code prints one or two.

使用 ..= 匹配值范围 (Matching Ranges of Values with ..=)

..= 语法允许我们匹配一个闭区间范围内的值。在以下代码中,当一个模式匹配给定范围内的任何值时,该分支将执行:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/no-listing-03-ranges/src/main.rs:here}}
}

如果 x12345 ,第一个分支将匹配。与使用 | 运算符表达相同想法相比,这种语法对于匹配多个值更方便;如果要使用 | ,我们就必须指定 1 | 2 | 3 | 4 | 5 。指定一个范围要短得多,特别是如果我们想匹配,比如 1 到 1,000 之间的任何数字!

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!

编译器在编译时会检查范围是否为空,并且由于 Rust 只能对 char 和数值判断其范围是否为空,因此范围只允许用于数值或 char 值。

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.

这里有一个使用 char 值范围的例子:

Here is an example using ranges of char values:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs:here}}
}

Rust 可以判断出 'c' 在第一个模式的范围内,并打印 early ASCII letter

Rust can tell that 'c' is within the first pattern’s range and prints early ASCII letter.

解构以分解值 (Destructuring to Break Apart Values)

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.

结构体 (Structs)

示例 19-12 显示了一个具有 xy 两个字段的 Point 结构体,我们可以使用带有 let 语句的模式将其分解。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-12/src/main.rs}}
}

这段代码创建了变量 ab ,它们匹配 p 结构体的 xy 字段的值。这个例子说明模式中变量的名称不必与结构体的字段名匹配。然而,将变量名与字段名匹配是很常见的,以便更容易记住哪些变量来自哪些字段。由于这种常见用法,并且由于编写 let Point { x: x, y: y } = p; 包含大量重复,Rust 提供了一种匹配结构体字段的模式简写:你只需要列出结构体字段的名称,从模式中创建的变量将具有相同的名称。示例 19-13 的行为与示例 19-12 中的代码相同,但在 let 模式中创建的变量是 xy 而不是 ab

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 19-13 behaves in the same way as the code in Listing 19-12, but the variables created in the let pattern are x and y instead of a and b.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-13/src/main.rs}}
}

这段代码创建了匹配变量 pxy 字段的变量 xy 。其结果是变量 xy 包含了来自 p 结构体的值。

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.

我们也可以将字面量值作为结构体模式的一部分进行解构,而不是为所有字段都创建变量。这样做允许我们测试某些字段是否具有特定值,同时创建变量来解构其他字段。

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.

在示例 19-14 中,我们有一个 match 表达式,它将 Point 值分为三种情况:直接位于 x 轴上(当 y = 0 时为真)、位于 y 轴上( x = 0 )或不在任一轴上的点。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-14/src/main.rs:here}}
}

通过指定 y 字段如果其值匹配字面量 0 则匹配,第一个分支将匹配位于 x 轴上的任何点。该模式仍然创建了一个 x 变量,我们可以在该分支的代码中使用它。

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.

类似地,第二个分支通过指定 x 字段如果其值为 0 则匹配来匹配 y 轴上的任何点,并为 y 字段的值创建一个变量 y 。第三个分支没有指定任何字面量,因此它匹配任何其他 Point 并为 xy 字段都创建变量。

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.

在这个例子中,值 p 由于 x 包含 0 而匹配第二个分支,所以这段代码将打印 On the y axis at 7

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.

记住 match 表达式一旦找到第一个匹配的模式就会停止检查分支,所以即使 Point { x: 0, y: 0 } 既在 x 轴也在 y 轴上,这段代码也只会打印 On the x axis at 0

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.

枚举 (Enums)

我们在本书中解构过枚举(例如第 6 章的示例 6-5),但我们还没有明确讨论过解构枚举的模式与枚举中存储数据定义的方式相对应。举个例子,在示例 19-15 中,我们使用示例 6-2 中的 Message 枚举,并编写了一个带有模式的 match ,这些模式将解构每个内部值。

We’ve destructured enums in this book (for example, Listing 6-5 in Chapter 6), but we 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 19-15, we use the Message enum from Listing 6-2 and write a match with patterns that will destructure each inner value.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-15/src/main.rs}}
}

这段代码将打印 Change color to red 0, green 160, and blue 255 。尝试更改 msg 的值,看看其他分支的代码运行情况。

This code will print Change color to red 0, green 160, and blue 255. Try changing the value of msg to see the code from the other arms run.

对于没有任何数据的枚举变体,如 Message::Quit ,我们无法进一步解构该值。我们只能匹配字面量 Message::Quit 值,且该模式中没有变量。

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::Move ,我们可以使用类似于匹配结构体所指定的模式。在变体名称之后,我们放置花括号,然后列出带有变量的字段,以便分解出各部分在该分支的代码中使用。在这里,我们使用了示例 19-13 中所用的简写形式。

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 that we break apart the pieces to use in the code for this arm. Here we use the shorthand form as we did in Listing 19-13.

对于类元组枚举变体,如持有一个包含一个元素元组的 Message::Write 和持有一个包含三个元素元组的 Message::ChangeColor ,其模式类似于匹配元组所指定的模式。模式中变量的数量必须与我们要匹配的变体中元素的数量相匹配。

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.

嵌套的结构体和枚举 (Nested Structs and Enums)

到目前为止,我们的示例都是匹配一层深度的结构体或枚举,但匹配也可以在嵌套项上进行!例如,我们可以重构示例 19-15 中的代码,以在 ChangeColor 消息中支持 RGB 和 HSV 颜色,如示例 19-16 所示。

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 19-15 to support RGB and HSV colors in the ChangeColor message, as shown in Listing 19-16.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-16/src/main.rs}}
}

match 表达式第一个分支的模式匹配一个包含 Color::Rgb 变体的 Message::ChangeColor 枚举变体;然后,模式绑定到三个内部的 i32 值。第二个分支的模式也匹配一个 Message::ChangeColor 枚举变体,但内部枚举匹配的是 Color::Hsv 。我们可以在一个 match 表达式中指定这些复杂的条件,即使涉及到两个枚举。

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.

结构体和元组 (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:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs:here}}
}

这段代码让我们能够将复杂类型拆分为其组成部分,以便我们可以分别使用我们感兴趣的值。

This code lets us break complex types into their component parts so that 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)

你已经看到,有时忽略模式中的值很有用,例如在 match 的最后一个分支中获取一个通配模式,它实际上不执行任何操作,但确实考虑了所有剩余的可能值。有几种方法可以在模式中忽略整个值或值的部分:使用 _ 模式(你已经见过了)、在另一个模式内部使用 _ 模式、使用以下划线开头的名称,或者使用 .. 来忽略值的剩余部分。让我们探索如何以及为什么要使用这些模式中的每一个。

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 catch-all 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.

使用 _ 忽略整个值 (An Entire Value with _)

我们将下划线用作通配符模式,它将匹配任何值但不绑定到该值。这在 match 表达式的最后一个分支中特别有用,但我们也可以在任何模式中使用它,包括函数参数,如示例 19-17 所示。

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 19-17.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-17/src/main.rs}}
}

这段代码将完全忽略作为第一个参数传入的值 3 ,并打印 This code only uses the y parameter: 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.

在大多数情况下,当你不再需要某个特定函数参数时,你会更改签名使其不包含该未使用的参数。忽略函数参数在某些情况下特别有用,例如,当你实现一个特征时,你需要某种特定的类型签名,但实现中的函数体并不需要其中一个参数。这时你就可以避免像使用名称那样得到关于未使用函数参数的编译器警告。

In most cases when you no longer need a particular function parameter, you would change the signature so that 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.

使用嵌套的 _ 忽略值的部分 (Parts of a Value with a Nested _)

我们也可以在另一个模式内部使用 _ 来忽略值的一部分,例如,当我们只想测试值的一部分,但在要运行的相应代码中不需要其他部分时。示例 19-18 显示了负责管理设置值的代码。业务要求是,不允许用户覆盖现有的设置自定义,但如果当前未设置,则可以取消设置并为其赋予一个值。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-18/src/main.rs:here}}
}

这段代码将打印 Can't overwrite an existing customized value 接着打印 setting is Some(5) 。在第一个 match 分支中,我们不需要匹配或使用任一 Some 变体内部的值,但我们确实需要测试 setting_valuenew_setting_value 都是 Some 变体的情况。在那种情况下,我们打印不更改 setting_value 的原因,并且它不会被更改。

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.

在由第二个分支中的 _ 模式表示的所有其他情况(如果 setting_valuenew_setting_value 之一是 None )中,我们希望允许 new_setting_value 成为 setting_value

In all other cases (if either setting_value or new_setting_value is None) expressed by the _ pattern in the second arm, we want to allow new_setting_value to become setting_value.

我们也可以在一个模式的多个地方使用下划线来忽略特定的值。示例 19-19 展示了一个忽略包含五个项的元组中第二个和第四个值的例子。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-19/src/main.rs:here}}
}

这段代码将打印 Some numbers: 2, 8, 32 ,值 416 将被忽略。

This code will print Some numbers: 2, 8, 32, and the values 4 and 16 will be ignored.

通过以 _ 开头命名来忽略未使用的变量 (An Unused Variable by Starting Its Name with _)

如果你创建了一个变量但在任何地方都不使用它,Rust 通常会发出警告,因为未使用的变量可能是一个 bug。然而,有时创建一个你尚未使用的变量是很有用的,比如当你正在开发原型或刚开始一个项目时。在这种情况下,你可以通过以连接号开头命名变量来告诉 Rust 不要就未使用的变量向你发出警告。在示例 19-20 中,我们创建了两个未使用的变量,但当我们编译这段代码时,我们应该只得到关于其中一个的警告。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-20/src/main.rs}}
}

在这里,我们得到了关于不使用变量 y 的警告,但没有得到关于不使用 _x 的警告。

Here, we get a warning about not using the variable y, but we don’t get a warning about not using _x.

注意,仅使用 _ 与使用以下划线开头的名称之间有细微的区别。语法 _x 仍然将值绑定到变量,而 _ 则完全不绑定。为了展示这种区别的重要性,示例 19-21 将为我们提供一个错误。

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 19-21 will provide us with an error.

{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-21/src/main.rs:here}}

我们将收到一个错误,因为 s 值仍将被移动到 _s 中,这阻止了我们再次使用 s 。然而,单独使用下划线永远不会绑定到该值。示例 19-22 将可以编译且没有任何错误,因为 s 不会被移动到 _ 中。

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 19-22 will compile without any errors because s doesn’t get moved into _.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-22/src/main.rs:here}}
}

这段代码运行良好,因为我们从未将 s 绑定到任何东西上;它没有被移动。

This code works just fine because we never bind s to anything; it isn’t moved.

使用 .. 忽略值的剩余部分 (Remaining Parts of a Value with ..)

对于具有许多部分的值,我们可以使用 .. 语法来使用特定的部分并忽略其余部分,从而避免为每个被忽略的值列出下划线。 .. 模式忽略了我们在模式的其余部分中没有显式匹配的值的任何部分。在示例 19-23 中,我们有一个 Point 结构体,它持有三维空间中的一个坐标。在 match 表达式中,我们只想对 x 坐标进行操作,并忽略 yz 字段中的值。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-23/src/main.rs:here}}
}

我们列出 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.

语法 .. 会根据需要扩展为尽可能多的值。示例 19-24 显示了如何对元组使用 ..

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-24/src/main.rs}}
}

在这段代码中,第一个和最后一个值分别与 firstlast 匹配。 .. 将匹配并忽略中间的所有内容。

In this code, the first and last values are matched with first and last. The .. will match and ignore everything in the middle.

然而,使用 .. 必须是无歧义的。如果还不清楚哪些值是打算用于匹配的,哪些应该是被忽略的,Rust 会给我们一个错误。示例 19-25 显示了一个以歧义方式使用 .. 的例子,因此它将无法编译。

{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-25/src/main.rs}}

当我们编译这个例子时,我们得到了这个错误:

{{#include ../listings/ch19-patterns-and-matching/listing-19-25/output.txt}}

Rust 不可能确定在将一个值与 second 匹配之前应该忽略元组中的多少个值,以及此后应该再忽略多少个值。这段代码可能意味着我们要忽略 2 ,将 second 绑定到 4 ,然后忽略 81632 ;或者我们要忽略 24 ,将 second 绑定到 8 ,然后忽略 1632 ;等等。变量名 second 对 Rust 来说没有任何特殊含义,所以因为像这样在两个地方使用 .. 具有歧义,我们得到了一个编译器错误。

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.

使用 match 守卫添加条件 (Adding Conditionals with Match Guards)

“match 守卫 (match guard)” 是在 match 分支模式之后指定的额外 if 条件,它也必须匹配才能选择该分支。match 守卫对于表达比单独模式所允许的更复杂的想法很有用。但请注意,它们仅在 match 表达式中可用,而不在 if letwhile let 表达式中。

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. Note, however, that they are only available in match expressions, not if let or while let expressions.

该条件可以使用在模式中创建的变量。示例 19-26 显示了一个 match ,其中第一个分支具有模式 Some(x) ,并且还具有 if x % 2 == 0 的 match 守卫(如果数字是偶数,则为 true )。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-26/src/main.rs:here}}
}

本例将打印 The number 4 is even 。当 num 与第一个分支中的模式比较时,它是匹配的,因为 Some(4) 匹配 Some(x) 。然后,match 守卫检查 x 除以 2 的余数是否等于 0,因为是,所以选择了第一个分支。

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.

如果 numSome(5) ,第一个分支中的 match 守卫将为 false ,因为 5 除以 2 的余数是 1,不等于 0。Rust 然后会转到第二个分支,它是匹配的,因为第二个分支没有 match 守卫,因此匹配任何 Some 变体。

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.

在模式中无法表达 if x % 2 == 0 条件,因此 match 守卫赋予了我们表达此逻辑的能力。这种额外表达能力的代价是,当涉及到 match 守卫表达式时,编译器不会尝试检查穷尽性。

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.

在讨论示例 19-11 时,我们提到可以使用 match 守卫来解决我们的模式遮蔽问题。回想一下,我们在 match 表达式内部的模式中创建了一个新变量,而不是使用 match 外部的变量。那个新变量意味着我们无法针对外部变量的值进行测试。示例 19-27 展示了我们如何使用 match 守卫来解决这个问题。

When discussing Listing 19-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 19-27 shows how we can use a match guard to fix this problem.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-27/src/main.rs}}
}

这段代码现在将打印 Default case, x = Some(5) 。第二个 match 分支中的模式没有引入会遮蔽外部 y 的新变量 y ,这意味着我们可以在 match 守卫中使用外部 y 。我们没有将模式指定为 Some(y) (那会遮蔽外部 y ),而是指定了 Some(n) 。这创建了一个新变量 n ,它不会遮蔽任何东西,因为 match 之外没有 n 变量。

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.

match 守卫 if n == y 不是一个模式,因此不会引入新变量。这个 y “是”外部的 y 而不是遮蔽它的新 y ,我们可以通过将 ny 进行比较来寻找具有与外部 y 相同值的值。

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 y shadowing it, and we can look for a value that has the same value as the outer y by comparing n to y.

你也可以在 match 守卫中使用“或”运算符 | 来指定多个模式;match 守卫条件将应用于所有模式。示例 19-28 显示了将使用 | 的模式与 match 守卫结合时的优先级。本例的重要部分是 if y match 守卫应用于 45 “以及” 6 ,即使它看起来可能像 if y 只应用于 6

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 19-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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-28/src/main.rs:here}}
}

match 条件声明该分支只有在 x 的值等于 456 “并且” ytrue 时才匹配。当这段代码运行时,第一个分支的模式匹配是因为 x4 ,但 match 守卫 if yfalse ,因此第一个分支没有被选中。代码转到第二个分支,它是匹配的,于是这个程序打印 no 。原因是 if 条件应用于整个模式 4 | 5 | 6 ,而不仅仅是最后一个值 6 。换句话说,match 守卫相对于模式的优先级表现如下:

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 just to the last value 6. In other words, the precedence of a match guard in relation to a pattern behaves like this:

(4 | 5 | 6) if y => ...

而不是这样:

rather than this:

4 | 5 | (6 if y) => ...

运行代码后,优先级行为显而易见:如果 match 守卫仅应用于使用 | 运算符指定的列表中的最后一个值,则该分支本应匹配,并且程序会打印出 yes

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.

使用 @ 绑定 (Using @ Bindings)

at 运算符 @ 允许我们在测试一个值是否匹配模式的同时创建一个持有该值的变量。在示例 19-29 中,我们要测试 Message::Helloid 字段是否在范围 3..=7 内。我们还想将该值绑定到变量 id ,以便我们可以在与该分支关联的代码中使用它。

The at operator @ lets us create a variable that holds a value at the same time we’re testing that value for a pattern match. In Listing 19-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 so that we can use it in the code associated with the arm.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch19-patterns-and-matching/listing-19-29/src/main.rs:here}}
}

本例将打印 Found an id in range: 5 。通过在范围 3..=7 之前指定 id @ ,我们捕捉到了任何匹配该范围的值并放入一个名为 id 的变量中,同时也测试了该值是否匹配该范围模式。

This example will print Found an id in range: 5. By specifying id @ before the range 3..=7, we’re capturing whatever value matched the range in a variable named id while also testing that the value matched the range pattern.

在第二个分支中,模式中仅指定了一个范围,与该分支关联的代码就没有包含 id 字段实际值的变量。 id 字段的值可能是 10、11 或 12,但与该模式配合的代码并不知道它是哪个。由于我们没有将 id 的值保存在变量中,模式代码无法使用来自 id 字段的值。

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 字段中的值应用任何测试:任何值都会匹配这个模式。

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.

使用 @ 让我们能在一个模式内测试一个值并将其保存在变量中。

Using @ lets us test a value and save it in a variable within one pattern.

总结 (Summary)

Rust 的模式在区分不同种类的数据时非常有用。当在 match 表达式中使用时,Rust 确保你的模式覆盖了每一个可能的值,否则你的程序将无法编译。 let 语句和函数参数中的模式使这些结构更有用,能够将值解构为更小的部分并将这些部分分配给变量。我们可以创建简单或复杂的模式来满足我们的需求。

Rust’s patterns are very useful in distinguishing between different kinds of data. When used in match expressions, Rust ensures that 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 and assigning those parts to variables. We can create simple or complex patterns to suit our needs.

接下来,作为本书的倒数第二章,我们将看看 Rust 各种特性的一些高级方面。走吧!

Next, for the penultimate chapter of the book, we’ll look at some advanced aspects of a variety of Rust’s features. Let’s go!

高级特性 (Advanced Features)


x-i18n: generated_at: “2026-03-01T14:57:45Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: dc250ffa5f82d92ee01e7a6bf46ac6fb7b1f71f0ae368bbb5fe88d71b1f6e5e5 source_path: ch20-00-advanced-features.md workflow: 16

高级特性 (Advanced Features)

Advanced Features

到目前为止,你已经学习了 Rust 编程语言中最常用的部分。在我们在第 21 章再做一个项目之前,我们将看看该语言中你可能偶尔会遇到但可能不会每天都使用的几个方面。当遇到任何未知内容时,你可以将本章作为参考。这里介绍的特性在非常特定的情况下很有用。虽然你可能不会经常用到它们,但我们希望确保你掌握 Rust 所提供的所有特性。

By now, you’ve learned the most commonly used parts of the Rust programming language. Before we do one more project, in Chapter 21, 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 (Unsafe Rust):如何选择退出 Rust 的某些保证,并承担手动维护这些保证的责任
  • 高级特征 (Advanced traits):关联类型、默认类型参数、完全限定语法、父特征 (supertraits) 以及与特征相关的 newtype 模式
  • 高级类型 (Advanced types):关于 newtype 模式的更多信息、类型别名、从不类型 (never type) 和动态大小类型
  • 高级函数和闭包 (Advanced functions and closures):函数指针和返回闭包
  • 宏 (Macros):在编译时定义定义更多代码的代码的方法

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
  • 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
  • Advanced functions and closures: Function pointers and returning closures
  • Macros: Ways to define code that defines more code at compile time

这是 Rust 特性的汇集,每个人都能各取所需!让我们潜入其中吧!

It’s a panoply of Rust features with something for everyone! Let’s dive in!

不安全 Rust (Unsafe Rust)


x-i18n: generated_at: “2026-03-01T14:59:43Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 5d91b909eec72d9a9438ed2f9d6db65cfa1243e607109d4f152e0be8e2295d7b source_path: ch20-01-unsafe-rust.md workflow: 16

不安全 Rust (Unsafe Rust)

到目前为止,我们讨论的所有代码都在编译时强制执行了 Rust 的内存安全保证。然而,Rust 内部隐藏着第二种不强制执行这些内存安全保证的语言:它被称为“不安全 Rust (unsafe Rust)”,它的工作方式与常规 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 的风险由你承担:如果你不正确地使用不安全代码,可能会由于内存不安全而发生问题,例如空指针解引用。

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 需要允许你进行低级系统编程,例如直接与操作系统交互,甚至编写你自己的操作系统。进行低级系统编程是该语言的目标之一。让我们探索一下我们可以用不安全 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.

执行不安全超能力 (Performing Unsafe Superpowers)

Performing Unsafe Superpowers

要切换到不安全 Rust,请使用 unsafe 关键字,然后开始一个持有不安全代码的新块。在不安全 Rust 中,你可以执行五项在安全 Rust 中不能执行的操作,我们称之为“不安全超能力 (unsafe superpowers)”。这些超能力包括以下能力:

  1. 解引用原始指针 (raw pointer)
  2. 调用不安全函数或方法
  3. 访问或修改可变的静态变量 (static variable)
  4. 实现不安全特征 (unsafe trait)
  5. 访问 union 的字段

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:

  1. Dereference a raw pointer.
  2. Call an unsafe function or method.
  3. Access or modify a mutable static variable.
  4. Implement an unsafe trait.
  5. Access fields of unions.

重要的是要理解, unsafe 并不会关闭借用检查器或禁用任何 Rust 的其他安全检查:如果你在不安全代码中使用引用,它仍然会被检查。 unsafe 关键字只允许你访问这五个随后不由编译器进行内存安全检查的特性。在不安全块内部,你仍然可以获得某种程度的安全。

It’s important to understand that unsafe doesn’t turn off the borrow checker or disable any of Rust’s other 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 an unsafe block.

此外, unsafe 并不意味着块内的代码一定是危险的,或者它肯定会有内存安全问题:其意图是,作为程序员,你将确保 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 that the code inside an unsafe block will access memory in a valid way.

人非圣贤,孰能无过,但通过要求将这五项不安全操作放在用 unsafe 标注的块内,你就会知道任何与内存安全相关的错误都必然发生在 unsafe 块内。请保持 unsafe 块足够小;当你调查内存 bug 时,你会感谢现在的决定的。

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.

为了尽可能隔离不安全代码,最好将此类代码封装在安全抽象中并提供一个安全的 API,我们将在本章后面研究不安全函数和方法时讨论这一点。标准库的部分内容被实现为对已审核过的不安全代码的安全抽象。将不安全代码包装在安全抽象中,可以防止 unsafe 的使用泄露到你或你的用户可能想要使用由 unsafe 代码实现的功能的所有地方,因为使用安全抽象是安全的。

To isolate unsafe code as much as possible, it’s best to enclose such 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.

让我们轮流看看这五个不安全超能力。我们还将看一些为不安全代码提供安全接口的抽象。

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)

在第 4 章“悬垂引用”部分中,我们提到编译器确保引用始终有效。不安全 Rust 有两种类似于引用的新类型,称为“原始指针 (raw pointers)”。与引用一样,原始指针可以是不可变的或可变的,分别写作 *const T*mut T 。星号不是解引用运算符;它是类型名称的一部分。在原始指针的上下文中,“不可变”意味着指针在解引用后不能被直接赋值。

In Chapter 4, in the “Dangling References” section, we mentioned that the compiler ensures that 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.

与引用和智能指针不同,原始指针:

  • 允许通过同时拥有指向同一位置的不可变和可变指针,或多个可变指针来忽略借用规则
  • 不保证指向有效的内存
  • 允许为 null
  • 不实现任何自动清理

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

通过选择不让 Rust 强制执行这些保证,你可以放弃保证的安全,以换取更高的性能,或者与 Rust 保证不适用的另一种语言或硬件进行接口。

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.

示例 20-1 展示了如何创建一个不可变和一个可变的原始指针。

Listing 20-1 shows how to create an immutable and a mutable raw pointer.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-01/src/main.rs:here}}
}

注意我们在这段代码中没有包含 unsafe 关键字。我们可以在安全代码中创建原始指针;我们只是不能在不安全块之外解引用原始指针,你稍后就会看到。

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.

我们通过使用原始借用运算符创建了原始指针: &raw const num 创建了一个 *const i32 不可变原始指针,而 &raw mut num 创建了一个 *mut i32 可变原始指针。因为我们直接从局部变量创建了它们,所以我们知道这些特定的原始指针是有效的,但我们不能对任何原始指针都做这种假设。

We’ve created raw pointers by using the raw borrow operators: &raw const num creates a *const i32 immutable raw pointer, and &raw mut num creates a *mut i32 mutable raw pointer. Because we created them directly from a local variable, we know these particular raw pointers are valid, but we can’t make that assumption about just any raw pointer.

为了证明这一点,接下来我们将使用关键字 as 来强制转换一个值,而不是使用原始借用运算符,从而创建一个有效性不那么确定的原始指针。示例 20-2 展示了如何创建一个指向内存中任意位置的原始指针。尝试使用任意内存是未定义的:那个地址可能有数据,也可能没有,编译器可能会优化代码导致没有内存访问,或者程序可能会以分段错误 (segmentation fault) 终止。通常,没有理由编写这样的代码,特别是在你可以改用原始借用运算符的情况下,但它是可能的。

To demonstrate this, next we’ll create a raw pointer whose validity we can’t be so certain of, using the keyword as to cast a value instead of using the raw borrow operator. Listing 20-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 that there is no memory access, or the program might terminate with a segmentation fault. Usually, there is no good reason to write code like this, especially in cases where you can use a raw borrow operator instead, but it is possible.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-02/src/main.rs:here}}
}

回想一下,我们可以在安全代码中创建原始指针,但我们不能解引用原始指针并读取被指向的数据。在示例 20-3 中,我们在一个原始指针上使用了需要 unsafe 块的解引用运算符 *

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-03/src/main.rs:here}}
}

创建指针没有任何坏处;只有当我们尝试访问它所指向的值时,我们才可能最终处理一个无效值。

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.

还要注意,在示例 20-1 和 20-3 中,我们创建了 *const i32*mut i32 原始指针,它们都指向存储 num 的相同内存位置。如果我们转而尝试为 num 创建一个不可变和一个可变的引用,代码将无法通过编译,因为 Rust 的所有权规则不允许在存在任何不可变引用的同时存在可变引用。使用原始指针,我们可以创建一个可变指针和一个不可变指针指向相同的位置,并通过可变指针更改数据,这可能会创建数据竞争。请务必小心!

Note also that in Listings 20-1 and 20-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!

既然有这么多危险,你为什么还要使用原始指针呢?一个主要的用例是与 C 代码交互时,你将在下一节看到。另一种情况是构建借用检查器无法理解的安全抽象。我们将介绍不安全函数,然后看一个使用不安全代码的安全抽象例子。

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. 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.

调用不安全函数或方法 (Calling an Unsafe Function or Method)

Calling an Unsafe Function or Method

你可以在不安全块中执行的第二类操作是调用不安全函数。不安全函数和方法看起来与常规函数和方法完全一样,但在定义的其余部分之前有一个额外的 unsafe 。在此上下文中的 unsafe 关键字表示,当我们调用此函数时,我们需要遵守一些要求,因为 Rust 无法保证我们已经满足了这些要求。通过在 unsafe 块内调用不安全函数,我们表示我们已经阅读了此函数的文档,并且我们承担维护函数合同的责任。

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 we take responsibility for upholding the function’s contracts.

这里有一个名为 dangerous 的不安全函数,它的主体里什么也没做:

Here is an unsafe function named dangerous that doesn’t do anything in its body:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-01-unsafe-fn/src/main.rs:here}}
}

我们必须在一个单独的 unsafe 块内调用 dangerous 函数。如果我们尝试在没有 unsafe 块的情况下调用 dangerous ,我们将得到一个错误:

{{#include ../listings/ch20-advanced-features/output-only-01-missing-unsafe/output.txt}}

有了 unsafe 块,我们就向 Rust 断言我们已经阅读了函数的文档,我们了解如何正确使用它,并且我们已经验证了我们正在履行函数的合同。

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 块,如果你忘记了,编译器会警告你。这有助于我们将 unsafe 块保持得尽可能小,因为不安全操作可能不需要贯穿整个函数体。

To perform unsafe operations in the body of an unsafe function, you still need to use an unsafe block, just as within a regular function, and the compiler will warn you if you forget. This helps us keep unsafe blocks as small as possible, as unsafe operations may not be needed across the whole function body.

在不安全代码上创建安全抽象 (Creating a Safe Abstraction over Unsafe Code)

仅仅因为一个函数包含不安全代码,并不意味着我们需要将整个函数标记为不安全。事实上,在安全函数中包装不安全代码是一种常见的抽象。作为一个例子,让我们研究一下标准库中的 split_at_mut 函数,它需要一些不安全代码。我们将探索如何实现它。这个安全方法定义在可变切片上:它接收一个切片,并根据作为参数给出的索引将其一分为二。示例 20-4 展示了如何使用 split_at_mut

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 20-4 shows how to use split_at_mut.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-04/src/main.rs:here}}
}

我们无法仅使用安全 Rust 来实现此函数。一次尝试可能看起来像示例 20-5,它将无法通过编译。为了简单起见,我们将 split_at_mut 实现为一个函数而不是方法,并且仅针对 i32 值的切片而不是针对泛型 T

We can’t implement this function using only safe Rust. An attempt might look something like Listing 20-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.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-05/src/main.rs:here}}

该函数首先获取切片的总长度。然后,它通过检查索引是否小于或等于长度,来断言作为参数给出的索引位于切片内。断言意味着如果我们传递一个大于切片分割长度的索引,函数将在尝试使用该索引之前引发恐慌。

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.

然后,我们在元组中返回两个可变切片:一个从原始切片的开始到 mid 索引,另一个从 mid 到切片的末尾。

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.

当我们尝试编译示例 20-5 中的代码时,我们将得到一个错误:

{{#include ../listings/ch20-advanced-features/listing-20-05/output.txt}}

Rust 的借用检查器无法理解我们正在借用切片的不同部分;它只知道我们两次从同一个切片中借用。借用切片的不同部分从根本上说没问题,因为这两个切片没有重叠,但 Rust 不够聪明,无法知道这一点。当我们知道代码没问题但 Rust 不知道时,就是该寻求不安全代码的时候了。

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.

示例 20-6 展示了如何使用 unsafe 块、原始指针和一些对不安全函数的调用,来使 split_at_mut 的实现正常工作。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-06/src/main.rs:here}}
}

回想第 4 章“切片类型”一节可知,切片是一个指向某些数据的指针和切片的长度。我们使用 len 方法获取切片的长度,使用 as_mut_ptr 方法访问切片的原始指针。在这种情况下,因为我们有一个 i32 值的可变切片, as_mut_ptr 返回一个类型为 *mut i32 的原始指针,我们将其存储在变量 ptr 中。

Recall from “The Slice Type” section in Chapter 4 that a slice is 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.

我们保留了 mid 索引在切片内的断言。然后,我们进入不安全代码: slice::from_raw_parts_mut 函数接收一个原始指针和一个长度,并创建一个切片。我们使用此函数创建一个从 ptr 开始且长度为 mid 项的切片。然后,我们在 ptr 上调用以 mid 为参数的 add 方法,以获得一个从 mid 开始的原始指针,并使用该指针和 mid 之后剩余的项数作为长度来创建一个切片。

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.

函数 slice::from_raw_parts_mut 是不安全的,因为它接收一个原始指针,并且必须相信这个指针是有效的。原始指针上的 add 方法也是不安全的,因为它必须相信偏移位置也是一个有效的指针。因此,我们必须在调用 slice::from_raw_parts_mutadd 时套上一个 unsafe 块,以便我们可以调用它们。通过观察代码并加上 mid 必须小于或等于 len 的断言,我们可以判断在 unsafe 块内使用的所有原始指针都将是切片内数据的有效指针。这是一种可以接受且恰当的 unsafe 用法。

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 that 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.

注意,我们不需要将生成的 split_at_mut 函数标记为 unsafe ,并且我们可以从安全 Rust 中调用此函数。我们已经通过以安全方式使用 unsafe 代码的函数实现,为不安全代码创建了一个安全抽象,因为它仅从该函数有权访问的数据中创建有效指针。

Note that we don’t need to mark the resultant 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.

相比之下,示例 20-7 中 slice::from_raw_parts_mut 的使用在切片被使用时很可能会崩溃。这段代码获取一个任意的内存位置,并创建一个 10,000 项长的切片。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-07/src/main.rs:here}}
}

我们并不拥有这个任意位置的内存,并且无法保证这段代码创建的切片包含有效的 i32 值。尝试像使用有效切片一样使用 values 会导致未定义行为。

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.

使用 extern 函数调用外部代码 (Using extern Functions to Call External Code)

有时你的 Rust 代码可能需要与另一种语言编写的代码进行交互。为此,Rust 提供了关键字 extern ,它促进了“外部函数接口 (Foreign Function Interface,FFI)”的创建和使用,FFI 是编程语言定义函数并允许另一种(外部)编程语言调用这些函数的一种方式。

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), which is a way for a programming language to define functions and enable a different (foreign) programming language to call those functions.

示例 20-8 演示了如何建立与 C 标准库中的 abs 函数的集成。在 extern 块中声明的函数通常在从 Rust 代码中调用时是不安全的,因此 extern 块也必须被标记为 unsafe 。原因是其他语言并不强制执行 Rust 的规则和保证,且 Rust 无法检查它们,因此确保安全的责任落在了程序员身上。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-08/src/main.rs}}
}

unsafe extern "C" 块内,我们列出了我们想要调用的另一种语言的外部函数的名称和签名。 "C" 部分定义了外部函数使用的“应用二进制接口 (application binary interface,ABI)”:ABI 定义了如何在汇编级别调用函数。 "C" ABI 是最常见的,遵循 C 编程语言的 ABI。关于 Rust 支持的所有 ABI 的信息可以在 Rust 参考手册 中找到。

Within the unsafe 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. Information about all the ABIs Rust supports is available in the Rust Reference.

unsafe extern 块中声明的每一项都是隐式不安全的。然而,一些 FFI 函数“是”安全调用的。例如,C 标准库中的 abs 函数没有任何内存安全方面的考虑,并且我们知道它可以用任何 i32 调用。在这种情况下,我们可以使用 safe 关键字来说明这个特定函数是安全调用的,尽管它位于 unsafe extern 块中。一旦我们做出此更改,调用它就不再需要 unsafe 块,如示例 20-9 所示。

Every item declared within an unsafe extern block is implicitly unsafe. However, some FFI functions are safe to call. For example, the abs function from C’s standard library does not have any memory safety considerations, and we know it can be called with any i32. In cases like this, we can use the safe keyword to say that this specific function is safe to call even though it is in an unsafe extern block. Once we make that change, calling it no longer requires an unsafe block, as shown in Listing 20-9.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-09/src/main.rs}}
}

将函数标记为 safe 并不代表它天生就是安全的!相反,这就像你向 Rust 做出的一个保证它是安全的承诺。确保该承诺得到履行仍然是你的责任!

Marking a function as safe does not inherently make it safe! Instead, it is like a promise you are making to Rust that it is safe. It is still your responsibility to make sure that promise is kept!

从其他语言调用 Rust 函数 (Calling Rust Functions from Other Languages)

Calling Rust Functions from Other Languages

我们也可以使用 extern 来创建一个允许其他语言调用 Rust 函数的接口。我们不是创建一个整个 extern 块,而是在相关函数的 fn 关键字之前添加 extern 关键字并指定要使用的 ABI。我们还需要添加一个 #[unsafe(no_mangle)] 注解,告诉 Rust 编译器不要对该函数的名称进行混淆 (mangle)。“混淆 (Mangling)” 是指编译器将我们赋予函数的名称更改为一个包含更多信息供编译过程其他部分消耗但可读性较低的不同名称。每种编程语言的编译器对名称的混淆方式都略有不同,因此,为了让 Rust 函数能被其他语言命名,我们必须禁用 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 an #[unsafe(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. This is unsafe because there might be name collisions across libraries without the built-in mangling, so it is our responsibility to make sure the name we choose is safe to export without mangling.

在下面的例子中,我们在将 call_from_c 函数编译为共享库并从 C 链接后,使其可以被 C 代码访问:

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:

#![allow(unused)]
fn main() {
#[unsafe(no_mangle)]
pub extern "C" fn call_from_c() {
    println!("Just called a Rust function from C!");
}
}

这种 extern 的用法仅在属性中需要 unsafe ,而不需要在 extern 块上。

This usage of extern requires unsafe only in the attribute, not on the extern block.

访问或修改可变的静态变量 (Accessing or Modifying a Mutable Static Variable)

Accessing or Modifying a Mutable Static Variable

在本书中,我们还没有谈到全局变量,Rust 确实支持全局变量,但对于 Rust 的所有权规则来说,它们可能会有问题。如果两个线程正在访问同一个可变全局变量,可能会导致数据竞争。

In this book, we’ve not yet talked about global variables, which Rust does support but which 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 中,全局变量被称为“静态 (static)”变量。示例 20-10 显示了一个带有字符串切片作为值的静态变量的声明和使用示例。

In Rust, global variables are called static variables. Listing 20-10 shows an example declaration and use of a static variable with a string slice as a value.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-10/src/main.rs}}
}

静态变量类似于我们在第 3 章“声明常量”部分讨论过的常量。按照惯例,静态变量的名称使用 SCREAMING_SNAKE_CASE 风格。静态变量只能存储具有 'static 生命周期的引用,这意味着 Rust 编译器可以算出该生命周期,且我们不被要求显式标注它。访问不可变的静态变量是安全的。

Static variables are similar to constants, which we discussed in the “Declaring 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.

常量和不可变静态变量之间的一个细微区别是,静态变量中的值在内存中有一个固定的地址。使用该值将始终访问相同的数据。另一方面,常量允许在每次使用时复制它们的数据。另一个区别是静态变量可以是可变的。访问和修改可变静态变量是“不安全的”。示例 20-11 展示了如何声明、访问和修改一个名为 COUNTER 的可变静态变量。

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 20-11 shows how to declare, access, and modify a mutable static variable named COUNTER.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-11/src/main.rs}}
}

与常规变量一样,我们使用 mut 关键字指定可变性。任何读取或写入 COUNTER 的代码都必须位于 unsafe 块内。示例 20-11 中的代码可以编译并如我们所料打印出 COUNTER: 3 ,因为它是单线程的。让多个线程访问 COUNTER 可能会导致数据竞争,因此这是未定义行为。因此,我们需要将整个函数标记为 unsafe ,并记录安全限制,以便任何调用该函数的人知道他们被允许以及不被允许安全执行的操作。

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. The code in Listing 20-11 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, so it is undefined behavior. Therefore, we need to mark the entire function as unsafe and document the safety limitation so that anyone calling the function knows what they are and are not allowed to do safely.

每当我们编写一个不安全函数时,惯例是写一条以 SAFETY 开头的注释,解释调用者为了安全地调用该函数需要做些什么。同样,每当我们执行一个不安全操作时,惯例也是写一条以 SAFETY 开头的注释来解释是如何遵守安全规则的。

Whenever we write an unsafe function, it is idiomatic to write a comment starting with SAFETY and explaining what the caller needs to do to call the function safely. Likewise, whenever we perform an unsafe operation, it is idiomatic to write a comment starting with SAFETY to explain how the safety rules are upheld.

此外,编译器将默认通过编译器 lint 拒绝任何通过编译器引用创建对可变静态变量引用的尝试。你必须显式通过添加 #[allow(static_mut_refs)] 注解来选择退出该 lint 的保护,或者通过使用原始借用运算符之一创建的原始指针来访问可变静态变量。这包括引用被无形创建的情况,例如在本代码清单的 println! 中使用它时。要求通过原始指针创建对静态可变变量的引用,有助于使使用它们的安全要求更加明显。

Additionally, the compiler will deny by default any attempt to create references to a mutable static variable through a compiler lint. You must either explicitly opt out of that lint’s protections by adding an #[allow(static_mut_refs)] annotation or access the mutable static variable via a raw pointer created with one of the raw borrow operators. That includes cases where the reference is created invisibly, as when it is used in the println! in this code listing. Requiring references to static mutable variables to be created via raw pointers helps make the safety requirements for using them more obvious.

对于全局可访问的可变数据,很难确保没有数据竞争,这就是 Rust 认为可变静态变量是不安全的原因。在可能的情况下,最好使用我们在第 16 章讨论过的并发技术和线程安全智能指针,以便编译器检查来自不同线程的数据访问是否安全执行。

With mutable data that is globally accessible, it’s difficult to ensure that 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 that the compiler checks that data access from different threads is done safely.

实现不安全特征 (Implementing an Unsafe Trait)

Implementing an Unsafe Trait

我们可以使用 unsafe 来实现一个不安全特征。当一个特征的至少一个方法具有编译器无法验证的某些不变量时,该特征就是不安全的。我们通过在 trait 之前添加 unsafe 关键字来声明特征是 unsafe 的,并将该特征的实现也标记为 unsafe ,如示例 20-12 所示。

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 20-12.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-12/src/main.rs:here}}
}

通过使用 unsafe impl ,我们承诺我们将维护编译器无法验证的不变量。

By using unsafe impl, we’re promising that we’ll uphold the invariants that the compiler can’t verify.

作为一个例子,回想一下我们在第 16 章“使用 SendSync 的可扩展并发”部分讨论过的 SendSync 标记特征:如果我们的类型完全由实现了 SendSync 的其他类型组成,编译器就会自动实现这些特征。如果我们实现了一个包含未实现 SendSync 类型(如原始指针)的类型,并且我们想将该类型标记为 SendSync ,我们必须使用 unsafe 。Rust 无法验证我们的类型是否维护了它可以被安全地跨线程发送或从多个线程访问的保证;因此,我们需要手动执行这些检查并使用 unsafe 进行指示。

As an example, recall the Send and Sync marker traits we discussed in the “Extensible Concurrency with Send and Sync section in Chapter 16: The compiler implements these traits automatically if our types are composed entirely of other types that implement Send and Sync. If we implement a type that contains a type that does not implement 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.

访问 Union 的字段 (Accessing Fields of a Union)

Accessing Fields of a Union

仅适用于 unsafe 的最后一项操作是访问 union 的字段。 一个 union 类似于 struct ,但在特定实例中一次只使用一个声明的字段。Union 主要用于与 C 代码中的 union 进行接口。访问 union 字段是不安全的,因为 Rust 无法保证 union 实例中当前存储的数据类型。你可以在 Rust 参考手册 中了解更多关于 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.

使用 Miri 检查不安全代码 (Using Miri to Check Unsafe Code)

Using Miri to Check Unsafe Code

在编写不安全代码时,你可能想检查你编写的代码是否真正安全且正确。实现这一目标的最佳方法之一是使用 Miri,这是一个用于检测未定义行为的官方 Rust 工具。借用检查器是一个在编译时工作的“静态 (static)”工具,而 Miri 是一个在运行时工作的“动态 (dynamic)”工具。它通过运行你的程序或其测试套件来检查你的代码,并检测你何时违反了它所理解的关于 Rust 应如何工作的规则。

When writing unsafe code, you might want to check that what you have written actually is safe and correct. One of the best ways to do that is to use Miri, an official Rust tool for detecting undefined behavior. Whereas the borrow checker is a static tool that works at compile time, Miri is a dynamic tool that works at runtime. It checks your code by running your program, or its test suite, and detecting when you violate the rules it understands about how Rust should work.

使用 Miri 需要 Rust 的每夜构建版 (nightly build)(我们在附录 G:Rust 的制造过程与 “Nightly Rust”中会更多地讨论它)。你可以通过输入 rustup +nightly component add miri 来同时安装 nightly 版 Rust 和 Miri 工具。这并不会改变你的项目所使用的 Rust 版本;它只是将该工具添加到你的系统中,以便你可以在想要时使用它。你可以通过输入 cargo +nightly miri runcargo +nightly miri test 在项目上运行 Miri。

Using Miri requires a nightly build of Rust (which we talk about more in Appendix G: How Rust is Made and “Nightly Rust”). You can install both a nightly version of Rust and the Miri tool by typing rustup +nightly component add miri. This does not change what version of Rust your project uses; it only adds the tool to your system so you can use it when you want to. You can run Miri on a project by typing cargo +nightly miri run or cargo +nightly miri test.

为了演示这有多大帮助,请考虑当我们对示例 20-7 运行它时会发生什么。

For an example of how helpful this can be, consider what happens when we run it against Listing 20-7.

{{#include ../listings/ch20-advanced-features/listing-20-07/output.txt}}

Miri 正确地警告我们,我们正在将一个整数强制转换为一个指针,这可能是一个问题,但 Miri 无法确定是否存在问题,因为它不知道指针是如何起源的。然后,由于我们有一个悬垂指针,Miri 返回了一个指出示例 20-7 具有未定义行为的错误。多亏了 Miri,我们现在知道存在未定义行为的风险,并且我们可以考虑如何使代码安全。在某些情况下,Miri 甚至可以就如何修复错误提出建议。

Miri correctly warns us that we’re casting an integer to a pointer, which might be a problem, but Miri can’t determine whether a problem exists because it doesn’t know how the pointer originated. Then, Miri returns an error where Listing 20-7 has undefined behavior because we have a dangling pointer. Thanks to Miri, we now know there is a risk of undefined behavior, and we can think about how to make the code safe. In some cases, Miri can even make recommendations about how to fix errors.

Miri 无法捕捉到你在编写不安全代码时可能犯下的所有错误。Miri 是一个动态分析工具,因此它只能捕捉到真正运行的代码的问题。这意味着你需要结合良好的测试技术来使用它,以增加你对自己编写的不安全代码的信心。Miri 也无法涵盖你的代码可能存在不健全性的所有可能方式。

Miri doesn’t catch everything you might get wrong when writing unsafe code. Miri is a dynamic analysis tool, so it only catches problems with code that actually gets run. That means you will need to use it in conjunction with good testing techniques to increase your confidence about the unsafe code you have written. Miri also does not cover every possible way your code can be unsound.

换句话说:如果 Miri “确实” 捕捉到了一个问题,你就知道存在一个 bug,但仅仅因为 Miri “没有” 捕捉到一个 bug,并不意味着不存在问题。不过,它能捕捉到很多问题。尝试在本章的其他不安全代码示例上运行它,看看它会说些什么!

Put another way: If Miri does catch a problem, you know there’s a bug, but just because Miri doesn’t catch a bug doesn’t mean there isn’t a problem. It can catch a lot, though. Try running it on the other examples of unsafe code in this chapter and see what it says!

你可以在 其 GitHub 仓库 了解更多关于 Miri 的信息。

You can learn more about Miri at its GitHub repository.

正确使用不安全代码 (Using Unsafe Code Correctly)

Using Unsafe Code Correctly

使用 unsafe 来使用刚才讨论的五项超能力中的一项并没有错,甚至不被反对,但由于编译器无法帮助维护内存安全,正确编写 unsafe 代码更具挑战性。当你有理由使用 unsafe 代码时,你可以这样做,并且显式的 unsafe 注解使得在问题发生时追踪其源头变得更容易。每当你编写不安全代码时,你都可以使用 Miri 来帮助你更确信你编写的代码遵守了 Rust 的规则。

Using unsafe to use one of the five 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. Whenever you write unsafe code, you can use Miri to help you be more confident that the code you have written upholds Rust’s rules.

为了更深入地探索如何有效地处理不安全 Rust,请阅读 Rust 关于 unsafe 的官方指南 《The Rustonomicon》

For a much deeper exploration of how to work effectively with unsafe Rust, read Rust’s official guide for unsafe, The Rustonomicon.

高级 Traits (Advanced Traits)


x-i18n: generated_at: “2026-03-01T15:00:37Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f544ee583a8c59cfaad510536590be8723547c299c39b44a7bad22b7eb1acdea source_path: ch20-02-advanced-traits.md workflow: 16

高级特征 (Advanced Traits)

我们在第 10 章的“使用特征定义共享行为”部分首次介绍了特征,但我们没有讨论更高级的细节。既然你对 Rust 有了更多了解,我们可以深入研究一下。

We first covered traits in the “Defining Shared Behavior with Traits” section in 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.

使用关联类型定义特征 (Defining Traits with Associated Types)

“关联类型 (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.

一个带有关联类型的特征示例是标准库提供的 Iterator 特征。关联类型名为 Item ,它代表实现 Iterator 特征的类型正在迭代的值的类型。 Iterator 特征的定义如示例 20-13 所示。

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 20-13.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-13/src/lib.rs}}

类型 Item 是一个占位符, next 方法的定义表明它将返回 Option<Self::Item> 类型的值。 Iterator 特征的实现者将为 Item 指定具体类型,并且 next 方法将返回一个包含该具体类型值的 Option

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.

关联类型可能看起来与泛型类似,因为后者允许我们定义一个函数而不指定它可以处理哪些类型。为了研究这两个概念之间的区别,我们将看看在名为 Counter 的类型上实现的 Iterator 特征,该实现指定 Item 类型为 u32

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:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-22-iterator-on-counter/src/lib.rs:ch19}}

这种语法似乎与泛型的语法相当。那么,为什么不直接用泛型来定义 Iterator 特征,如示例 20-14 所示呢?

This syntax seems comparable to that of generics. So, why not just define the Iterator trait with generics, as shown in Listing 20-14?

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-14/src/lib.rs}}

区别在于,当使用泛型时(如示例 20-14),我们必须在每个实现中标注类型;因为我们还可以为 Counter 实现 Iterator<String> 或任何其他类型,所以我们可以为 Counter 实现多个 Iterator 。换句话说,当特征具有泛型参数时,它可以为同一个类型实现多次,每次更改泛型类型参数的具体类型。当我们在 Counter 上使用 next 方法时,我们将不得不提供类型注解,以指明我们想要使用哪个 Iterator 实现。

The difference is that when using generics, as in Listing 20-14, 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.

使用关联类型,我们不需要标注类型,因为我们无法多次为一个类型实现同一个特征。在示例 20-13 的关联类型定义中,我们只能为 Item 的类型选择一次,因为只能有一个 impl Iterator for Counter 。我们不必在每个调用 Counter 上的 next 的地方都指定我们想要一个 u32 值的迭代器。

With associated types, we don’t need to annotate types, because we can’t implement a trait on a type multiple times. In Listing 20-13 with the definition that uses associated types, we can choose what the type of Item will be only once because there can be only one impl Iterator for Counter. We don’t have to specify that we want an iterator of u32 values everywhere we call next on Counter.

关联类型也成为了特征合同的一部分:特征的实现者必须提供一个类型来填补关联类型的占位符。关联类型通常有一个描述该类型将如何使用的名称,并在 API 文档中记录关联类型是一个良好的实践。

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 a good practice.

使用默认泛型参数和运算符重载 (Using Default Generic Parameters and Operator Overloading)

当我们使用泛型类型参数时,我们可以为泛型类型指定一个默认的具体类型。这消除了特征实现者在默认类型可行时指定具体类型的需要。你在使用 <PlaceholderType=ConcreteType> 语法声明泛型类型时指定默认类型。

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.

这种技术非常有用的一个绝佳例子是“运算符重载 (operator overloading)”,即你在特定情况下自定义运算符(如 + )的行为。

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 不允许你创建自己的运算符或重载任意运算符。但你可以通过实现与运算符关联的特征来重载 std::ops 中列出的操作和相应的特征。例如,在示例 20-15 中,我们重载了 + 运算符以将两个 Point 实例相加。我们通过在 Point 结构体上实现 Add 特征来做到这一点。

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 20-15, we overload the + operator to add two Point instances together. We do this by implementing the Add trait on a Point struct.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-15/src/main.rs}}
}

add 方法将两个 Point 实例的 x 值相加,以及两个 Point 实例的 y 值相加,以创建一个新的 PointAdd 特征具有一个名为 Output 的关联类型,它决定了从 add 方法返回的类型。

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 特征内。以下是其定义:

The default generic type in this code is within the Add trait. Here is its definition:

#![allow(unused)]
fn main() {
trait Add<Rhs=Self> {
    type Output;

    fn add(self, rhs: Rhs) -> Self::Output;
}
}

这段代码看起来应该大致熟悉:一个带有一个方法和一个关联类型的特征。新部分是 Rhs=Self :这种语法被称为“默认类型参数 (default type parameters)”。 Rhs 泛型类型参数(“right-hand side” 的缩写)定义了 add 方法中 rhs 参数的类型。如果我们实现 Add 特征时没有为 Rhs 指定具体类型, Rhs 的类型将默认为 Self ,即我们正在实现 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.

当我们为 Point 实现 Add 时,我们使用了 Rhs 的默认值,因为我们想将两个 Point 实例相加。让我们看一个实现 Add 特征的例子,其中我们想要自定义 Rhs 类型而不是使用默认值。

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.

我们有两个结构体, MillimetersMeters ,持有不同单位的值。这种将现有类型薄薄地包装在另一个结构体中的做法被称为“newtype 模式”,我们将在“使用 newtype 模式实现外部特征”一节中进行更详细的描述。我们想要将以毫米为单位的值加到以米为单位的值上,并让 Add 的实现正确执行转换。我们可以为 Millimeters 实现 Add 并将 Meters 作为 Rhs ,如示例 20-16 所示。

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 “Implementing External Traits with the Newtype Pattern” 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 20-16.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-16/src/lib.rs}}

为了将 MillimetersMeters 相加,我们指定 impl Add<Meters> 来设置 Rhs 类型参数的值,而不是使用默认的 Self

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.

你将主要以两种方式使用默认类型参数:

  1. 扩展一个类型而不破坏现有代码
  2. 在大多数用户不需要的特定情况下允许定制

You’ll use default type parameters in two main ways:

  1. To extend a type without breaking existing code
  2. To allow customization in specific cases most users won’t need

标准库的 Add 特征是第二个目的的示例:通常情况下,你会将两个相似的类型相加,但 Add 特征提供了除此之外的定制能力。在 Add 特征定义中使用默认类型参数意味着你大多数时候不必指定额外的参数。换句话说,不需要一点实现样板,使得特征更容易使用。

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.

第一个目的与第二个类似但相反:如果你想向现有特征添加类型参数,你可以给它一个默认值,以允许扩展该特征的功能而不破坏现有的实现代码。

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.

消除同名方法之间的歧义 (Disambiguating Between Identically Named Methods)

Disambiguating Between Identically Named Methods

Rust 并不禁止一个特征拥有与另一个特征的方法同名的方法,也不禁止你在一个类型上实现这两个特征。直接在类型上实现与特征方法同名的方法也是可能的。

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 你想使用哪一个。考虑示例 20-17 中的代码,我们定义了两个特征 PilotWizard ,它们都带有一个名为 fly 的方法。然后我们在一个已经实现了名为 fly 的方法的 Human 类型上实现了这两个特征。每个 fly 方法执行不同的操作。

When calling methods with the same name, you’ll need to tell Rust which one you want to use. Consider the code in Listing 20-17 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-17/src/main.rs:here}}
}

当我们在 Human 实例上调用 fly 时,编译器默认调用直接在类型上实现的方法,如示例 20-18 所示。

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 20-18.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-18/src/main.rs:here}}
}

运行这段代码将打印 *waving arms furiously* ,表明 Rust 直接调用了在 Human 上实现的方法。

Running this code will print *waving arms furiously*, showing that Rust called the fly method implemented on Human directly.

要从 Pilot 特征或 Wizard 特征中调用 fly 方法,我们需要使用更显式的语法来指定我们要的是哪一个 fly 方法。示例 20-19 演示了这种语法。

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 20-19 demonstrates this syntax.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-19/src/main.rs:here}}
}

在方法名称之前指定特征名称向 Rust 澄清了我们要调用哪个 fly 实现。我们也可以写成 Human::fly(&person) ,这与我们在示例 20-19 中使用的 person.fly() 是等效的,但如果不需要消除歧义,这种写法写起来有点长。

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 20-19, but this is a bit longer to write if we don’t need to disambiguate.

运行这段代码会打印以下内容:

{{#include ../listings/ch20-advanced-features/listing-20-19/output.txt}}

因为 fly 方法接收一个 self 参数,如果我们有两个都实现了“同一个特征”的“类型”,Rust 可以根据 self 的类型弄清楚该使用特征的哪个实现。

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.

然而,非方法的关联函数没有 self 参数。当有多个类型或特征定义了具有相同函数名的非方法函数时,除非你使用“完全限定语法 (fully qualified syntax)”,否则 Rust 并不总是知道你指的是哪种类型。例如,在示例 20-20 中,我们为一个动物收容所创建了一个特征,该收容所希望给所有幼犬命名为 Spot。我们创建了一个带有非方法关联函数 baby_nameAnimal 特征。该 Animal 特征在 Dog 结构体上实现,我们也直接在 Dog 上提供了一个非方法关联函数 baby_name

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 20-20, 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-20/src/main.rs}}
}

我们在定义于 Dog 上的 baby_name 关联函数中实现了给所有小狗命名为 Spot 的代码。 Dog 类型也实现了 Animal 特征,该特征描述了所有动物都具有的特征。幼犬被称为 puppies,这在 Dog 上的 Animal 特征实现的 baby_name 函数(与 Animal 特征关联)中有所体现。

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.

main 中,我们调用 Dog::baby_name 函数,它直接调用定义在 Dog 上的关联函数。这段代码打印以下内容:

{{#include ../listings/ch20-advanced-features/listing-20-20/output.txt}}

此输出并不是我们想要的。我们想要调用作为我们在 Dog 上实现的 Animal 特征一部分的 baby_name 函数,以便代码打印出 A baby dog is called a puppy 。我们在示例 20-19 中使用的指定特征名称的技术在这里没有帮助;如果我们把 main 改为示例 20-21 中的代码,我们将得到一个编译错误。

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 that the code prints A baby dog is called a puppy. The technique of specifying the trait name that we used in Listing 20-19 doesn’t help here; if we change main to the code in Listing 20-21, we’ll get a compilation error.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-21/src/main.rs:here}}

因为 Animal::baby_name 没有 self 参数,并且可能有其他类型实现了 Animal 特征,Rust 无法弄清楚我们要的是哪一个 Animal::baby_name 的实现。我们将得到这个编译器错误:

{{#include ../listings/ch20-advanced-features/listing-20-21/output.txt}}

为了消除歧义并告诉 Rust 我们想要使用针对 DogAnimal 实现(而不是针对其他某种类型的 Animal 实现),我们需要使用完全限定语法。示例 20-22 演示了如何使用完全限定语法。

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 20-22 demonstrates how to use fully qualified syntax.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-22/src/main.rs:here}}
}

我们在尖括号内向 Rust 提供了一个类型标注,这表明我们想调用针对 Dog 实现的 Animal 特征中的 baby_name 方法,通过声明我们想在此函数调用中将 Dog 类型视为 Animal 。这段代码现在将打印出我们想要的内容:

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:

{{#include ../listings/ch20-advanced-features/listing-20-22/output.txt}}

通常,完全限定语法的定义如下:

In general, fully qualified syntax is defined as follows:

<Type as Trait>::function(receiver_if_method, next_arg, ...);

对于不是方法的关联函数,将没有 receiver(接收者):只有其他参数列表。你可以在调用函数或方法的任何地方使用完全限定语法。然而,你被允许省略该语法的任何部分,只要 Rust 可以从程序中的其他信息中推断出来。只有在存在多个同名实现且 Rust 需要帮助来识别你想要调用的实现时,你才需要使用这种更冗长的语法。

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.

使用父特征 (Supertraits)

Using Supertraits

有时你可能会编写一个依赖于另一个特征的特征定义:为了让一个类型实现第一个特征,你希望要求该类型同时也实现第二个特征。你会这样做是为了让你的特征定义可以利用第二个特征的关联项。你的特征定义所依赖的那个特征被称为该特征的“父特征 (supertrait)”。

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.

例如,假设我们想制作一个带有 outline_print 方法的 OutlinePrint 特征,该方法将打印一个给定的值,其格式是被括在星号框中。也就是说,给定一个实现了标准库 Display 特征从而得出 (x, y)Point 结构体,当我们对一个 x1y3Point 实例调用 outline_print 时,它应该打印以下内容:

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:

**********
*        *
* (1, 3) *
*        *
**********

outline_print 方法的实现中,我们想要使用 Display 特征的功能。因此,我们需要指定 OutlinePrint 特征仅适用于同样实现了 Display 且能提供 OutlinePrint 所需功能的类型。我们可以在特征定义中通过指定 OutlinePrint: Display 来做到这一点。这种技术类似于向特征添加特征约束。示例 20-23 展示了 OutlinePrint 特征的一个实现。

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 20-23 shows an implementation of the OutlinePrint trait.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-23/src/main.rs:here}}
}

因为我们已经指定 OutlinePrint 需要 Display 特征,所以我们可以使用为任何实现了 Display 的类型自动实现的 to_string 函数。如果我们尝试在不添加冒号并在特征名称后指定 Display 特征的情况下使用 to_string ,我们将得到一个错误,指出在当前作用域内未找到类型 &Self 的名为 to_string 的方法。

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.

让我们看看当我们尝试在一个未实现 Display 的类型(如 Point 结构体)上实现 OutlinePrint 时会发生什么:

Let’s see what happens when we try to implement OutlinePrint on a type that doesn’t implement Display, such as the Point struct:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs:here}}

我们得到了一个错误,指出 Display 是必需的但未实现:

We get an error saying that Display is required but not implemented:

{{#include ../listings/ch20-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt}}

要修复此问题,我们在 Point 上实现 Display 并满足 OutlinePrint 要求的约束,如下所示:

To fix this, we implement Display on Point and satisfy the constraint that OutlinePrint requires, like so:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-03-impl-display-for-point/src/main.rs:here}}
}

然后,为 Point 实现 OutlinePrint 特征将可以成功编译,并且我们可以在 Point 实例上调用 outline_print 以在星号轮廓内显示它。

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.

使用 newtype 模式实现外部特征 (Implementing External Traits with the Newtype Pattern)

Implementing External Traits with the Newtype Pattern

在第 10 章的“在类型上实现特征”一节中,我们提到了孤儿规则,该规则规定只有当特征或类型(或两者)对我们的 crate 是本地的时,我们才被允许在类型上实现该特征。可以使用 newtype 模式绕过此限制,该模式涉及在元组结构体中创建一个新类型。(我们在第 5 章的“使用元组结构体创建不同的类型”部分介绍过元组结构体。)元组结构体将有一个字段,并作为我们想要为其实现特征的类型的薄包装。然后,该包装器类型对我们的 crate 是本地的,我们就可以在包装器上实现该特征了。“Newtype” 是一个起源于 Haskell 编程语言的术语。使用此模式不会产生运行时性能损失,并且包装器类型在编译时会被消除。

In the “Implementing a Trait on a Type” section in Chapter 10, 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, or both, 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 “Creating Different Types with Tuple Structs” section in Chapter 5.) The tuple struct will have one field and be a thin wrapper around the type for which we want to implement a trait. 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.

作为一个例子,假设我们想在 Vec<T> 上实现 Display ,孤儿规则阻止我们直接这样做,因为 Display 特征和 Vec<T> 类型都定义在我们的 crate 之外。我们可以创建一个持有 Vec<T> 实例的 Wrapper 结构体;然后,我们就可以在 Wrapper 上实现 Display 并使用 Vec<T> 的值,如示例 20-24 所示。

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 20-24.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-24/src/main.rs}}
}

Display 的实现使用 self.0 来访问内部的 Vec<T> ,因为 Wrapper 是一个元组结构体,而 Vec<T> 是元组中索引为 0 的项。然后,我们就可以在 Wrapper 上使用 Display 特征的功能了。

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.

使用这种技术的缺点是,由于 Wrapper 是一个新类型,它没有它所持有值的方法。我们将不得不直接在 Wrapper 上实现 Vec<T> 的所有方法,并使这些方法委托给 self.0 ,这将允许我们将 Wrapper 完全视为 Vec<T> 。如果我们希望新类型具有内部类型的每一个方法,那么在 Wrapper 上实现 Deref 特征以返回内部类型会是一个解决方案(我们在第 15 章“像普通引用一样处理智能指针”一节中讨论过实现 Deref 特征)。如果我们不希望 Wrapper 类型具有内部类型的所有方法(例如,为了限制 Wrapper 类型的行为),我们就必须手动实现我们确实想要的方法。

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 on the Wrapper to return the inner type would be a solution (we discussed implementing the Deref trait in the “Treating Smart Pointers Like Regular References” section in Chapter 15). If we didn’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.

即使不涉及特征,这种 newtype 模式也是有用的。让我们切换焦点,看看与 Rust 类型系统交互的一些高级方式。

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.

高级类型 (Advanced Types)


x-i18n: generated_at: “2026-03-01T15:01:14Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 640f8f52f31cf573a6a1f64dbbdebfe7f36f54a3f42a8cf22c42e7658e75960e source_path: ch20-03-advanced-types.md workflow: 16

高级类型 (Advanced Types)

Rust 类型系统有一些我们到目前为止提到过但尚未讨论的特性。我们将从一般性的 newtype 开始讨论,研究为什么它们作为类型很有用。然后,我们将转向类型别名,这是一个类似于 newtype 但语义略有不同的特性。我们还将讨论 ! 类型和动态大小类型。

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 they 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.

使用 Newtype 模式实现类型安全和抽象 (Type Safety and Abstraction with the Newtype Pattern)

本节假设你已经阅读了前面的“使用 Newtype 模式实现外部特征”一节。Newtype 模式除了我们已经讨论过的任务外,还对其他任务非常有用,包括静态地强制执行值永远不会混淆,并指示值的单位。你在示例 20-16 中看到了使用 newtype 指示单位的例子:回想一下, MillimetersMeters 结构体在 newtype 中包装了 u32 值。如果我们编写了一个带有 Millimeters 类型参数的函数,我们就无法编译一个由于疏忽而尝试使用 Meters 或普通 u32 值调用该函数的程序。

This section assumes you’ve read the earlier section “Implementing External Traits with the Newtype Pattern”. 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 20-16: 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 wouldn’t be able to compile a program that accidentally tried to call that function with a value of type Meters or a plain u32.

我们也可以使用 newtype 模式来抽象掉一个类型的一些实现细节:新类型可以暴露一个与其内部私有类型的 API 不同的公有 API。

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 还可以隐藏内部实现。例如,我们可以提供一个 People 类型来包装一个存储人的 ID 及其姓名的 HashMap<i32, String> 。使用 People 的代码将仅与我们提供的公有 API 交互,例如向 People 集合添加姓名字符串的方法;那段代码不需要知道我们在内部为姓名分配了一个 i32 ID。Newtype 模式是实现封装以隐藏实现细节的一种轻量级方式,我们在第 18 章的“隐藏实现细节的封装”部分讨论过这一点。

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 in Chapter 18.

类型同义词和类型别名 (Type Synonyms and Type Aliases)

Rust 提供了声明“类型别名 (type alias)”的能力,为现有类型赋予另一个名称。为此,我们使用 type 关键字。例如,我们可以像这样为 i32 创建别名 Kilometers

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-04-kilometers-alias/src/main.rs:here}}
}

现在别名 Kilometersi32 的一个“同义词 (synonym)”;与我们在示例 20-16 中创建的 MillimetersMeters 类型不同, Kilometers 不是一个单独的、新的类型。具有 Kilometers 类型的值将被视为与 i32 类型的值相同:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-04-kilometers-alias/src/main.rs:there}}
}

因为 Kilometersi32 是相同的类型,我们可以将这两种类型的值相加,也可以将 Kilometers 值传递给接收 i32 参数的函数。然而,使用这种方法,我们无法获得前面讨论过的 newtype 模式所带来的类型检查优势。换句话说,如果我们在某处混淆了 Kilometersi32 的值,编译器将不会给出错误。

Because Kilometers and i32 are the same type, we can add values of both types and 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.

类型同义词的主要用例是减少重复。例如,我们可能有一个冗长的类型,如下所示:

Box<dyn Fn() + Send + 'static>

在函数签名和作为类型注解在代码各处编写这个冗长的类型可能会让人厌烦且容易出错。想象一下,如果一个项目中充满了像示例 20-25 中那样的代码。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-25/src/main.rs:here}}
}

类型别名通过减少重复来使这段代码更易于管理。在示例 20-26 中,我们为这个冗长的类型引入了一个名为 Thunk 的别名,并可以用较短的别名 Thunk 替换该类型的所有用法。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-26/src/main.rs:here}}
}

这段代码读写起来都容易得多!为类型别名选择一个有意义的名称也可以帮助传达你的意图( 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).

类型别名也经常与 Result<T, E> 类型一起使用,以减少重复。考虑标准库中的 std::io 模块。I/O 操作经常返回 Result<T, E> 来处理操作失败的情况。该库有一个 std::io::Error 结构体,代表所有可能的 I/O 错误。 std::io 中的许多函数都将返回 Result<T, E> ,其中 Estd::io::Error ,例如 Write 特征中的这些函数:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-05-write-trait/src/lib.rs}}

Result<..., Error> 被重复了很多次。因此, std::io 有这个类型别名声明:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-06-result-alias/src/lib.rs:here}}

因为这个声明位于 std::io 模块中,我们可以使用完全限定别名 std::io::Result<T> ;也就是说,这是一个将 E 填充为 std::io::ErrorResult<T, E>Write 特征的函数签名最终看起来像这样:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-06-result-alias/src/lib.rs:there}}

类型别名在两个方面提供了帮助:它使代码更易于编写,“并且”它在整个 std::io 中为我们提供了一个一致的接口。因为它是一个别名,所以它只是另一个 Result<T, E> ,这意味着我们可以对其使用任何适用于 Result<T, E> 的方法,以及像 ? 运算符这样的特殊语法。

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.

永不返回的 Never 类型 (The Never Type That Never Returns)

Rust 有一种特殊的类型,名为 ! ,在类型理论术语中被称为“空类型 (empty type)”,因为它没有任何值。我们更喜欢称之为“永不类型 (never type)”,因为它在函数永远不会返回时充当返回类型的占位。这里有一个例子:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-07-never-type/src/lib.rs:here}}

这段代码读作“函数 bar 永不返回 (returns never)”。永不返回的函数被称为“发散函数 (diverging functions)”。我们无法创建 ! 类型的值,所以 bar 永远不可能返回。

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.

但是对于一种你永远无法创建其值的类型,它有什么用处呢?回想一下示例 2-5 中的代码,它是数字猜谜游戏的一部分;我们在示例 20-27 中重现了其中一小部分。

{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs:ch19}}

当时,我们跳过了这段代码中的一些细节。在第 6 章的match 控制流结构”一节中,我们讨论了 match 分支必须全部返回相同的类型。所以,例如,以下代码就无法工作:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-08-match-arms-different-types/src/main.rs:here}}

这段代码中 guess 的类型必须既是整数“又是”字符串,而 Rust 要求 guess 只有一个类型。那么, continue 返回什么呢?在示例 20-27 中,我们怎么被允许从一个分支返回 u32 而另一个分支以 continue 结束呢?

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 20-27?

正如你可能已经猜到的, continue 具有一个 ! 值。也就是说,当 Rust 计算 guess 的类型时,它查看两个 match 分支,前者具有 u32 的值,而后者具有 ! 的值。因为 ! 永远不会有值,所以 Rust 决定 guess 的类型是 u32

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.

描述这种行为的正式方式是, ! 类型表达式可以被强制转换为任何其他类型。我们被允许以此 match 分支以 continue 结束,是因为 continue 不返回值;相反,它将控制权移回到循环顶部,所以在 Err 的情况下,我们从未给 guess 分配值。

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.

Never 类型对 panic! 宏也很有用。回想一下我们在 Option<T> 值上调用以产生一个值或引发恐慌的 unwrap 函数,其定义如下:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-09-unwrap-definition/src/lib.rs:here}}

在这段代码中,发生了与示例 20-27 中的 match 相同的事情:Rust 看到 val 具有类型 T ,而 panic! 具有类型 ! ,因此整个 match 表达式的结果是 T 。这段代码之所以能工作,是因为 panic! 不产生值;它结束了程序。在 None 的情况下,我们不会从 unwrap 返回值,因此这段代码是有效的。

In this code, the same thing happens as in the match in Listing 20-27: 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.

最后一个具有 ! 类型的表达式是一个循环:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-10-loop-returns-never/src/main.rs:here}}

在这里,循环永远不会结束,所以 ! 是表达式的值。然而,如果我们包含了一个 break ,这就不是真的了,因为循环会在执行到 break 时终止。

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.

动态大小类型与 Sized 特征 (Dynamically Sized Types and the Sized Trait)

Rust 需要知道其类型的某些细节,例如为特定类型的值分配多少空间。这使得其类型系统的一个角落起初有些令人困惑:即“动态大小类型 (dynamically sized types)”的概念。这些类型有时被称为 DST 或“不定大小类型 (unsized types)”,它们让我们能编写使用那些只有在运行时才能知道其大小的值的代码。

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.

让我们深入了解一下名为 str 的动态大小类型的细节,我们在整本书中都一直在使用它。没错,不是 &str ,而是 str 本身,是一个 DST。在许多情况下,例如存储用户输入的文本时,我们直到运行时才能知道字符串有多长。这意味着我们不能创建一个 str 类型的变量,也不能接收一个 str 类型的参数。考虑以下无法工作的代码:

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. In many cases, such as when storing text entered by a user, we can’t know how long the string is until runtime. That means 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:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-11-cant-create-str/src/main.rs:here}}

Rust 需要知道为特定类型的任何值分配多少内存,并且一个类型的所有值必须使用相同数量的内存。如果 Rust 允许我们编写这段代码,这两个 str 值将需要占用相同数量的空间。但它们有不同的长度: s1 需要 12 字节的存储空间,而 s2 需要 15 字节。这就是为什么无法创建一个持有动态大小类型的变量。

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.

那么,我们该怎么办呢?在这种情况下,你已经知道答案了:我们将 s1s2 的类型设为字符串切片 ( &str ) 而不是 str 。回想第 4 章“字符串切片”一节可知,切片数据结构仅存储起始位置和切片的长度。所以,虽然 &T 是一个存储 T 所在内存地址的单一值,但字符串切片是“两个”值: str 的地址及其长度。因此,我们可以在编译时知道字符串切片值的大小:它是 usize 长度的两倍。也就是说,我们始终知道字符串切片的大小,无论它引用的字符串有多长。通常,这就是在 Rust 中使用动态大小类型的方式:它们有一个存储动态信息大小的额外元数据片段。动态大小类型的金科玉律是:我们必须始终将动态大小类型的值放在某种指针之后。

So, what do we do? In this case, you already know the answer: We make the type of s1 and s2 string slice (&str) rather than str. Recall from the “String Slices” section in Chapter 4 that the slice data structure only stores the starting position and the length of the slice. So, although &T is a single value that stores the memory address of where the T is located, a string slice is two values: the address of the str and its length. As such, we can know the size of a string slice value at compile time: It’s twice the length of a usize. That is, we always know the size of a string slice, 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.

我们可以将 str 与各种指针结合使用:例如 Box<str>Rc<str> 。实际上,你以前见过这种情况,但是使用的是另一种动态大小类型:特征。每一个特征都是一个我们可以通过使用特征名称来引用的动态大小类型。在第 18 章的“使用特征对象实现不同类型间的抽象行为”一节中,我们提到为了将特征用作特征对象,我们必须将它们放在指针之后,例如 &dyn TraitBox<dyn Trait>Rc<dyn Trait> 也可以)。

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 the “Using Trait Objects to Abstract over Shared Behavior” section in Chapter 18, 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).

为了处理 DST,Rust 提供了 Sized 特征来确定一个类型的大小在编译时是否已知。对于大小在编译时已知的所有事物,此特征会自动实现。此外,Rust 会隐式地为每个泛型函数添加一个 Sized 约束。也就是说,像这样的泛型函数定义:

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:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs}}

实际上被视为好像我们编写了这段代码:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs}}

默认情况下,泛型函数将仅适用于在编译时具有已知大小的类型。然而,你可以使用以下特殊语法来放宽此限制:

{{#rustdoc_include ../listings/ch20-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs}}

?Sized 上的特征约束意味着“ T 可能是也可能不是 Sized ”,这种记法覆盖了泛型类型在编译时必须具有已知大小的默认设置。具有此含义的 ?Trait 语法仅对 Sized 可用,不对任何其他特征可用。

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.

还要注意,我们将 t 参数的类型从 T 更改为 &T 。因为该类型可能不是 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.

接下来,我们将讨论函数和闭包!

Next, we’ll talk about functions and closures!

高级函数与闭包 (Advanced Functions and Closures)


x-i18n: generated_at: “2026-03-01T15:01:52Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: cfbbca957a9a1657c75e2d61a511643b06ffffbbb57da101ab2da6eccca97bf4 source_path: ch20-04-advanced-functions-and-closures.md workflow: 16

高级函数与闭包 (Advanced Functions and Closures)

本节探讨一些与函数和闭包相关的高级特性,包括函数指针和返回闭包。

This section explores some advanced features related to functions and closures, including function pointers and returning closures.

函数指针 (Function Pointers)

我们讨论过如何向函数传递闭包;你也可以向函数传递常规函数!当你想要传递一个已经定义的函数而不是定义一个新的闭包时,这种技术很有用。函数强制转换为类型 fn (带有小写字母 f),不要与 Fn 闭包特征混淆。 fn 类型被称为“函数指针 (function pointer)”。通过函数指针传递函数将允许你将函数作为其他函数的参数。

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.

指定参数为函数指针的语法与闭包类似,如示例 20-28 所示,我们定义了一个在其参数上加 1 的函数 add_one 。函数 do_twice 接收两个参数:一个指向任何接收 i32 参数并返回 i32 的函数的函数指针,以及一个 i32 值。 do_twice 函数调用函数 f 两次,将 arg 值传递给它,然后将两次函数调用的结果相加。 main 函数使用参数 add_one5 调用 do_twice

The syntax for specifying that a parameter is a function pointer is similar to that of closures, as shown in Listing 20-28, where we’ve defined a function add_one that adds 1 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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-28/src/main.rs}}
}

这段代码打印 The answer is: 12 。我们指定 do_twice 中的参数 f 是一个 fn ,它接收一个 i32 类型的参数并返回一个 i32 。然后我们可以在 do_twice 的主体中调用 f 。在 main 中,我们可以将函数名 add_one 作为第一个参数传递给 do_twice

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.

与闭包不同, fn 是一个类型而不是一个特征,所以我们直接指定 fn 作为参数类型,而不是声明一个以 Fn 特征之一作为特征约束的泛型类型参数。

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.

函数指针实现了所有三种闭包特征( FnFnMutFnOnce ),这意味着你始终可以将函数指针作为参数传递给期望闭包的函数。最好使用泛型类型和其中一种闭包特征编写函数,以便你的函数可以接收函数或闭包。

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 that your functions can accept either functions or closures.

即便如此,一个你只想接收 fn 而不接收闭包的例子是与没有闭包的外部代码交互时:C 函数可以接收函数作为参数,但 C 没有闭包。

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.

作为一个既可以使用内联定义的闭包也可以使用命名函数的例子,让我们看看标准库中 Iterator 特征提供的 map 方法的一种用法。要使用 map 方法将一个数字向量转换为字符串向量,我们可以使用闭包,如示例 20-29 所示。

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 method to turn a vector of numbers into a vector of strings, we could use a closure, as in Listing 20-29.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-29/src/main.rs:here}}
}

或者我们可以将一个函数命名为 map 的参数,而不是使用闭包。示例 20-30 展示了这看起来是什么样子的。

Or we could name a function as the argument to map instead of the closure. Listing 20-30 shows what this would look like.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-30/src/main.rs:here}}
}

注意我们必须使用在“高级特征”一节中讨论过的完全限定语法,因为有多个名为 to_string 的可用函数。

Note that we must use the fully qualified syntax that we talked about in the “Advanced Traits” section because there are multiple functions available named to_string.

这里,我们使用的是 ToString 特征中定义的 to_string 函数,标准库已经为任何实现了 Display 的类型实现了该特征。

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.

回想第 6 章“枚举值”一节,我们定义的每个枚举变体的名称也成为了一个初始化函数。我们可以将这些初始化函数作为实现了闭包特征的函数指针来使用,这意味着我们可以将初始化函数指定为接收闭包的方法的参数,如示例 20-31 所示。

Recall from the “Enum Values” section in 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, as seen in Listing 20-31.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-31/src/main.rs:here}}
}

这里,我们通过使用 Status::Value 的初始化函数,为调用 map 的范围内的每个 u32 值创建 Status::Value 实例。有些人更喜欢这种风格,有些人则更喜欢使用闭包。它们会编译成相同的代码,所以请使用对你来说更清晰的风格。

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.

返回闭包 (Returning Closures)

闭包由特征表示,这意味着你不能直接返回闭包。在大多数你可能想返回特征的情况下,你可以改用实现该特征的具体类型作为函数的返回值。然而,对于闭包,你通常不能这样做,因为它们没有可返回的具体类型;例如,如果闭包从其作用域中捕获了任何值,你就不被允许使用函数指针 fn 作为返回类型。

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 usually 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 if the closure captures any values from its scope, for example.

相反,你通常会使用我们在第 10 章学到的 impl Trait 语法。你可以返回任何函数类型,使用 FnFnOnceFnMut 。例如,示例 20-32 中的代码将可以正常编译。

Instead, you will normally use the impl Trait syntax we learned about in Chapter 10. You can return any function type, using Fn, FnOnce, and FnMut. For example, the code in Listing 20-32 will compile just fine.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-32/src/lib.rs}}
}

然而,正如我们在第 13 章“推断并标注闭包类型”一节中所指出的,每个闭包也是它自己独特的类型。如果你需要处理具有相同签名但不同实现的多个函数,你将需要为它们使用特征对象。考虑一下如果你编写像示例 20-33 所示的代码会发生什么。

However, as we noted in the “Inferring and Annotating Closure Types” section in Chapter 13, each closure is also its own distinct type. If you need to work with multiple functions that have the same signature but different implementations, you will need to use a trait object for them. Consider what happens if you write code like that shown in Listing 20-33.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-33/src/main.rs}}

这里我们有两个函数, returns_closurereturns_initialized_closure ,它们都返回 impl Fn(i32) -> i32 。注意它们返回的闭包是不同的,尽管它们实现了相同的类型。如果我们尝试编译这个,Rust 会让我们知道它行不通:

Here we have two functions, returns_closure and returns_initialized_closure, which both return impl Fn(i32) -> i32. Notice that the closures that they return are different, even though they implement the same type. If we try to compile this, Rust lets us know that it won’t work:

{{#include ../listings/ch20-advanced-features/listing-20-33/output.txt}}

错误消息告诉我们,每当我们返回一个 impl Trait 时,Rust 都会创建一个唯一的“不透明类型 (opaque type)”,即一个我们无法查看 Rust 为我们构造的细节的类型,我们也无法猜测 Rust 将生成的类型来自己编写。所以,即使这些函数返回了实现相同特征 Fn(i32) -> i32 的闭包,Rust 为每个函数生成的不透明类型也是不同的。(这类似于 Rust 为不同的异步块产生不同的具体类型,即使它们具有相同的输出类型,正如我们在第 17 章Pin 类型与 Unpin 特征”中看到的。)我们已经多次见过这个问题的解决方案:我们可以使用特征对象,如示例 20-34 所示。

The error message tells us that whenever we return an impl Trait, Rust creates a unique opaque type, a type where we cannot see into the details of what Rust constructs for us, nor can we guess the type Rust will generate to write ourselves. So, even though these functions return closures that implement the same trait, Fn(i32) -> i32, the opaque types Rust generates for each are distinct. (This is similar to how Rust produces different concrete types for distinct async blocks even when they have the same output type, as we saw in “The Pin Type and the Unpin Trait” in Chapter 17.) We have seen a solution to this problem a few times now: We can use a trait object, as in Listing 20-34.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-34/src/main.rs:here}}
}

这段代码可以正常编译。关于特征对象的更多信息,请参阅第 18 章“使用特征对象实现不同类型间的抽象行为”一节。

This code will compile just fine. For more about trait objects, refer to the section “Using Trait Objects To Abstract over Shared Behavior” in Chapter 18.

接下来,让我们看看宏!

Next, let’s look at macros!

宏 (Macros)


x-i18n: generated_at: “2026-03-01T15:03:30Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 403fb3429c4c11ef118a31477aae7ce73cfcc0a2776289faac1a797c7f57f173 source_path: ch20-05-macros.md workflow: 16

宏 (Macros)

我们在整本书中都使用了像 println! 这样的宏,但我们还没有全面探讨什么是宏以及它是如何工作的。术语“宏 (macro)”指的是 Rust 中的一系列特性——使用 macro_rules! 的声明式宏以及三种过程式宏:

The term macro refers to a family of features in Rust—declarative macros with macro_rules! and three kinds of procedural macros:

  • 自定义 #[derive] 宏,用于指定在结构体和枚举上使用 derive 属性时添加的代码

  • 属性类宏 (Attribute-like macros),定义可用于任何项的自定义属性

  • 函数类宏 (Function-like macros),看起来像函数调用,但对其参数指定的 token 进行操作

  • Custom #[derive] macros that specify code added with the derive attribute used on structs and enums

  • 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)

从根本上说,宏是一种编写编写其他代码的代码的方式,这被称为“元编程 (metaprogramming)”。在附录 C 中,我们讨论了 derive 属性,它会为你生成各种特征的实现。我们在书中也使用了 println!vec! 宏。所有这些宏都会“展开 (expand)”,以产生比你手动编写的代码更多的代码。

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.

元编程对于减少你必须编写和维护的代码量非常有用,这也是函数的作用之一。然而,宏具有一些函数所不具备的额外能力。

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 have.

一个函数签名必须声明函数拥有的参数数量和类型。另一方面,宏可以接收可变数量的参数:我们可以用一个参数调用 println!("hello") ,或者用两个参数调用 println!("hello {}", name) 。此外,宏是在编译器解释代码含义之前展开的,因此宏可以,例如,在给定类型上实现一个特征。函数则不行,因为它是在运行时调用的,而特征需要在编译时实现。

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.

实现宏而不是函数的缺点是,宏定义比函数定义更复杂,因为你是在编写编写 Rust 代码的 Rust 代码。由于这种间接性,宏定义通常比函数定义更难阅读、理解和维护。

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.

宏和函数之间的另一个重要区别是,你必须在文件中调用宏“之前”定义它们或将其引入作用域,而函数则可以定义在任何地方并在任何地方调用。

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 for General Metaprogramming)

Rust 中使用最广泛的宏形式是“声明式宏 (declarative macro)”。这些宏有时也被称为“示例宏 (macros by example)”、“ macro_rules! 宏”或简称为“宏”。其核心在于,声明式宏允许你编写类似于 Rust match 表达式的东西。正如第 6 章中所讨论的, match 表达式是控制结构,它接收一个表达式,将表达式的结果值与模式进行比较,然后运行与匹配模式关联的代码。宏也将一个值与和特定代码关联的模式进行比较:在这种情况下,该值是传递给宏的字面 Rust 源代码;模式与该源代码的结构进行比较;并且与每个模式关联的代码在匹配时会替换传递给宏的代码。这一切都发生在编译期间。

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 resultant 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.

要定义一个宏,你需要使用 macro_rules! 结构。让我们通过查看 vec! 宏是如何定义的来探索如何使用 macro_rules! 。第 8 章涵盖了我们如何使用 vec! 宏来创建一个带有特定值的新向量。例如,以下宏创建了一个包含三个整数的新向量:

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:

#![allow(unused)]
fn main() {
let v: Vec<u32> = vec![1, 2, 3];
}

我们也可以使用 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.

示例 20-35 显示了一个略微简化的 vec! 宏定义。

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-35/src/lib.rs}}

注意:标准库中 vec! 宏的实际定义包含预先分配正确内存量的代码。为了使示例更简单,我们在这里不包含该代码,它是一种优化。

Note: The actual definition of the vec! macro in the standard library includes code to pre-allocate the correct amount of memory up front. That code is an optimization that we don’t include here, to make the example simpler.

#[macro_export] 注解表明,每当定义该宏的 crate 被引入作用域时,该宏就应该是可用的。如果没有这个注解,该宏就无法被引入作用域。

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_rules! 和我们要定义的宏的名称(“不带”感叹号)开始宏定义。名称(在此例中为 vec )后面跟着表示宏定义主体的花括号。

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.

vec! 主体中的结构类似于 match 表达式的结构。这里我们有一个带有模式 ( $( $x:expr ),* ) 的分支,后跟 => 和与此模式关联的代码块。如果模式匹配,关联的代码块将被发出。由于这是此宏中唯一的模式,因此只有一种有效的匹配方式;任何其他模式都会导致错误。更复杂的宏将具有多个分支。

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.

宏定义中有效的模式语法与第 19 章中介绍的模式语法不同,因为宏模式是针对 Rust 代码结构而不是值进行匹配的。让我们逐步了解示例 20-35 中模式片段的含义;有关完整的宏模式语法,请参阅 Rust 参考手册

Valid pattern syntax in macro definitions is different from the pattern syntax covered in Chapter 19 because macro patterns are matched against Rust code structure rather than values. Let’s walk through what the pattern pieces in Listing 20-35 mean; for the full macro pattern syntax, see the Rust Reference.

首先,我们使用一对圆括号包裹整个模式。我们使用美元符号 ( $ ) 在宏系统中声明一个变量,该变量将包含匹配模式的 Rust 代码。美元符号清楚地表明这是一个宏变量,而不是常规的 Rust 变量。接下来是一对圆括号,它捕获与圆括号内的模式匹配的值,以便在替换代码中使用。在 $() 内部是 $x:expr ,它匹配任何 Rust 表达式并赋予该表达式名称 $x

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.

紧随 $() 后的逗号表明,匹配 $() 中代码的代码每个实例之间必须出现一个字面量逗号分隔符字符。 * 指定该模式匹配零个或多个其前面的内容。

The comma following $() indicates that a literal comma separator character must appear between each instance of the code that matches the code in $(). The * specifies that the pattern matches zero or more of whatever precedes the *.

当我们用 vec![1, 2, 3]; 调用此宏时, $x 模式与三个表达式 123 匹配了三次。

When we call this macro with vec![1, 2, 3];, the $x pattern matches three times with the three expressions 1, 2, and 3.

现在让我们看看与此分支关联的代码体中的模式: $()* 内部的 temp_vec.push() 为匹配模式中 $() 的每个部分生成零次或多次,具体取决于模式匹配的次数。 $x 被替换为匹配到的每个表达式。当我们用 vec![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:

{
    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.

要了解更多关于如何编写宏的信息,请查阅在线文档或其他资源,例如由 Daniel Keep 发起并由 Lukas Wirth 继续维护的《Rust 宏小书》 (The Little Book of Rust Macros)

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.

用于从属性生成代码的过程式宏 (Procedural Macros for Generating Code from Attributes)

宏的第二种形式是过程式宏,它表现得更像函数(并且是一种过程类型)。“过程式宏 (Procedural macros)”接收一段代码作为输入,对该代码进行操作,并产生一段代码作为输出,而不是像声明式宏那样与模式匹配并用其他代码替换代码。过程式宏有三种:自定义 derive 、属性类和函数类,它们的工作方式都类似。

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.

在创建过程式宏时,其定义必须驻留在具有特殊 crate 类型的主 crate 中。这是由于我们希望将来能消除的复杂技术原因。在示例 20-36 中,我们展示了如何定义一个过程式宏,其中 some_attribute 是使用特定宏变体的占位符。

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 20-36, we show how to define a procedural macro, where some_attribute is a placeholder for using a specific macro variety.

use proc_macro::TokenStream;

#[some_attribute]
pub fn some_name(input: TokenStream) -> TokenStream {
}

定义过程式宏的函数接收一个 TokenStream 作为输入,并产生一个 TokenStream 作为输出。 TokenStream 类型由 Rust 附带的 proc_macro crate 定义,并代表一个 token 序列。这是宏的核心:宏操作的源代码组成了输入 TokenStream ,宏生成的代码则是输出 TokenStream 。该函数还附带一个属性,指定我们正在创建哪种过程式宏。我们可以在同一个 crate 中拥有多种过程式宏。

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.

让我们看看不同种类的过程式宏。我们将从自定义 derive 宏开始,然后解释使其他形式不同的微小差异。

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.

自定义 derive 宏 (Custom derive Macros)

让我们创建一个名为 hello_macro 的 crate,它定义了一个名为 HelloMacro 的特征,带有一个名为 hello_macro 的关联函数。与其让我们的用户为他们的每个类型都实现 HelloMacro 特征,不如提供一个过程式宏,以便用户可以使用 #[derive(HelloMacro)] 标注他们的类型,从而获得 hello_macro 函数的默认实现。默认实现将打印 Hello, Macro! My name is TypeName! ,其中 TypeName 是定义此特征的类型的名称。换句话说,我们将编写一个 crate,使另一位程序员能够使用我们的 crate 编写像示例 20-37 这样的代码。

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 that 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 20-37 using our crate.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-37/src/main.rs}}

完成后,这段代码将打印 Hello, Macro! My name is Pancakes! 。第一步是创建一个新的库 crate,如下所示:

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:

$ cargo new hello_macro --lib

接下来,在示例 20-38 中,我们将定义 HelloMacro 特征及其关联函数。

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-38/hello_macro/src/lib.rs}}

我们有了一个特征及其函数。在这一点上,我们的 crate 用户可以通过手动实现该特征来达到预期的功能,如示例 20-39 所示。

We have a trait and its function. At this point, our crate user could implement the trait to achieve the desired functionality, as in Listing 20-39.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-39/pancakes/src/main.rs}}

然而,他们需要为每个想要与 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 函数提供默认实现来打印实现该特征的类型名称:Rust 没有反射能力,因此它无法在运行时查找类型的名称。我们需要一个宏在编译时生成代码。

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.

下一步是定义过程式宏。在撰写本文时,过程式宏需要放在它们自己的 crate 中。最终,这种限制可能会被解除。构建 crate 和宏 crate 的惯例是:对于一个名为 foo 的 crate,自定义 derive 过程式宏 crate 被称为 foo_derive 。让我们在我们的 hello_macro 项目中开始一个新的名为 hello_macro_derive 的 crate:

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:

$ cargo new hello_macro_derive --lib

我们的两个 crate 紧密相关,因此我们在 hello_macro 目录内创建过程式宏 crate。如果我们更改了 hello_macro 中的特征定义,我们就也必须更改 hello_macro_derive 中过程式宏的实现。这两个 crate 需要分别发布,并且使用这些 crate 的程序员需要将它们都作为依赖项添加并都引入作用域。我们本可以让 hello_macro crate 使用 hello_macro_derive 作为依赖项并重新导出过程式宏代码。然而,我们构建项目的方式使得程序员即使不想用 derive 功能也可以使用 hello_macro

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.

我们需要将 hello_macro_derive crate 声明为过程式宏 crate。我们还将需要来自 synquote crate 的功能(你稍后会看到),所以我们需要将它们添加为依赖项。将以下内容添加到 hello_macro_deriveCargo.toml 文件中:

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:

{{#include ../listings/ch20-advanced-features/listing-20-40/hello_macro/hello_macro_derive/Cargo.toml:6:12}}

要开始定义过程式宏,请将示例 20-40 中的代码放入 hello_macro_derive crate 的 src/lib.rs 文件中。注意,在我们为 impl_hello_macro 函数添加定义之前,这段代码无法编译。

To start defining the procedural macro, place the code in Listing 20-40 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.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-40/hello_macro/hello_macro_derive/src/lib.rs}}

注意我们将代码拆分成了负责解析 TokenStreamhello_macro_derive 函数和负责转换语法树的 impl_hello_macro 函数:这使得编写过程式宏更方便。外层函数(在此例中为 hello_macro_derive )中的代码对于你见到或创建的几乎每个过程式宏 crate 都是相同的。你在内层函数(在此例中为 impl_hello_macro )的主体中指定的代码将根据过程式宏的目的而有所不同。

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.

我们引入了三个新 crate: proc_macrosynquoteproc_macro crate 随 Rust 附带,所以我们不需要在 Cargo.toml 的依赖项中添加它。 proc_macro crate 是编译器的 API,它允许我们从代码中读取和操作 Rust 代码。

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.

syn crate 将字符串形式的 Rust 代码解析为我们可以对其执行操作的数据结构。 quote crate 则将 syn 数据结构转回为 Rust 代码。这些 crate 使得解析我们要处理的任何 Rust 代码都简单得多:为 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.

当库的用户在类型上指定 #[derive(HelloMacro)] 时, hello_macro_derive 函数将被调用。这是因为我们在这里为 hello_macro_derive 函数标注了 proc_macro_derive 并指定了名称 HelloMacro ,它与我们的特征名称匹配;这是大多数过程式宏遵循的惯例。

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.

hello_macro_derive 函数首先将 inputTokenStream 转换为一个随后我们可以解释并对其执行操作的数据结构。这就是 syn 发挥作用的地方。 syn 中的 parse 函数接收一个 TokenStream 并返回一个代表已解析 Rust 代码的 DeriveInput 结构体。示例 20-41 显示了从解析 struct Pancakes; 字符串中获得的 DeriveInput 结构体的相关部分。

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 20-41 shows the relevant parts of the DeriveInput struct we get from parsing the struct Pancakes; string.

DeriveInput {
    // --snip--

    ident: Ident {
        ident: "Pancakes",
        span: #0 bytes(95..103)
    },
    data: Struct(
        DataStruct {
            struct_token: Struct,
            fields: Unit,
            semi_token: Some(
                Semi
            )
        }
    )
}

该结构体的字段显示,我们解析的 Rust 代码是一个具有 ident (标识符,意指名称)为 Pancakes 的单元结构体。该结构体上还有更多字段用于描述各种 Rust 代码;查看 syn 关于 DeriveInput 的文档以获取更多信息。

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.

稍后我们将定义 impl_hello_macro 函数,我们将在这里构建我们想要包含的新 Rust 代码。但在我们开始之前,请注意我们 derive 宏的输出也是一个 TokenStream 。返回的 TokenStream 会被添加到我们的 crate 用户编写的代码中,所以当他们编译他们的 crate 时,他们将获得我们在修改后的 TokenStream 中提供的额外功能。

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.

你可能已经注意到我们调用了 unwrap ,以便在 syn::parse 函数调用失败时导致 hello_macro_derive 函数发生恐慌。过程式宏在错误时发生恐慌是必要的,因为 proc_macro_derive 函数必须返回 TokenStream 而不是 Result 才能符合过程式宏 API。我们通过使用 unwrap 简化了这个示例;在生产代码中,你应该通过使用 panic!expect 提供关于出了什么问题的更具体错误消息。

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.

既然我们已经有了将标注过的 Rust 代码从 TokenStream 转换为 DeriveInput 实例的代码,让我们生成在标注过的类型上实现 HelloMacro 特征的代码,如示例 20-42 所示。

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 20-42.

{{#rustdoc_include ../listings/ch20-advanced-features/listing-20-42/hello_macro/hello_macro_derive/src/lib.rs:here}}

我们使用 ast.ident 获取一个包含标注类型名称(标识符)的 Ident 结构体实例。示例 20-41 中的结构体显示,当我们在示例 20-37 中的代码上运行 impl_hello_macro 函数时,得到的 identident 字段值为 "Pancakes" 。因此,示例 20-42 中的 name 变量将包含一个 Ident 结构体实例,当打印时,它将是字符串 "Pancakes" ,即示例 20-37 中结构体的名称。

We get an Ident struct instance containing the name (identifier) of the annotated type using ast.ident. The struct in Listing 20-41 shows that when we run the impl_hello_macro function on the code in Listing 20-37, the ident we get will have the ident field with a value of "Pancakes". Thus, the name variable in Listing 20-42 will contain an Ident struct instance that, when printed, will be the string "Pancakes", the name of the struct in Listing 20-37.

quote! 宏让我们能够定义我们想要返回的 Rust 代码。编译器期望的东西与 quote! 宏执行的直接结果不同,所以我们需要将其转换为 TokenStream 。我们通过调用 into 方法来实现这一点,该方法会消耗这个中间表示并返回所需 TokenStream 类型的值。

The quote! macro lets us define the Rust code that we want to return. The compiler expects something different from 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! 宏还提供了一些非常酷的模板机制:我们可以输入 #namequote! 会将其替换为 name 变量中的值。你甚至可以执行一些类似于常规宏工作方式的重复。查看 quote crate 的文档以获得详尽的介绍。

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.

我们希望我们的过程式宏为用户标注的类型生成一个我们的 HelloMacro 特征实现,我们可以通过使用 #name 获得该类型。特征实现具有一个函数 hello_macro ,其函数体包含我们要提供的功能:打印 Hello, Macro! My name is 及其后标注类型的名称。

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.

这里使用的 stringify! 宏是内置在 Rust 中的。它接收一个 Rust 表达式,例如 1 + 2 ,并在编译时将该表达式转换为字符串字面量,例如 "1 + 2" 。这与 format!println! 不同,后者是在运行时对表达式求值然后再将结果转换为 String 的宏。由于 #name 输入可能是一个要逐字打印的表达式,所以我们使用 stringify! 。使用 stringify! 还可以通过在编译时将 #name 转换为字符串字面量来节省一次内存分配。

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 from format! or println!, which are macros that 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.

此时, cargo build 应该在 hello_macrohello_macro_derive 中都能成功完成。让我们将这些 crate 连接到示例 20-37 中的代码,看看过程式宏的实际应用!在你的 projects 目录下使用 cargo new pancakes 创建一个新的二进制项目。我们需要在 pancakes crate 的 Cargo.toml 中将 hello_macrohello_macro_derive 添加为依赖项。如果你正在将你的 hello_macrohello_macro_derive 版本发布到 crates.io,它们将是常规依赖项;如果不是,你可以按照如下方式指定它们为 path 依赖项:

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 20-37 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:

{{#include ../listings/ch20-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml:6:8}}

将示例 20-37 中的代码放入 src/main.rs ,运行 cargo run :它应该打印出 Hello, Macro! My name is Pancakes! 。来自过程式宏的 HelloMacro 特征实现被包含进来了,而无需 pancakes crate 自行实现; #[derive(HelloMacro)] 添加了该特征实现。

Put the code in Listing 20-37 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.

接下来,让我们探索其他种类的过程式宏与自定义 derive 宏有何不同。

Next, let’s explore how the other kinds of procedural macros differ from custom derive macros.

属性类宏 (Attribute-Like Macros)

Attribute-Like Macros

属性类宏与自定义 derive 宏类似,但它们不为 derive 属性生成代码,而是允许你创建新的属性。它们也更灵活: derive 仅适用于结构体和枚举;属性则可以应用于其他项,例如函数。这里有一个使用属性类宏的例子。假设你有一个名为 route 的属性,在使用 Web 应用程序框架时用于标注函数:

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:

#[route(GET, "/")]
fn index() {

这个 #[route] 属性将由框架定义为一个过程式宏。宏定义函数的签名看起来像这样:

#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {

在这里,我们有两个 TokenStream 类型的参数。第一个用于属性的内容:即 GET, "/" 部分。第二个是属性附加到的项的主体:在此例中是 fn index() {} 及其函数体的其余部分。

Here, we have two parameters of type TokenStream. The first is for the contents of the attribute: the GET, "/" part. 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.

除此之外,属性类宏的工作方式与自定义 derive 宏相同:你创建一个 proc-macro 类型的 crate,并实现一个生成你想要代码的函数!

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!

函数类宏 (Function-Like Macros)

Function-Like Macros

函数类宏定义的宏看起来像函数调用。与 macro_rules! 宏类似,它们比函数更灵活;例如,它们可以接收未知数量的参数。然而, macro_rules! 宏只能使用我们在前面的“用于通用元编程的声明式宏”一节中讨论过的类 match 语法来定义。函数类宏接收一个 TokenStream 参数,它们的定义就像其他两种类型的过程式宏一样,使用 Rust 代码来操作该 TokenStream 。函数类宏的一个例子是 sql! 宏,它可能会像这样被调用:

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 only be defined using the match-like syntax we discussed in the “Declarative Macros for General Metaprogramming” section 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:

let sql = sql!(SELECT * FROM posts WHERE id=1);

这个宏将解析其中的 SQL 语句并检查它是否在语法上正确,这比 macro_rules! 宏能做的处理复杂得多。 sql! 宏将被如下定义:

#[proc_macro]
pub fn sql(input: TokenStream) -> TokenStream {

此定义类似于自定义 derive 宏的签名:我们接收圆括号内的 token 并返回我们想要生成的代码。

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)

呼!现在你的工具箱中已经拥有了一些你可能不会经常使用,但会在非常特殊的情况下用到的 Rust 特性。我们介绍了几个复杂的主题,这样当你以后在错误消息建议或他人的代码中遇到它们时,你将能够识别这些概念和语法。请将本章作为指引你寻找解决方案的参考。

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 people’s code, you’ll be able to recognize these concepts and syntax. Use this chapter as a reference to guide you to solutions.

接下来,我们将把整本书中讨论过的一切付诸实践,再做一个项目!

Next, we’ll put everything we’ve discussed throughout the book into practice and do one more project!

结业项目:构建多线程 Web 服务器 (Final Project: Building a Multithreaded Web Server)


x-i18n: generated_at: “2026-03-01T15:03:42Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 2a0e9ef98893b80390e0c428b109ad90bc200852c6bc0151144bcdf6843f2abd source_path: ch21-00-final-project-a-web-server.md workflow: 16

最终项目:构建一个多线程 Web 服务器 (Final Project: Building a Multithreaded Web Server)

Final Project: Building a Multithreaded Web Server

这是一段漫长的旅程,但我们已经到达了本书的尽头。在本章中,我们将一起再构建一个项目,以演示我们在最后几章中涵盖的一些概念,并回顾一些早期的课程。

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.

作为我们的最终项目,我们将制作一个会说 “Hello!” 的 Web 服务器,在 Web 浏览器中看起来如图 21-1 所示。

For our final project, we’ll make a web server that says “Hello!” and looks like Figure 21-1 in a web browser.

以下是我们构建 Web 服务器的计划:

  1. 了解一些关于 TCP 和 HTTP 的知识。
  2. 在套接字 (socket) 上监听 TCP 连接。
  3. 解析少量的 HTTP 请求。
  4. 创建一个正式的 HTTP 响应。
  5. 使用线程池提高服务器的吞吐量。

Here is our plan for building the web server:

  1. Learn a bit about TCP and HTTP.
  2. Listen for TCP connections on a socket.
  3. Parse a small number of HTTP requests.
  4. Create a proper HTTP response.
  5. Improve the throughput of our server with a thread pool.
浏览器访问地址 127.0.0.1:8080 的截图,显示了一个包含文本内容 “Hello! Hi from Rust” 的网页

图 21-1:我们最后的共享项目

在我们开始之前,我们应该提到两个细节。首先,我们将使用的方法并不是用 Rust 构建 Web 服务器的最佳方式。社区成员已经在 crates.io 上发布了许多生产级的 crate,它们提供了比我们将要构建的更完整的 Web 服务器和线程池实现。然而,我们在本章的意图是帮助你学习,而不是走捷径。因为 Rust 是一门系统编程语言,我们可以选择想要使用的抽象级别,并且可以深入到比其他语言中可能或实际可行的更低级别。

Before we get started, we should mention two details. First, 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 at 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.

其次,我们在这里不会使用 async 和 await。构建线程池本身就是一个足够大的挑战,不需要再加上构建一个异步运行时!然而,我们会注意到 async 和 await 可能适用于我们在本章中将看到的一些相同问题。归根结底,正如我们在第 17 章中指出的,许多异步运行时都使用线程池来管理它们的工作。

Second, we will not be using async and await here. Building a thread pool is a big enough challenge on its own, without adding in building an async runtime! However, we will note how async and await might be applicable to some of the same problems we will see in this chapter. Ultimately, as we noted back in Chapter 17, many async runtimes use thread pools for managing their work.

因此,我们将手动编写基础的 HTTP 服务器和线程池,以便你可以了解你将来可能使用的 crate 背后的通用思想和技术。

We’ll therefore write the basic HTTP server and thread pool manually so that you can learn the general ideas and techniques behind the crates you might use in the future.

构建单线程 Web 服务器 (Building a Single-Threaded Web Server)


x-i18n: generated_at: “2026-03-01T15:05:23Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 899122a94a52c45f4c934e1967460a36c7803fcc1b6a933b790e610a9376f04f source_path: ch21-01-single-threaded.md workflow: 16

构建单线程 Web 服务器 (Building a Single-Threaded Web Server)

Building a Single-Threaded Web Server

我们将从让一个单线程 Web 服务器运行起来开始。在开始之前,让我们快速概览一下构建 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 服务器涉及的两个主要协议是“超文本传输协议 (Hypertext Transfer Protocol, HTTP)”和“传输控制协议 (Transmission Control Protocol, TCP)”。这两个协议都是“请求-响应 (request-response)”协议,这意味着“客户端 (client)”发起请求,“服务器 (server)”监听请求并向客户端提供响应。这些请求和响应的内容由协议定义。

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.

TCP 是描述信息如何从一台服务器到达另一台服务器的底层协议,但它不指定该信息是什么。HTTP 构建在 TCP 之上,通过定义请求和响应的内容。技术上可以将 HTTP 与其他协议配合使用,但在绝大多数情况下,HTTP 通过 TCP 发送数据。我们将处理 TCP 和 HTTP 请求及响应的原始字节。

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 连接 (Listening to the TCP Connection)

Listening to the TCP Connection

我们的 Web 服务器需要监听 TCP 连接,所以这是我们要处理的第一部分。标准库提供了一个 std::net 模块,可以让我们做到这一点。让我们以通常的方式创建一个新项目:

$ cargo new hello
     Created binary (application) `hello` project
$ cd hello

现在在 src/main.rs 中输入示例 21-1 中的代码作为开始。这段代码将在本地地址 127.0.0.1:7878 上监听传入的 TCP 流。当它获得传入流时,它将打印 Connection established!

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-01/src/main.rs}}
}

使用 TcpListener ,我们可以在地址 127.0.0.1:7878 上监听 TCP 连接。在地址中,冒号前面的部分是代表你计算机的 IP 地址(这在每台计算机上都是一样的,不代表作者的特定计算机), 7878 是端口。我们选择这个端口有两个原因:HTTP 通常不在此端口上被接受,所以我们的服务器不太可能与你机器上运行的任何其他 Web 服务器冲突,而且 7878 是在电话上输入的 rust

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.

在这种情况下, bind 函数的工作方式类似于 new 函数,它将返回一个新的 TcpListener 实例。该函数之所以被称为 bind ,是因为在网络中,连接到要监听的端口被称为“绑定到端口 (binding to a port)”。

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 函数返回一个 Result<T, E> ,这表明绑定可能会失败,例如,如果我们运行程序的两个实例,从而有两个程序在监听同一个端口。因为我们编写基本服务器只是为了学习目的,所以我们不会担心处理这些类型的错误;相反,如果发生错误,我们使用 unwrap 来停止程序。

The bind function returns a Result<T, E>, which indicates that it’s possible for binding to fail, 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.

TcpListener 上的 incoming 方法返回一个迭代器,它给我们提供一系列流(更具体地说是 TcpStream 类型的流)。单个“流 (stream)”代表客户端与服务器之间的开启连接。“连接 (Connection)”是完整请求和响应过程的名称,其中客户端连接到服务器,服务器生成响应,然后服务器关闭连接。因此,我们将从 TcpStream 中读取以查看客户端发送了什么,然后将我们的响应写入流中以将数据发送回客户端。总的来说,这个 for 循环将轮流处理每个连接,并产生一系列流供我们处理。

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. 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.

目前,我们对流的处理包括在流发生任何错误时调用 unwrap 来终止程序;如果没有发生错误,程序就会打印一条消息。我们将在下一个列表中为成功的情况添加更多功能。当我们有一个客户端连接到服务器时,我们可能会从 incoming 方法收到错误,原因是由于我们实际上并没有遍历连接。相反,我们是在遍历“连接尝试 (connection attempts)”。连接可能由于多种原因而不成功,其中许多与操作系统有关。例如,许多操作系统支持的同时打开的连接数是有限制的;超过该数量的新连接尝试将产生错误,直到一些打开的连接被关闭。

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.

让我们尝试运行这段代码!在终端中调用 cargo run ,然后在 Web 浏览器中加载 127.0.0.1:7878 。浏览器应该显示诸如“连接重置 (Connection reset)”之类的错误消息,因为服务器当前没有发回任何数据。但当你查看终端时,你应该看到浏览器连接到服务器时打印的几条消息!

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!

     Running `target/debug/hello`
Connection established!
Connection established!
Connection established!

有时你会看到为一个浏览器请求打印多条消息;原因可能是浏览器正在请求页面,同时也正在请求其他资源,比如出现在浏览器标签页中的 favicon.ico 图标。

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.

也可能是浏览器正尝试多次连接服务器,因为服务器没有返回任何数据。当 stream 超出作用域并在循环结束时被丢弃时,连接作为 drop 实现的一部分而被关闭。浏览器有时会通过重试来处理关闭的连接,因为问题可能是暂时的。

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.

浏览器有时也会在不发送任何请求的情况下向服务器开启多个连接,以便如果它们稍后“确实”发送请求,那些请求可以更快地发生。发生这种情况时,我们的服务器将看到每个连接,无论该连接上是否有任何请求。例如,许多版本的基于 Chrome 的浏览器都会这样做;你可以通过使用私密浏览模式或使用不同的浏览器来禁用该优化。

Browsers also sometimes open multiple connections to the server without sending any requests so that if they do later send requests, those requests can happen more quickly. When this occurs, our server will see each connection, regardless of whether there are any requests over that connection. Many versions of Chrome-based browsers do this, for example; you can disable that optimization by using private browsing mode or using a different browser.

重要的因素是我们已经成功获得了一个 TCP 连接的句柄!

The important factor is that we’ve successfully gotten a handle to a TCP connection!

请记住,当你运行完特定版本的代码时,按 ctrl-C 停止程序。然后,在每次进行代码更改后,通过调用 cargo run 命令重新启动程序,以确保你运行的是最新的代码。

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.

读取请求 (Reading the Request)

Reading the Request

让我们实现从浏览器读取请求的功能!为了将首先获取连接和随后对连接执行某些操作的关注点分离,我们将开启一个用于处理连接的新函数。在这个新的 handle_connection 函数中,我们将从 TCP 流中读取数据并打印它,以便我们可以看到从浏览器发送的数据。将代码更改为如示例 21-2 所示。

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 that we can see the data being sent from the browser. Change the code to look like Listing 21-2.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-02/src/main.rs}}
}

我们将 std::io::BufReaderstd::io::prelude 引入作用域,以获得允许我们从流中读取和向流中写入的特征和类型。在 main 函数的 for 循环中,我们现在不再打印表示连接已建立的消息,而是调用新的 handle_connection 函数并将 stream 传递给它。

We bring std::io::BufReader and std::io::prelude 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.

handle_connection 函数中,我们创建了一个包装了 stream 引用的新 BufReader 实例。 BufReader 通过为我们管理 std::io::Read 特征方法的调用来添加缓冲。

In the handle_connection function, we create a new BufReader instance that wraps a reference to the stream. The BufReader adds buffering by managing calls to the std::io::Read trait methods for us.

我们创建一个名为 http_request 的变量,用于收集浏览器发送到我们服务器的请求行。我们通过添加 Vec<_> 类型注解来指明我们想在一个向量中收集这些行。

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.

BufReader 实现了 std::io::BufRead 特征,该特征提供了 lines 方法。 lines 方法通过在每当看到换行符字节时分割数据流,来返回 Result<String, std::io::Error> 的迭代器。为了获得每个 String ,我们 mapunwrap 每个 Result 。如果数据不是有效的 UTF-8,或者从流中读取时出现问题, Result 可能会是一个错误。同样地,生产级程序应该更优雅地处理这些错误,但为了简单起见,我们选择在错误情况下停止程序。

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.

浏览器通过连续发送两个换行符来表示 HTTP 请求的结束,所以为了从流中获取一个请求,我们读取每一行直到我们得到一个空字符串。一旦我们将这些行收集到向量中,我们就使用漂亮的调试格式打印出它们,以便我们可以查看浏览器正在向我们的服务器发送什么指令。

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 that we can take a look at the instructions the web browser is sending to our server.

让我们试一下这段代码!启动程序并再次在 Web 浏览器中发起请求。请注意,我们在浏览器中仍然会得到一个错误页面,但我们程序在终端中的输出现在看起来将类似于:

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` profile [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",
]

根据你的浏览器,你可能会得到略有不同的输出。既然我们正在打印请求数据,我们就可以通过查看请求第一行中 GET 之后的路径,来理解为什么我们会从一个浏览器请求中得到多个连接。如果重复的连接都在请求 / ,我们就知道浏览器在重复尝试获取 / ,因为它没有从我们的程序中得到响应。

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.

让我们分解一下这个请求数据,以理解浏览器对我们程序的要求。

Let’s break down this request data to understand what the browser is asking of our program.

更仔细地观察 HTTP 请求 (Looking More Closely at an HTTP Request)

HTTP 是一种基于文本的协议,一个请求采用如下格式:

HTTP is a text-based protocol, and a request takes this format:

Method Request-URI HTTP-Version CRLF
headers CRLF
message-body

第一行是“请求行 (request line)”,它保存着关于客户端请求内容的信息。请求行的第一部分指示所使用的“方法 (method)”,例如 GETPOST ,它描述了客户端如何发起此请求。我们的客户端使用了 GET 请求,这意味着它正在请求信息。

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.

请求行的下一部分是 / ,它指示客户端请求的“统一资源标识符 (URI)”:URI 几乎(但不完全)等同于“统一资源定位符 (URL)”。URI 和 URL 之间的区别对于我们在本章中的目的并不重要,但 HTTP 规范使用了术语 URI ,所以我们可以在脑海中直接将 URL 替换为 URI

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.

最后一部分是客户端使用的 HTTP 版本,然后请求行以 CRLF 序列结束。( CRLF 代表 carriage return(回车)和 line feed(换行),这些是打字机时代的术语!)CRLF 序列也可以写成 \r\n ,其中 \r 是回车, \n 是换行。 CRLF 序列将请求行与请求数据的其余部分隔开。请注意,当打印 CRLF 时,我们看到的是一个新行的开始,而不是 \r\n

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.

查看我们目前运行程序收到的请求行数据,我们看到 GET 是方法, / 是请求 URI,而 HTTP/1.1 是版本。

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.

在请求行之后,从 Host: 开始的剩余行是标头 (headers)。 GET 请求没有正文 (body)。

After the request line, the remaining lines starting from Host: onward are headers. GET requests have no body.

尝试从不同的浏览器发起请求,或者请求不同的地址(如 127.0.0.1:7878/test),来看看请求数据是如何变化的。

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.

既然我们知道了浏览器在请求什么,让我们发回一些数据!

Now that we know what the browser is asking for, let’s send back some data!

编写响应 (Writing a Response)

Writing a Response

我们将实现针对客户端请求发送数据的响应。响应具有以下格式:

Responses have the following format:

HTTP-Version Status-Code Reason-Phrase CRLF
headers CRLF
message-body

第一行是“状态行 (status line)”,包含响应中使用的 HTTP 版本、汇总请求结果的数字状态代码,以及提供状态代码文本描述的原因短语 (reason phrase)。在 CRLF 序列之后是任何标头、另一个 CRLF 序列以及响应的正文。

The first line is a status line that contains the HTTP version used in the reason-phrase, 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 1.1 版本、状态代码为 200、原因短语为 OK、无标头、无正文的响应示例:

Here is an example response that uses HTTP version 1.1 and has a status code of 200, an OK reason phrase, no headers, and no body:

HTTP/1.1 200 OK\r\n\r\n

状态代码 200 是标准的成功响应。这段文本是一个极其微小的成功 HTTP 响应。让我们将其写入流,作为我们对成功请求的响应!从 handle_connection 函数中,移除打印请求数据的 println! ,并替换为示例 21-3 中的代码。

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 21-3.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-03/src/main.rs:here}}
}

第一行新定义了持有成功消息数据的 response 变量。然后,我们在 response 上调用 as_bytes 将字符串数据转换为字节。 stream 上的 write_all 方法接收一个 &[u8] 并直接将这些字节通过连接发送。因为 write_all 操作可能会失败,所以我们照例对任何错误结果使用 unwrap 。同样地,在实际应用程序中,你应该在这里添加错误处理。

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.

做了这些更改后,让我们运行我们的代码并发起一个请求。我们不再向终端打印任何数据,所以除了 Cargo 的输出外,你不会看到任何输出。当你在 Web 浏览器中加载 127.0.0.1:7878 时,你应该会得到一个空白页面而不是一个错误。你刚刚手写了接收 HTTP 请求并发送响应的代码!

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 handcoded receiving an HTTP request and sending a response!

返回真正的 HTML (Returning Real HTML)

Returning Real HTML

让我们实现返回不仅仅是一个空白页面的功能。在项目根目录下创建一个新文件 hello.html ,不要放在 src 目录下。你可以输入任何你想要的 HTML;示例 21-4 显示了一种可能性。

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 21-4 shows one possibility.

{{#include ../listings/ch21-web-server/listing-21-05/hello.html}}

这是一个带有标题和一些文本的最小 HTML5 文档。为了在收到请求时从服务器返回此内容,我们将如示例 21-5 所示修改 handle_connection ,以读取 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 21-5 to read the HTML file, add it to the response as a body, and send it.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-05/src/main.rs:here}}
}

我们在 use 语句中添加了 fs ,以便将标准库的文件系统模块引入作用域。将文件内容读取为字符串的代码看起来应该很熟悉;我们在示例 12-4 中为我们的 I/O 项目读取文件内容时使用过它。

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 when we read the contents of a file for our I/O project in Listing 12-4.

接下来,我们使用 format! 将文件内容作为成功响应的正文。为了确保 HTTP 响应有效,我们添加了 Content-Length 标头,它被设置为响应正文的大小——在此例中即为 hello.html 的大小。

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.

使用 cargo run 运行此代码并在浏览器中加载 127.0.0.1:7878 ;你应该看到渲染出的 HTML!

Run this code with cargo run and load 127.0.0.1:7878 in your browser; you should see your HTML rendered!

目前,我们忽略了 http_request 中的请求数据,只是无条件地发回 HTML 文件的内容。这意味着如果你在浏览器中尝试请求 127.0.0.1:7878/something-else ,你仍然会得到这个相同的 HTML 响应。目前,我们的服务器非常受限,并没有做大多数 Web 服务器所做的事情。我们希望根据请求自定义我们的响应,并且只针对对 / 的规范请求发回 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 /.

验证请求并选择性响应 (Validating the Request and Selectively Responding)

Validating the Request and Selectively Responding

现在,无论客户端请求什么,我们的 Web 服务器都会返回文件中的 HTML。让我们添加一个功能,在返回 HTML 文件之前检查浏览器是否正在请求 / ,如果浏览器请求其他任何内容,则返回错误。为此我们需要修改 handle_connection ,如示例 21-6 所示。这段新代码将接收到的请求内容与我们已知的对 / 的请求的样子进行比对,并添加 ifelse 块以区别对待请求。

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 to return an error if the browser requests anything else. For this we need to modify handle_connection, as shown in Listing 21-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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-06/src/main.rs:here}}
}

我们只打算看 HTTP 请求的第一行,所以不再将整个请求读入向量,而是调用 next 从迭代器中获取第一项。第一个 unwrap 处理 Option ,如果迭代器没有项则停止程序。第二个 unwrap 处理 Result ,其效果与示例 21-2 中添加的 map 里的 unwrap 相同。

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 21-2.

接下来,我们检查 request_line 以查看它是否等于指向 / 路径的 GET 请求行。如果是, if 块将返回我们 HTML 文件的内容。

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 请求,则意味着我们收到了一些其他请求。我们稍后会向 else 块添加代码以响应所有其他请求。

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.

现在运行这段代码并请求 127.0.0.1:7878 ;你应该会得到 hello.html 中的 HTML。如果你发起任何其他请求,例如 127.0.0.1:7878/something-else ,你将得到一个连接错误,就像你在运行示例 21-1 和示例 21-2 中的代码时看到的那样。

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 21-1 and Listing 21-2.

现在让我们将示例 21-7 中的代码添加到 else 块中,以返回状态代码为 404 的响应,这表明未找到请求的内容。我们还将返回一些用于在浏览器中渲染的 HTML,向终端用户指示该响应。

Now let’s add the code in Listing 21-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.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-07/src/main.rs:here}}
}

在这里,我们的响应有一个状态代码为 404 且原因短语为 NOT FOUND 的状态行。响应的正文将是 404.html 文件中的 HTML。你需要在 hello.html 旁边创建一个 404.html 文件作为错误页面;同样,你可以随意使用任何 HTML,或使用示例 21-8 中的示例 HTML。

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 21-8.

{{#include ../listings/ch21-web-server/listing-21-07/404.html}}

做了这些更改后,再次运行你的服务器。请求 127.0.0.1:7878 应该返回 hello.html 的内容,而任何其他请求(如 127.0.0.1:7878/foo )应该返回来自 404.html 的错误 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.

重构 (Refactoring)

Refactoring

目前, ifelse 块中有很多重复:它们都在读取文件并将文件内容写入流。唯一的区别是状态行和文件名。让我们通过将这些差异提取到独立的 ifelse 语句中来使代码更简洁,从而将状态行和文件名的值分配给变量;然后我们就可以在读取文件和写入响应的代码中无条件地使用这些变量。示例 21-9 显示了替换掉庞大的 ifelse 块后的生成代码。

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 21-9 shows the resultant code after replacing the large if and else blocks.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-09/src/main.rs:here}}
}

现在, ifelse 块仅在一个元组中返回适当的状态行和文件名值;然后我们使用解构,通过 let 语句中的模式将这两个值分配给 status_linefilename ,正如第 19 章中所讨论的那样。

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 19.

以前重复的代码现在位于 ifelse 块之外,并使用 status_linefilename 变量。这使得更容易看到两种情况之间的差异,并意味着如果我们想更改文件读取和响应写入的工作方式,我们只需要在一个地方更新代码。示例 21-9 中代码的行为将与示例 21-7 中的相同。

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 21-9 will be the same as that in Listing 21-7.

太棒了!我们现在拥有一个约 40 行 Rust 代码的简单 Web 服务器,它对一个请求返回一页内容,对所有其他请求返回 404 响应。

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.

目前,我们的服务器在单线程中运行,这意味着它一次只能服务一个请求。让我们通过模拟一些慢速请求来研究这为什么会成为一个问题。然后,我们将修复它,以便我们的服务器可以同时处理多个请求。

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 that our server can handle multiple requests at once.

从单线程到多线程服务器 (From Single-Threaded to Multithreaded Server)


x-i18n: generated_at: “2026-03-01T15:06:51Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: ea94b0a16b87464290058c5c650d4e859d3d5d796af955742068a915ee97cd14 source_path: ch21-02-multithreaded.md workflow: 16

从单线程服务器到多线程服务器 (From a Single-Threaded to a Multithreaded Server)

目前,服务器会轮流处理每个请求,这意味着在第一个连接处理完毕之前,它不会处理第二个连接。如果服务器收到的请求越来越多,这种串行执行的效率会越来越低。如果服务器收到一个处理时间很长的请求,后续请求必须等待该长请求完成,即使新请求可以很快处理完毕。我们需要修复这个问题,但首先让我们看看实际存在的问题。

Right now, the server will process each request in turn, meaning it won’t process a second connection until the first connection 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)

我们将观察慢速处理请求如何影响对我们当前服务器实现的其他请求。示例 21-10 实现了对 /sleep 请求的处理,并带有一个模拟的慢速响应,该响应会导致服务器在响应前休眠五秒。

We’ll look at how a slowly processing request can affect other requests made to our current server implementation. Listing 21-10 implements handling a request to /sleep with a simulated slow response that will cause the server to sleep for five seconds before responding.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-10/src/main.rs:here}}
}

既然我们有了三种情况,我们将 if 切换为了 match 。我们需要显式地匹配 request_line 的切片来与字符串字面量值进行模式匹配; match 不会像相等方法那样进行自动引用和解引用。

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.

第一个分支与示例 21-9 中的 if 块相同。第二个分支匹配对 /sleep 的请求。收到该请求后,服务器将在渲染成功 HTML 页面之前休眠五秒。第三个分支与示例 21-9 中的 else 块相同。

The first arm is the same as the if block from Listing 21-9. The second arm matches a request to /sleep. When that request is received, the server will sleep for five seconds before rendering the successful HTML page. The third arm is the same as the else block from Listing 21-9.

你可以看到我们的服务器是多么原始:真正的库会以更简洁的方式处理多个请求的识别!

You can see how primitive our server is: Real libraries would handle the recognition of multiple requests in a much less verbose way!

使用 cargo run 启动服务器。然后,开启两个浏览器窗口:一个访问 http://127.0.0.1:7878 ,另一个访问 http://127.0.0.1:7878/sleep 。如果你像之前一样多次输入 / URI,你会看到它响应很快。但如果你输入 /sleep 然后加载 / ,你会看到 / 一直等待,直到 sleep 休眠了整整五秒后才加载。

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 five seconds before loading.

有多种技术可以用来避免请求积压在慢速请求之后,包括像我们在第 17 章中那样使用异步;我们要实现的一种技术是线程池 (thread pool)。

There are multiple techniques we could use to avoid requests backing up behind a slow request, including using async as we did Chapter 17; the one we’ll implement is a thread pool.

使用线程池提高吞吐量 (Improving Throughput with a Thread Pool)

“线程池 (thread pool)”是一组已生成且正在等待处理任务的线程。当程序收到新任务时,它会将池中的一个线程分配给该任务,由该线程处理任务。池中剩余的线程可用于处理在第一个线程处理期间进来的任何其他任务。当第一个线程处理完任务后,它会返回到空闲线程池中,准备处理新任务。线程池允许你并发处理连接,从而提高服务器的吞吐量。

A thread pool is a group of spawned threads that are ready and waiting 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.

我们将把池中的线程数量限制在一个较小的数字,以保护我们免受 DoS 攻击;如果我们的程序为每个进来的请求都创建一个新线程,那么有人对我们的服务器发起 1000 万个请求,就可能会耗尽我们服务器的所有资源并导致请求处理陷入停滞,从而造成严重破坏。

We’ll limit the number of threads in the pool to a small number to protect us from 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 wreak havoc by using up all our server’s resources and grinding the processing of requests to a halt.

因此,我们将让固定数量的线程在池中等待,而不是生成无限量的线程。进来的请求被发送到池中进行处理。池将维护一个进来的请求队列。池中的每个线程将从这个队列中弹出一个请求,处理该请求,然后再向队列索要另一个请求。有了这种设计,我们可以并发处理多达 N 个请求,其中 N 是线程数量。如果每个线程都在响应一个长时间运行的请求,后续请求仍然可以在队列中积压,但我们在达到那一点之前增加了可以处理的长时间运行请求的数量。

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.

这种技术只是提高 Web 服务器吞吐量的众多方法之一。你可能还会探索其他选项,如 fork/join 模型、单线程异步 I/O 模型和多线程异步 I/O 模型。如果你对这个话题感兴趣,可以阅读更多关于其他解决方案的信息并尝试实现它们;使用 Rust 这样的低级语言,所有这些选项都是可能的。

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, and the multithreaded 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.

在开始实现线程池之前,让我们谈谈使用池应该是什么样子的。当你尝试设计代码时,先编写客户端接口可以帮助指导你的设计。以你想要调用代码的方式来构建代码的 API;然后在该结构内实现功能,而不是先实现功能然后再设计公共 API。

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 that 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.

类似于我们在第 12 章的项目中使用测试驱动开发的方式,我们在这里将使用“编译器驱动开发”。我们将编写调用所需函数的代码,然后根据编译器的错误来确定我们接下来应该更改什么以使代码正常工作。然而,在这样做之前,我们将探索一下不打算作为起点的技术。

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.

为每个请求生成一个线程 (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.

示例 21-11 显示了对 main 进行的更改,以便在 for 循环内生成一个新线程来处理每个流。

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/listing-21-11/src/main.rs:here}}
}

正如你在第 16 章学到的, thread::spawn 将创建一个新线程,然后在该新线程中运行闭包中的代码。如果你运行这段代码并在浏览器中加载 /sleep ,然后在另外两个浏览器标签页中加载 / ,你确实会看到对 / 的请求不必等待 /sleep 完成。然而,正如我们提到的,这最终会使系统崩溃,因为你会无限制地创建新线程。

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.

你可能还记得第 17 章提到过,这正是 async 和 await 大显身手的情况!在我们构建线程池时请记住这一点,并思考使用异步时情况会有什么不同或相同。

You may also recall from Chapter 17 that this is exactly the kind of situation where async and await really shine! Keep that in mind as we build the thread pool and think about how things would look different or the same with async.

创建有限数量的线程 (Creating a Finite Number of Threads)

我们希望我们的线程池以类似的、熟悉的模式工作,这样从线程切换到线程池就不需要对使用我们 API 的代码进行大幅改动。示例 21-12 展示了我们要用来代替 thread::spawnThreadPool 结构体的假设接口。

We want our thread pool to work in a similar, familiar way so that switching from threads to a thread pool doesn’t require large changes to the code that uses our API. Listing 21-12 shows the hypothetical interface for a ThreadPool struct we want to use instead of thread::spawn.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-12/src/main.rs:here}}

我们使用 ThreadPool::new 来创建一个具有可配置线程数量(在此例中为四个)的新线程池。然后,在 for 循环中, pool.execute 具有与 thread::spawn 类似的接口,它接收一个池应该为每个流运行的闭包。我们需要实现 pool.execute ,使其接收闭包并将其交给池中的一个线程运行。这段代码目前还无法编译,但我们将尝试这样做,以便编译器能指导我们如何修复它。

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 that the pool should run for each stream. We need to implement pool.execute so that 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 that the compiler can guide us in how to fix it.

使用编译器驱动开发构建 ThreadPool (Building ThreadPool Using Compiler-Driven Development)

src/main.rs 进行示例 21-12 中的更改,然后让我们使用来自 cargo check 的编译器错误来驱动我们的开发。这是我们得到的第一个错误:

Make the changes in Listing 21-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:

{{#include ../listings/ch21-web-server/listing-21-12/output.txt}}

太好了!这个错误告诉我们我们需要一个 ThreadPool 类型或模块,所以我们现在构建一个。我们的 ThreadPool 实现将独立于 Web 服务器正在执行的工作。因此,让我们将 hello crate 从二进制 crate 切换为库 crate,以持有我们的 ThreadPool 实现。切换到库 crate 后,我们也可以将独立的线程池库用于任何我们想使用线程池完成的工作,而不仅仅是用于服务 Web 请求。

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.

创建一个包含以下内容的 src/lib.rs 文件,这是我们目前能拥有的 ThreadPool 结构体的最简单定义:

Create a src/lib.rs file that contains the following, which is the simplest definition of a ThreadPool struct that we can have for now:

{{#rustdoc_include ../listings/ch21-web-server/no-listing-01-define-threadpool-struct/src/lib.rs}}

然后,编辑 main.rs 文件,通过在 src/main.rs 顶部添加以下代码,将 ThreadPool 从库 crate 引入作用域:

Then, edit the main.rs file to bring ThreadPool into scope from the library crate by adding the following code to the top of src/main.rs:

{{#rustdoc_include ../listings/ch21-web-server/no-listing-01-define-threadpool-struct/src/main.rs:here}}

这段代码仍然无法运行,但让我们再次检查以获得我们需要解决的下一个错误:

This code still won’t work, but let’s check it again to get the next error that we need to address:

{{#include ../listings/ch21-web-server/no-listing-01-define-threadpool-struct/output.txt}}

这个错误表明接下来我们需要为 ThreadPool 创建一个名为 new 的关联函数。我们也知道 new 需要有一个可以接收 4 作为参数的参数,并应返回一个 ThreadPool 实例。让我们实现具有这些特征的最简单的 new 函数:

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:

{{#rustdoc_include ../listings/ch21-web-server/no-listing-02-impl-threadpool-new/src/lib.rs}}

我们选择 usize 作为 size 参数的类型,因为我们知道负数的线程数量没有任何意义。我们也知道我们将使用这个 4 作为线程集合中元素的数量,而 usize 类型正是为此设计的,正如在第 3 章“整数类型”一节中所讨论的那样。

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 in Chapter 3.

让我们再次检查代码:

Let’s check the code again:

{{#include ../listings/ch21-web-server/no-listing-02-impl-threadpool-new/output.txt}}

现在的错误发生是因为我们在 ThreadPool 上没有 execute 方法。回想“创建有限数量的线程”一节,我们决定我们的线程池应该具有类似于 thread::spawn 的接口。此外,我们将实现 execute 函数,使其接收给予它的闭包,并将其交给池中的一个空闲线程来运行。

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 that it takes the closure it’s given and gives it to an idle thread in the pool to run.

我们将定义 ThreadPool 上的 execute 方法以接收一个闭包作为参数。回想第 13 章中的“将捕获的值移出闭包”一节,我们可以接收具有三种不同特征的闭包作为参数: FnFnMutFnOnce 。我们需要决定在这里使用哪种闭包。我们知道最终会执行类似于标准库 thread::spawn 实现的操作,所以我们可以查看 thread::spawn 的签名对其参数有哪些约束。文档向我们展示了以下内容:

We’ll define the execute method on ThreadPool to take a closure as a parameter. Recall from the “Moving Captured Values Out of Closures” 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:

pub fn spawn<F, T>(f: F) -> JoinHandle<T>
    where
        F: FnOnce() -> T,
        F: Send + 'static,
        T: Send + 'static,

F 类型参数是我们在这里关心的; T 类型参数与返回值有关,我们并不关心那个。我们可以看到 spawn 使用了 FnOnce 作为 F 的特征约束。这可能也是我们想要的,因为我们最终会将获得的实参在 execute 中传递给 spawn 。我们可以进一步确信 FnOnce 是我们要使用的特征,因为运行请求的线程只会执行该请求的闭包一次,这与 FnOnce 中的 Once 相匹配。

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 类型参数还具有 Send 特征约束和 'static 生命周期约束,这在我们的情况下很有用:我们需要 Send 来将闭包从一个线程转移到另一个线程,需要 'static 是因为我们不知道线程执行需要多长时间。让我们在 ThreadPool 上创建一个 execute 方法,它将接收一个具有这些约束的类型为 F 的泛型参数:

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:

{{#rustdoc_include ../listings/ch21-web-server/no-listing-03-define-execute/src/lib.rs:here}}

我们仍然在 FnOnce 之后使用 () ,因为这个 FnOnce 代表一个不接收任何参数并返回单元类型 () 的闭包。就像函数定义一样,返回类型可以从签名中省略,但即使我们没有参数,我们仍然需要圆括号。

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.

同样,这是 execute 方法最简单的实现:它什么也不做,但我们只是想让我们的代码通过编译。让我们再次检查它:

Again, this is the simplest implementation of the execute method: It does nothing, but we’re only trying to make our code compile. Let’s check it again:

{{#include ../listings/ch21-web-server/no-listing-03-define-execute/output.txt}}

它通过编译了!但请注意,如果你尝试 cargo run 并在浏览器中发起请求,你将看到我们在本章开头看到的浏览器错误。我们的库实际上还没有调用传递给 execute 的闭包!

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!

注意:关于像 Haskell 和 Rust 这样具有严格编译器的语言,有一句谚语是:“如果代码能编译,它就能工作。”但这句话并非普遍适用。我们的项目通过了编译,但它绝对什么也没做!如果我们正在构建一个真正的、完整的项目,现在将是开始编写单元测试的好时机,以检查代码在通过编译的“同时”是否具有我们想要的行为。

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.

思考一下:如果我们打算执行的是一个 future 而不是闭包,这里会有什么不同?

Consider: What would be different here if we were going to execute a future instead of a closure?

new 中验证线程数量 (Validating the Number of Threads in new)

我们没有对 newexecute 的参数做任何操作。让我们通过我们想要的行为来实现这些函数的主体。首先,让我们考虑一下 new 。早些时候我们为 size 参数选择了无符号类型,因为负数的线程池没有任何意义。然而,零个线程的池也没有任何意义,但零是一个完全有效的 usize 。我们将在返回 ThreadPool 实例之前添加代码来检查 size 是否大于零,并让程序在接收到零时使用 assert! 宏引发恐慌,如示例 21-13 所示。

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 we’ll have the program panic if it receives a zero by using the assert! macro, as shown in Listing 21-13.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-13/src/lib.rs:here}}

我们还使用文档注释为我们的 ThreadPool 添加了一些文档。请注意,我们遵循了良好的文档实践,添加了一个部分来说明我们的函数可能发生恐慌的情况,正如第 14 章中所讨论的那样。尝试运行 cargo doc --open 并点击 ThreadPool 结构体,看看生成的 new 文档是什么样子的!

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!

与其像我们在这里所做的那样添加 assert! 宏,我们可以将 new 更改为 build 并返回一个 Result ,就像我们在示例 12-9 的 I/O 项目中对 Config::build 所做的那样。但在这种情况下,我们决定尝试创建一个没有任何线程的线程池应该是一个不可恢复的错误。如果你雄心勃勃,可以尝试编写一个名为 build 的具有以下签名的函数,并与 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:

pub fn build(size: usize) -> Result<ThreadPool, PoolCreationError> {

创建用于存储线程的空间 (Creating Space to Store the Threads)

既然我们有办法知道我们拥有存储在池中的有效线程数量,我们就可以创建这些线程并在返回结构体之前将其存储在 ThreadPool 结构体中。但我们如何“存储”一个线程呢?让我们再看一下 thread::spawn 的签名:

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:

pub fn spawn<F, T>(f: F) -> JoinHandle<T>
    where
        F: FnOnce() -> T,
        F: Send + 'static,
        T: Send + 'static,

spawn 函数返回一个 JoinHandle<T> ,其中 T 是闭包返回的类型。让我们也尝试使用 JoinHandle 看看会发生什么。在我们的例子中,我们要传递给线程池的闭包将处理连接且不返回任何内容,因此 T 将是单元类型 ()

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 ().

示例 21-14 中的代码可以编译,但它目前还没有创建任何线程。我们已经更改了 ThreadPool 的定义以持有一个 thread::JoinHandle<()> 实例向量,使用 size 容量初始化了该向量,设置了一个将运行一些代码来创建线程的 for 循环,并返回了一个包含它们的 ThreadPool 实例。

The code in Listing 21-14 will compile, but it 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.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-14/src/lib.rs:here}}

我们在库 crate 中引入了 std::thread ,因为我们正在使用 thread::JoinHandle 作为 ThreadPool 向量中项的类型。

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.

一旦接收到有效的 size,我们的 ThreadPool 就会创建一个可以持有 size 项的新向量。 with_capacity 函数执行与 Vec::new 相同的任务,但有一个重要的区别:它预先分配了向量中的空间。因为我们知道我们需要在向量中存储 size 个元素,所以预先进行这种分配比使用 Vec::new 稍微高效一些,后者会在元素插入时调整自身大小。

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 pre-allocates 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.

当你再次运行 cargo check 时,它应该会成功。

When you run cargo check again, it should succeed.

将代码从 ThreadPool 发送到线程 (Sending Code from the ThreadPool to a Thread)

Sending Code from the ThreadPool to a Thread

我们在示例 21-14 的 for 循环中留下了关于创建线程的注释。在这里,我们将看看我们如何真正创建线程。标准库提供了 thread::spawn 作为创建线程的一种方式,并且 thread::spawn 期望获得线程在创建后应立即运行的一些代码。然而,在我们的例子中,我们想要创建线程并让它们“等待”我们稍后将发送的代码。标准库的线程实现不包含任何执行此操作的方法;我们必须手动实现。

We left a comment in the for loop in Listing 21-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.

我们将通过在 ThreadPool 和线程之间引入一个新的数据结构来管理这种新行为,以此来实现它。我们将这个数据结构称为 Worker(工人),这是池实现中的一个常用术语。 Worker 拾取需要运行的代码并在其线程中运行该代码。

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 its 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 filling them.

我们不再在线程池中存储 JoinHandle<()> 实例向量,而是存储 Worker 结构体实例。每个 Worker 将存储单个 JoinHandle<()> 实例。然后,我们将在 Worker 上实现一个方法,该方法将接收一个要运行的闭包代码,并将其发送到已经在运行的线程中执行。我们还将给每个 Worker 一个 id ,以便在记录日志或调试时我们可以区分池中的不同 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 that we can distinguish between the different instances of Worker in the pool when logging or debugging.

以下是我们在创建 ThreadPool 时将发生的新过程。在按这种方式设置好 Worker 后,我们将实现将闭包发送到线程的代码:

  1. 定义一个持有 idJoinHandle<()>Worker 结构体。
  2. 更改 ThreadPool 以持有一个 Worker 实例向量。
  3. 定义一个 Worker::new 函数,该函数接收一个 id 数字并返回一个持有该 id 以及使用空闭包生成的线程的 Worker 实例。
  4. ThreadPool::new 中,使用 for 循环计数器生成一个 id ,创建一个具有该 id 的新 Worker ,并将该 Worker 存储在向量中。

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:

  1. Define a Worker struct that holds an id and a JoinHandle<()>.
  2. Change ThreadPool to hold a vector of Worker instances.
  3. Define a Worker::new function that takes an id number and returns a Worker instance that holds the id and a thread spawned with an empty closure.
  4. In ThreadPool::new, use the for loop counter to generate an id, create a new Worker with that id, and store the Worker in the vector.

如果你准备好迎接挑战,请在查看示例 21-15 中的代码之前尝试自己实现这些更改。

If you’re up for a challenge, try implementing these changes on your own before looking at the code in Listing 21-15.

准备好了吗?这里是示例 21-15,提供了一种进行上述修改的方法。

Ready? Here is Listing 21-15 with one way to make the preceding modifications.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-15/src/lib.rs:here}}

我们将 ThreadPool 上的字段名称从 threads 更改为了 workers ,因为它现在持有的是 Worker 实例而不是 JoinHandle<()> 实例。我们将 for 循环中的计数器作为 Worker::new 的参数,并将每个新 Worker 存储在名为 workers 的向量中。

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.

外部代码(比如 src/main.rs 中的服务器)不需要知道关于在 ThreadPool 内部使用 Worker 结构体的实现细节,所以我们将 Worker 结构体及其 new 函数设为私有。 Worker::new 函数使用我们给出的 id ,并存储一个通过使用空闭包产生新线程创建的 JoinHandle<()> 实例。

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.

注意:如果由于系统资源不足而无法创建线程, thread::spawn 将引发恐慌。即使创建某些线程可能成功,这也会导致我们的整个服务器发生恐慌。为了简单起见,这种行为是可以接受的,但在生产级线程池实现中,你可能会想使用 std::thread::Builder 及其返回 Resultspawn 方法。

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.

这段代码可以编译,并将存储我们在 ThreadPool::new 参数中指定的 Worker 实例数量。但我们“仍然”没有处理我们在 execute 中获得的闭包。让我们接下来看看如何做到这一点。

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.

通过通道向线程发送请求 (Sending Requests to Threads via Channels)

我们要解决的下一个问题是,给予 thread::spawn 的闭包绝对没做任何事情。目前,我们在 execute 方法中获得了我们想要执行的闭包。但我们需要在创建 ThreadPool 期间创建每个 Worker 时,给 thread::spawn 一个要运行的闭包。

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.

我们希望我们刚刚创建的 Worker 结构体能从 ThreadPool 持有的队列中获取要运行的代码,并将该代码发送到其线程中运行。

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.

我们在第 16 章学到的通道——一种在两个线程之间通信的简单方式——对于这种用例来说是完美的。我们将使用通道作为工作队列, execute 将通过发送端从 ThreadPoolWorker 实例发送一个作业,后者再将该作业发送到其线程。计划如下:

  1. ThreadPool 将创建一个通道并持有发送端。
  2. 每个 Worker 将持有接收端。
  3. 我们将创建一个新的 Job 结构体,它将持有我们想要通过通道发送的闭包。
  4. execute 方法将通过发送端发送它想要执行的作业。
  5. 在其线程中, Worker 将在其接收端上循环,并执行其收到的任何作业的闭包。

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:

  1. The ThreadPool will create a channel and hold on to the sender.
  2. Each Worker will hold on to the receiver.
  3. We’ll create a new Job struct that will hold the closures we want to send down the channel.
  4. The execute method will send the job it wants to execute through the sender.
  5. In its thread, the Worker will loop over its receiver and execute the closures of any jobs it receives.

让我们先在 ThreadPool::new 中创建一个通道,并在 ThreadPool 实例中持有发送端,如示例 21-16 所示。 Job 结构体目前不持有任何内容,但它将是我们通过通道发送的项类型。

{{#rustdoc_include ../listings/ch21-web-server/listing-21-16/src/lib.rs:here}}

ThreadPool::new 中,我们创建了我们的新通道,并让池持有发送端。这将成功通过编译。

In ThreadPool::new, we create our new channel and have the pool hold the sender. This will successfully compile.

让我们尝试在线程池创建通道时,将通道的接收端传递给每个 Worker 。我们知道我们想在 Worker 实例产生的线程中使用接收端,所以我们将引用闭包中的 receiver 参数。示例 21-17 中的代码还不能完全通过编译。

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 Worker instances spawn, so we’ll reference the receiver parameter in the closure. The code in Listing 21-17 won’t quite compile yet.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-17/src/lib.rs:here}}

我们做了一些小而直观的更改:我们将接收端传入 Worker::new ,然后我们在闭包内部使用它。

We’ve made some small and straightforward changes: We pass the receiver into Worker::new, and then we use it inside the closure.

当我们尝试检查这段代码时,我们得到了这个错误:

When we try to check this code, we get this error:

{{#include ../listings/ch21-web-server/listing-21-17/output.txt}}

代码尝试将 receiver 传递给多个 Worker 实例。这将行不通,正如你从第 16 章所能回想起来的:Rust 提供的通道实现是“多生产者,单消费者 (multiple producer, single consumer)”。这意味着我们不能仅仅通过克隆通道的消费端来修复这段代码。我们也不想多次向多个消费者发送一条消息;我们想要一个由多个 Worker 实例共享的消息列表,使得每条消息仅被处理一次。

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 Worker instances such that each message gets processed once.

此外,从通道队列中取出一个作业涉及修改 receiver ,因此线程需要一种安全的方式来共享和修改 receiver ;否则,我们可能会遇到竞态条件(如第 16 章所述)。

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).

回想一下第 16 章讨论过的线程安全智能指针:为了跨多个线程共享所有权并允许线程修改值,我们需要使用 Arc<Mutex<T>>Arc 类型将允许多个 Worker 实例拥有接收端,而 Mutex 将确保同一时间只有一个 Worker 从接收端获得作业。示例 21-18 显示了我们需要做的更改。

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 Worker instances own the receiver, and Mutex will ensure that only one Worker gets a job from the receiver at a time. Listing 21-18 shows the changes we need to make.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-18/src/lib.rs:here}}

ThreadPool::new 中,我们将接收端放在 ArcMutex 中。对于每一个新的 Worker ,我们克隆 Arc 以增加引用计数,以便 Worker 实例可以共享接收端的所有权。

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 that the Worker instances can share ownership of the receiver.

做了这些更改后,代码可以通过编译了!我们快成功了!

With these changes, the code compiles! We’re getting there!

实现 execute 方法 (Implementing the execute Method)

Implementing the execute Method

让我们最终实现 ThreadPool 上的 execute 方法。我们还将把 Job 从结构体更改为一个特征对象的类型别名,该特征对象持有 execute 接收到的闭包类型。正如在第 20 章“类型同义词和类型别名”一节中所讨论的,类型别名允许我们将长类型缩短以方便使用。看示例 21-19。

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 “Type Synonyms and Type Aliases” section in Chapter 20, type aliases allow us to make long types shorter for ease of use. Look at Listing 21-19.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-19/src/lib.rs:here}}

在使用我们在 execute 中获得的闭包创建了一个新的 Job 实例后,我们将该作业发送到通道的发送端。我们为发送失败的情况在 send 上调用 unwrap 。这可能会发生,例如,如果我们停止了所有线程的执行,这意味着接收端已经停止接收新消息。目前,我们还不能停止线程的执行:只要池还存在,我们的线程就会继续执行。我们使用 unwrap 的原因是我们知道失败的情况不会发生,但编译器并不知道。

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.

但我们还没有完全完成!在 Worker 中,我们传递给 thread::spawn 的闭包仍然只是“引用”了通道的接收端。相反,我们需要闭包永远循环,向通道的接收端索要作业,并在获得作业时运行它。让我们对 Worker::new 做出示例 21-20 所示的更改。

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 21-20 to Worker::new.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-20/src/lib.rs:here}}

在这里,我们首先在 receiver 上调用 lock 以获取互斥锁,然后调用 unwrap 在发生任何错误时引发恐慌。如果互斥锁处于“中毒 (poisoned)”状态,获取锁可能会失败,当其他线程在持有锁而不是释放锁时发生恐慌,就可能发生这种情况。在这种情况下,调用 unwrap 让此线程也发生恐慌是正确的行动。你可以随意将这个 unwrap 更改为一个具有对你有意义错误消息的 expect

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.

如果我们拿到了互斥锁,我们就调用 recv 从通道中接收一个 Job 。最后一次 unwrap 也会略过这里的任何错误,如果持有发送端的线程已经关闭,就可能会发生这类错误,这类似于如果接收端关闭, send 方法会返回 Err

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 的调用是阻塞的,所以如果没有可用的作业,当前线程将一直等待,直到有一个作业变为可用。 Mutex<T> 确保了同一时间只有一个 Worker 线程在尝试请求作业。

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.

我们的线程池现在处于工作状态了!给它一个 cargo run 并发起一些请求:

Our thread pool is now in a working state! Give it a cargo run and make some requests:

$ cargo run
   Compiling hello v0.1.0 (file:///projects/hello)
warning: field `workers` is never read
 --> src/lib.rs:7:5
  |
6 | pub struct ThreadPool {
  |            ---------- field in this struct
7 |     workers: Vec<Worker>,
  |     ^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: fields `id` and `thread` are never read
  --> src/lib.rs:48:5
   |
47 | struct Worker {
   |        ------ fields in this struct
48 |     id: usize,
   |     ^^
49 |     thread: thread::JoinHandle<()>,
   |     ^^^^^^

warning: `hello` (lib) generated 2 warnings
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 4.91s
     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.

成功了!我们现在拥有一个可以异步执行连接的线程池。创建的线程永远不会超过四个,所以如果服务器收到大量请求,我们的系统就不会过载。如果我们对 /sleep 发起请求,服务器将能够通过让另一个线程运行其他请求来为它们提供服务。

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 ,它们可能会以五秒的间隔逐一加载。一些 Web 浏览器出于缓存原因会顺序执行同一个请求的多个实例。这种限制并不是由我们的 Web 服务器造成的。

Note: If you open /sleep in multiple browser windows simultaneously, they might load one at a time in five-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.

现在是一个停下来思考的好时机,看看如果我们将 future 而不是闭包用于待完成工作,示例 21-18、21-19 和 21-20 中的代码会有什么不同。哪些类型会改变?方法签名会有什么不同(如果有的话)?代码的哪些部分会保持不变?

This is a good time to pause and consider how the code in Listings 21-18, 21-19, and 21-20 would be different if we were using futures instead of a closure for the work to be done. What types would change? How would the method signatures be different, if at all? What parts of the code would stay the same?

在第 17 章和第 19 章学习了 while let 循环后,你可能会想知道为什么我们没有像示例 21-21 所示那样编写 Worker 线程代码。

After learning about the while let loop in Chapter 17 and Chapter 19, you might be wondering why we didn’t write the Worker thread code as shown in Listing 21-21.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-21/src/lib.rs:here}}

这段代码虽然可以编译并运行,但并不会产生预期的多线程行为:一个慢速请求仍然会导致其他请求等待处理。原因有些微妙: Mutex 结构体没有公共的 unlock 方法,因为锁的所有权基于 lock 方法返回的 LockResult<MutexGuard<T>> 内部的 MutexGuard<T> 的生命周期。在编译时,借用检查器随后可以强制执行这样一条规则:除非我们持有锁,否则不能访问由 Mutex 保护的资源。然而,如果我们不注意 MutexGuard<T> 的生命周期,这种实现也可能导致锁被持有的时间超过预期。

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>.

示例 21-20 中使用 let job = receiver.lock().unwrap().recv().unwrap(); 的代码之所以有效,是因为对于 let ,等号右侧表达式中使用的任何临时值在 let 语句结束时都会被立即丢弃。然而, while let (以及 if letmatch )直到关联代码块结束时才会丢弃临时值。在示例 21-21 中,锁在调用 job() 的整个持续时间内都保持被持有的状态,这意味着其他 Worker 实例无法接收作业。

The code in Listing 21-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 equal 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 21-21, the lock remains held for the duration of the call to job(), meaning other Worker instances cannot receive jobs.

优雅停机与清理 (Graceful Shutdown and Cleanup)


x-i18n: generated_at: “2026-03-01T15:07:21Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: e4c2abaaa676697bc84f66443a4f10ee3ebd19f305e5edcda888e5872ab7ff92 source_path: ch21-03-graceful-shutdown-and-cleanup.md workflow: 16

优雅停机与清理 (Graceful Shutdown and Cleanup)

示例 21-20 中的代码正如我们所愿,通过使用线程池来异步响应请求。我们得到了一些关于未以直接方式使用的 workersidthread 字段的警告,这提醒我们没有进行任何清理工作。当我们使用不那么优雅的 ctrl-C 方法来停止主线程时,所有其他线程也会立即停止,即使它们正处于服务请求的中途。

The code in Listing 21-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.

那么接下来,我们将实现 Drop 特征来对池中的每个线程调用 join ,以便它们在关闭之前可以完成正在处理的请求。然后,我们将实现一种方法来告诉线程它们应该停止接收新请求并关闭。为了看到这段代码的实际运行,我们将修改我们的服务器,使其在优雅地关闭其线程池之前仅接受两个请求。

Next, then, we’ll implement the Drop trait to call join on each of the threads in the pool so that 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.

在进行过程中要注意一点:这一切都不会影响处理执行闭包的那部分代码,所以如果我们在异步运行时中使用线程池,这里的一切都会是一样的。

One thing to notice as we go: None of this affects the parts of the code that handle executing the closures, so everything here would be the same if we were using a thread pool for an async runtime.

ThreadPool 上实现 Drop 特征 (Implementing the Drop Trait on ThreadPool)

Implementing the Drop Trait on ThreadPool

让我们从在我们的线程池上实现 Drop 开始。当池被丢弃时,我们的线程应该全部 join 以确保它们完成工作。示例 21-22 展示了 Drop 实现的第一次尝试;这段代码目前还不能完全运行。

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 21-22 shows a first attempt at a Drop implementation; this code won’t quite work yet.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-22/src/lib.rs:here}}

首先,我们遍历线程池中的每一个 workers 。我们为此使用 &mut ,因为 self 是一个可变引用,并且我们也需要能够修改 worker 。对于每个 worker ,我们打印一条消息表示该特定的 Worker 实例正在关闭,然后我们在该 Worker 实例的线程上调用 join 。如果对 join 的调用失败,我们使用 unwrap 让 Rust 引发恐慌并进入非优雅停机。

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 instance is shutting down, and then we call join on that Worker instance’s thread. If the call to join fails, we use unwrap to make Rust panic and go into an ungraceful shutdown.

这是我们编译这段代码时得到的错误:

Here is the error we get when we compile this code:

{{#include ../listings/ch21-web-server/listing-21-22/output.txt}}

该错误告诉我们不能调用 join ,因为我们只有每个 worker 的可变借用,而 join 会获取其参数的所有权。为了解决此问题,我们需要将线程从拥有 threadWorker 实例中移出,以便 join 可以消耗该线程。实现这一点的一种方法是采取我们在示例 18-15 中采取的相同方法。如果 Worker 持有一个 Option<thread::JoinHandle<()>> ,我们就可以在 Option 上调用 take 方法将值从 Some 变体中移出,并在原位留下一个 None 变体。换句话说,正在运行的 Workerthread 中会有一个 Some 变体,而当我们想清理 Worker 时,我们会用 None 替换 Some ,这样 Worker 就没有可以运行的线程了。

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 that join can consume the thread. One way to do this is to take the same approach we took in Listing 18-15. If Worker held an Option<thread::JoinHandle<()>>, we could 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 would have a Some variant in thread, and when we wanted to clean up a Worker, we’d replace Some with None so that the Worker wouldn’t have a thread to run.

然而,出现这种情况的“唯一”时刻是在丢弃 Worker 时。作为代价,我们在访问 worker.thread 的任何地方都必须处理 Option<thread::JoinHandle<()>> 。惯用的 Rust 经常使用 Option ,但当你发现自己为了像这样绕过问题而将一个你明知始终存在的东西包装在 Option 中时,寻找替代方法来使你的代码更简洁且更不易出错是一个好主意。

However, the only time this would come up would be when dropping the Worker. In exchange, we’d have to deal with an Option<thread::JoinHandle<()>> anywhere we accessed worker.thread. Idiomatic Rust uses Option quite a bit, but when you find yourself wrapping something you know will always be present in an Option as a workaround like this, it’s a good idea to look for alternative approaches to make your code cleaner and less error-prone.

在这种情况下,存在一个更好的替代方案: Vec::drain 方法。它接收一个范围参数来指定要从向量中移除哪些项,并返回这些项的迭代器。传入 .. 范围语法将移除向量中的“每一项”。

In this case, a better alternative exists: the Vec::drain method. It accepts a range parameter to specify which items to remove from the vector and returns an iterator of those items. Passing the .. range syntax will remove every value from the vector.

所以,我们需要像这样更新 ThreadPooldrop 实现:

So, we need to update the ThreadPool drop implementation like this:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch21-web-server/no-listing-04-update-drop-definition/src/lib.rs:here}}
}

这解决了编译器错误,并且不需要对我们的代码进行任何其他更改。请注意,因为 drop 可以在恐慌时被调用, unwrap 也可能会引发恐慌并导致双重恐慌,这将立即导致程序崩溃并结束正在进行的任何清理。这对于示例程序来说是可以的,但不建议用于生产代码。

This resolves the compiler error and does not require any other changes to our code. Note that, because drop can be called when panicking, the unwrap could also panic and cause a double panic, which immediately crashes the program and ends any cleanup in progress. This is fine for an example program, but it isn’t recommended for production code.

通知线程停止监听作业 (Signaling to the Threads to Stop Listening for Jobs)

Signaling to the Threads to Stop Listening for Jobs

做了所有这些更改后,我们的代码在编译时没有任何警告。然而,坏消息是,这段代码目前还不能按照我们想要的方式运作。关键在于由 Worker 实例线程运行的闭包中的逻辑:目前,我们调用了 join ,但这不会关闭线程,因为它们在 loop 中永远寻找作业。如果我们尝试使用当前的 drop 实现来丢弃我们的 ThreadPool ,主线程将永远阻塞,等待第一个线程结束。

With all the changes we’ve made, our code compiles without any warnings. However, the bad news is that 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.

为了解决这个问题,我们需要在 ThreadPooldrop 实现中做一处改动,然后在 Worker 循环中也做一处改动。

To fix this problem, we’ll need a change in the ThreadPool drop implementation and then a change in the Worker loop.

首先,我们将更改 ThreadPooldrop 实现,在等待线程结束之前显式丢弃 sender 。示例 21-23 显示了对 ThreadPool 进行的显式丢弃 sender 的更改。与线程不同,这里我们“确实”需要使用 Option 才能通过 Option::takesender 移出 ThreadPool

First, we’ll change the ThreadPool drop implementation to explicitly drop the sender before waiting for the threads to finish. Listing 21-23 shows the changes to ThreadPool to explicitly drop sender. Unlike with the thread, here we do need to use an Option to be able to move sender out of ThreadPool with Option::take.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-23/src/lib.rs:here}}

丢弃 sender 会关闭通道,这表示不再会有消息被发送。当发生这种情况时, Worker 实例在无限循环中执行的所有 recv 调用都将返回一个错误。在示例 21-24 中,我们将 Worker 循环更改为在这种情况下优雅地退出循环,这意味着当 ThreadPooldrop 实现对线程调用 join 时,线程将会结束。

Dropping sender closes the channel, which indicates no more messages will be sent. When that happens, all the calls to recv that the Worker instances do in the infinite loop will return an error. In Listing 21-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.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-24/src/lib.rs:here}}

为了看到这段代码的实际运行,让我们修改 main 以便在优雅地关闭服务器之前仅接受两个请求,如示例 21-25 所示。

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 21-25.

{{#rustdoc_include ../listings/ch21-web-server/listing-21-25/src/main.rs:here}}

你肯定不希望一个现实世界的 Web 服务器在仅服务两个请求后就关闭。这段代码只是演示优雅停机和清理工作处于正常状态。

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.

take 方法定义在 Iterator 特征中,它最多将迭代限制在前两个项。 ThreadPool 将在 main 结束时超出作用域,并运行 drop 实现。

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.

使用 cargo run 启动服务器并发起三个请求。第三个请求应该会报错,在你的终端中,你应该看到类似于这样的输出:

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
   Compiling hello v0.1.0 (file:///projects/hello)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.41s
     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

你可能会看到不同的 Worker ID 排序和打印的消息顺序。我们可以从消息中看到这段代码是如何工作的: Worker 实例 0 和 3 获得了前两个请求。服务器在第二个连接之后停止接受连接,并且 ThreadPool 上的 Drop 实现甚至在 Worker 3 开始其作业之前就开始执行。丢弃 sender 会断开所有 Worker 实例的连接并告诉它们关闭。 Worker 实例在断开连接时各自打印一条消息,然后线程池调用 join 等待每个 Worker 线程结束。

You might see a different ordering of Worker IDs and messages printed. We can see how this code works from the messages: Worker instances 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 Worker instances and tells them to shut down. The Worker instances each print a message when they disconnect, and then the thread pool calls join to wait for each Worker thread to finish.

注意这次特定执行的一个有趣方面: ThreadPool 丢弃了 sender ,并且在任何 Worker 收到错误之前,我们就尝试 join Worker 0Worker 0 尚未从 recv 收到错误,因此主线程发生阻塞,等待 Worker 0 结束。与此同时, Worker 3 收到了一个作业,然后所有线程都收到了一个错误。当 Worker 0 完成后,主线程等待剩余的 Worker 实例完成。在那一点上,它们都已经退出了循环并停止了。

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 Worker instances to finish. At that point, they had all exited their loops and stopped.

恭喜!我们现在已经完成了我们的项目;我们拥有一个使用线程池异步响应的基本 Web 服务器。我们能够执行服务器的优雅停机,清理池中的所有线程。

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.

这是供参考的完整代码:

Here’s the full code for reference:

{{#rustdoc_include ../listings/ch21-web-server/no-listing-07-final-code/src/main.rs}}
{{#rustdoc_include ../listings/ch21-web-server/no-listing-07-final-code/src/lib.rs}}

我们在这里还可以做得更多!如果你想继续增强这个项目,这里有一些想法:

  • ThreadPool 及其公共方法添加更多文档。
  • 添加对库功能的测试。
  • 将对 unwrap 的调用更改为更健壮的错误处理。
  • 使用 ThreadPool 执行除服务 Web 请求之外的其他任务。
  • crates.io 上寻找一个线程池 crate,并改为使用该 crate 实现一个类似的 Web 服务器。然后,将其 API 和健壮性与我们实现的线程池进行比较。

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.
  • Add tests of the library’s functionality.
  • Change calls to unwrap to more robust error handling.
  • Use ThreadPool to perform some task other than serving web requests.
  • 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.

总结 (Summary)

Summary

做得好!你已经读到了这本书的尽头!我们要感谢你加入我们的 Rust 之旅。你现在已经准备好实现你自己的 Rust 项目并帮助他人的项目了。请记住,有一个热情的其他 Rustaceans 社区,他们非常乐意帮助你解决在 Rust 旅程中遇到的任何挑战。

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 people’s 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.

附录 (Appendix)


x-i18n: generated_at: “2026-03-01T09:09:22Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 40d28cc6e2850568c1f627748ef35fcce0afe898b3ad1b326e075a843ebb0d38 source_path: appendix-00.md workflow: 16

附录 (Appendix)

Appendix

以下章节包含了在你的 Rust 旅程中可能会发现有用的参考资料。

The following sections contain reference material you may find useful in your Rust journey.

A - 关键字 (A - Keywords)


x-i18n: generated_at: “2026-03-01T09:10:28Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 9178c0420eb760c7c8fc7dd3a5c6d790c133f66968a9cac90f71c743c65ed8d6 source_path: appendix-01-keywords.md workflow: 16

附录 A:关键字 (Appendix A: Keywords)

Appendix A: Keywords

以下列表包含为 Rust 语言当前或未来使用而保留的关键字。因此,它们不能用作标识符(除非作为原始标识符,正如我们在“原始标识符”部分所讨论的那样)。标识符 (Identifiers) 是函数、变量、参数、结构体字段、模块、Crates、常量、宏、静态值、属性、类型、Traits 或生命周期的名称。

The following lists contain 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 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.

目前使用的关键字 (Keywords Currently in Use)

Keywords Currently in Use

以下是目前正在使用的关键字列表,及其功能的简要描述。

The following is a list of keywords currently in use, with their functionality described.

  • as:执行原始类型转换、消除包含某项的特定 trait 的歧义,或在 use 语句中重命名项。
  • as: Perform primitive casting, disambiguate the specific trait containing an item, or rename items in use statements.
  • async:返回一个 Future 而不是阻塞当前线程。
  • async: Return a Future instead of blocking the current thread.
  • await:暂停执行,直到 Future 的结果就绪。
  • await: Suspend execution until the result of a Future is ready.
  • break:立即退出循环。
  • break: Exit a loop immediately.
  • const:定义常量条目或常量原始指针。
  • const: Define constant items or constant raw pointers.
  • continue:继续下一次循环迭代。
  • continue: Continue to the next loop iteration.
  • crate:在模块路径中,引用 crate 根。
  • crate: In a module path, refers to the crate root.
  • dyn:动态分发到 trait 对象。
  • dyn: Dynamic dispatch to a trait object.
  • elseifif let 控制流结构的备选分支。
  • else: Fallback for if and if let control flow constructs.
  • enum:定义枚举。
  • enum: Define an enumeration.
  • extern:链接外部函数或变量。
  • extern: Link an external function or variable.
  • false:布尔假字面值。
  • false: Boolean false literal.
  • fn:定义函数或函数指针类型。
  • fn: Define a function or the function pointer type.
  • for:遍历迭代器中的项、实现 trait 或指定高阶生命周期 (higher ranked lifetime)。
  • for: Loop over items from an iterator, implement a trait, or specify a higher ranked lifetime.
  • if:基于条件表达式的结果进行分支。
  • if: Branch based on the result of a conditional expression.
  • impl:实现固有功能或 trait 功能。
  • impl: Implement inherent or trait functionality.
  • infor 循环语法的一部分。
  • in: Part of for loop syntax.
  • let:绑定变量。
  • let: Bind a variable.
  • loop:无条件循环。
  • loop: Loop unconditionally.
  • match:将值与模式匹配。
  • match: Match a value to patterns.
  • mod:定义模块。
  • mod: Define a module.
  • move:使闭包获取其所有捕获变量的所有权。
  • move: Make a closure take ownership of all its captures.
  • mut:表示引用、原始指针或模式绑定中的可变性。
  • mut: Denote mutability in references, raw pointers, or pattern bindings.
  • pub:表示结构体字段、impl 块或模块中的公有可见性。
  • pub: Denote public visibility in struct fields, impl blocks, or modules.
  • ref:通过引用绑定。
  • ref: Bind by reference.
  • return:从函数返回。
  • return: Return from function.
  • Self:正在定义或实现的类型的类型别名。
  • Self: A type alias for the type we are defining or implementing.
  • self:方法主体或当前模块。
  • self: Method subject or current module.
  • static:全局变量或在整个程序执行期间持续的生命周期。
  • static: Global variable or lifetime lasting the entire program execution.
  • struct:定义结构体。
  • struct: Define a structure.
  • super:当前模块的父模块。
  • super: Parent module of the current module.
  • trait:定义 trait。
  • trait: Define a trait.
  • true:布尔真字面值。
  • true: Boolean true literal.
  • type:定义类型别名或关联类型。
  • type: Define a type alias or associated type.
  • union:定义 联合体 (union);仅在联合体声明中使用时才是关键字。
  • union: Define a union; is a keyword only when used in a union declaration.
  • unsafe:表示不安全的代码、函数、Traits 或实现。
  • unsafe: Denote unsafe code, functions, traits, or implementations.
  • use:将符号引入作用域。
  • use: Bring symbols into scope.
  • where:表示约束类型的子句。
  • where: Denote clauses that constrain a type.
  • while:基于表达式结果的有条件循环。
  • while: Loop conditionally based on the result of an expression.

保留供未来使用的关键字 (Keywords Reserved for Future Use)

Keywords Reserved for Future Use

以下关键字目前还没有任何功能,但被 Rust 保留用于潜在的未来用途:

The following keywords do not yet have any functionality but are reserved by Rust for potential future use:

  • abstract
  • become
  • box
  • do
  • final
  • gen
  • macro
  • override
  • priv
  • try
  • typeof
  • unsized
  • virtual
  • yield

原始标识符 (Raw Identifiers)

Raw Identifiers

原始标识符 (Raw identifiers) 是允许你在通常不允许使用关键字的地方使用关键字的语法。你可以通过在关键字前加上前缀 r# 来使用原始标识符。

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#.

例如,match 是一个关键字。如果你尝试编译以下使用 match 作为名称的函数:

For example, match is a keyword. If you try to compile the following function that uses match as its name:

文件名: src/main.rs

Filename: 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

该错误显示你不能使用关键字 match 作为函数标识符。要将 match 用作函数名,你需要使用原始标识符语法,如下所示:

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:

文件名: src/main.rs

Filename: src/main.rs

fn r#match(needle: &str, haystack: &str) -> bool {
    haystack.contains(needle)
}

fn main() {
    assert!(r#match("foo", "foobar"));
}

这段代码将编译通过而不会出现任何错误。请注意在函数定义的函数名上以及在 main 中调用该函数的地方都使用了 r# 前缀。

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.

原始标识符允许你使用任何你选择的单词作为标识符,即使该单词恰好是一个保留关键字。这给了我们选择标识符名称的更多自由,同时也让我们能够与使用非关键字语言编写的程序进行集成。此外,原始标识符还允许你使用与你的 crate 使用的不同 Rust 版本 (edition) 编写的库。例如,try 在 2015 版本中不是关键字,但在 2018、2021 和 2024 版本中是。如果你依赖一个使用 2015 版本编写且具有 try 函数的库,在更高版本的代码中调用该函数时,你需要使用原始标识符语法(在本例中为 r#try)。有关版本的更多信息,请参阅附录 E

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, 2021, and 2024 editions. If you depend on a library that is 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 code on later editions. See Appendix E for more information on editions.

B - 运算符与符号 (B - Operators and Symbols)


x-i18n: generated_at: “2026-03-01T09:11:45Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: bc33afa09cd57576dacd399d348950fa5bc8a3642818c1bc05ddbc088c0c5514 source_path: appendix-02-operators.md workflow: 16

附录 B:运算符与符号 (Appendix B: Operators and Symbols)

Appendix B: Operators and Symbols

本附录包含 Rust 语法的术语表,包括运算符以及单独出现或出现在路径、泛型、Trait 约束、宏、属性、注释、元组和括号上下文中的其他符号。

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.

运算符 (Operators)

Operators

表 B-1 包含了 Rust 中的运算符,这些运算符在上下文中的示例,简要说明,以及该运算符是否可重载。如果一个运算符是可重载的,则列出了用于重载该运算符的相关 trait。

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:运算符 (Table B-1: Operators)

Table B-1: Operators

运算符 (Operator)示例 (Example)说明 (Explanation)是否可重载? (Overloadable?)
!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借用 (Borrow)
&&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原始指针 (Raw pointer)
+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函数和闭包返回类型 (Function and closure return type)
.expr.ident字段访问 (Field access)
.expr.ident(expr, ...)方法调用 (Method call)
.expr.0, expr.1, and so on元组索引 (Tuple indexing)
...., expr.., ..expr, expr..expr右开区间字面值 (Right-exclusive range literal)PartialOrd
..=..=expr, expr..=expr右闭区间字面值 (Right-inclusive range literal)PartialOrd
....expr结构体字面值更新语法 (Struct literal update syntax)
..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约束 (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赋值/等值 (Assignment/equivalence)
==expr == expr相等比较 (Equality comparison)PartialEq
=>pat => exprmatch 臂语法的一部分 (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)

Non-operator Symbols

以下表格包含了所有不作为运算符使用的符号;也就是说,它们的行为不像函数或方法调用。

The following tables contain all symbols that don’t function as operators; that is, they don’t behave like a function or method call.

表 B-2 显示了单独出现且在多个位置有效的符号。

Table B-2 shows symbols that appear on their own and are valid in a variety of locations.

表 B-2:独立语法 (Table B-2: Stand-alone Syntax)

Table B-2: Stand-alone Syntax

符号 (Symbol)说明 (Explanation)
'ident具名生命周期或循环标签 (Named lifetime or loop label)
紧随其后的是 u8i32f64usize 等的数字 (Digits immediately followed by u8, i32, f64, usize, and so on)特定类型的数值字面值 (Numeric literal of specific type)
"..."字符串字面值 (String literal)
r"...", r#"..."#, r##"..."##, 等 (and so on)原始字符串字面值;不处理转义字符 (Raw string literal; escape characters not processed)
b"..."字节字符串字面值;构造字节数组而不是字符串 (Byte string literal; constructs an array of bytes instead of a string)
br"...", br#"..."#, br##"..."##, 等 (and so on)原始字节字符串字面值;原始和字节字符串字面值的组合 (Raw byte string literal; combination of raw and byte string literal)
'...'字符字面值 (Character literal)
b'...'ASCII 字节字面值 (ASCII byte literal)
|…| expr闭包 (Closure)
!用于发散函数的始终为空的底类型 (Always-empty bottom type for diverging functions)
_“忽略”模式绑定;也用于提高整数字面值的可读性 (“Ignored” pattern binding; also used to make integer literals readable)

表 B-3 显示了在通过模块层级结构指向某项的路径上下文中出现的符号。

Table B-3 shows symbols that appear in the context of a path through the module hierarchy to an item.

表 B-3:路径相关语法 (Table B-3: Path-Related Syntax)

Table B-3: Path-Related Syntax

符号 (Symbol)说明 (Explanation)
ident::ident命名空间路径 (Namespace path)
::path相对于 crate 根的路径(即显式的绝对路径) (Path relative to the crate root (that is, an explicitly absolute path))
self::path相对于当前模块的路径(即显式的相对路径) (Path relative to the current module (that is, an explicitly relative path))
super::path相对于当前模块父模块的路径 (Path relative to the parent of the current module)
type::ident, <type as trait>::ident关联常量、函数和类型 (Associated constants, functions, and types)
<type>::...无法直接命名的类型的关联项(例如 <&T>::...<[T]>::... 等) (Associated item for a type that cannot be directly named (for example, <&T>::..., <[T]>::..., and so on))
trait::method(...)通过命名定义方法的 trait 来消除方法调用的歧义 (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(...)通过命名 trait 和类型来消除方法调用的歧义 (Disambiguating a method call by naming the trait and type)

表 B-4 显示了在利用泛型类型参数的上下文中出现的符号。

Table B-4 shows symbols that appear in the context of using generic type parameters.

表 B-4:泛型 (Table B-4: Generics)

Table B-4: Generics

符号 (Symbol)说明 (Explanation)
path<...>在类型中指定泛型类型的参数(例如 Vec<u8>) (Specifies parameters to a generic type in a type (for example, Vec<u8>))
path::<...>, method::<...>在表达式中指定泛型类型、函数或方法的参数;通常被称为 turbofish(例如 "42".parse::<i32>()) (Specifies parameters to a generic type, function, or method in an expression; often referred to as turbofish (for example, "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>一个或多个关联类型具有特定赋值的泛型类型(例如 Iterator<Item=T>) (A generic type where one or more associated types have specific assignments (for example, Iterator<Item=T>))

表 B-5 显示了在用 trait 约束来限制泛型类型参数的上下文中出现的符号。

Table B-5 shows symbols that appear in the context of constraining generic type parameters with trait bounds.

表 B-5:Trait 约束 (Table B-5: Trait Bound Constraints)

Table B-5: Trait Bound Constraints

符号 (Symbol)说明 (Explanation)
T: U泛型参数 T 被限制为实现了 U 的类型 (Generic parameter T constrained to types that implement U)
T: 'a泛型类型 T 必须比生命周期 'a 存活得更久(意味着该类型不能传递地包含任何生命周期短于 'a 的引用) (Generic type T must outlive lifetime 'a (meaning the type cannot transitively contain any references with lifetimes shorter than 'a))
T: 'static泛型类型 T 除了 'static 引用外不包含任何借用引用 (Generic type T contains no borrowed references other than 'static ones)
'b: 'a泛型生命周期 'b 必须比生命周期 'a 存活得更久 (Generic lifetime 'b must outlive lifetime 'a)
T: ?Sized允许泛型类型参数是动态大小类型 (Allow generic type parameter to be a dynamically sized type)
'a + trait, trait + trait复合类型约束 (Compound type constraint)

表 B-6 显示了在调用或定义宏以及在项上指定属性的上下文中出现的符号。

Table B-6 shows symbols that appear in the context of calling or defining macros and specifying attributes on an item.

表 B-6:宏与属性 (Table B-6: Macros and Attributes)

Table B-6: Macros and Attributes

符号 (Symbol)说明 (Explanation)
#[meta]外层属性 (Outer attribute)
#![meta]内层属性 (Inner attribute)
$ident宏替换 (Macro substitution)
$ident:kind宏元变量 (Macro metavariable)
$(...)...宏重复 (Macro repetition)
ident!(...), ident!{...}, ident![...]宏调用 (Macro invocation)

表 B-7 显示了创建注释的符号。

Table B-7 shows symbols that create comments.

表 B-7:注释 (Table B-7: Comments)

Table B-7: Comments

符号 (Symbol)说明 (Explanation)
//行注释 (Line comment)
//!内层行文档注释 (Inner line doc comment)
///外层行文档注释 (Outer line doc comment)
/*...*/块注释 (Block comment)
/*!...*/内层块文档注释 (Inner block doc comment)
/**...*/外层块文档注释 (Outer block doc comment)

表 B-8 显示了使用圆括号的上下文。

Table B-8 shows the contexts in which parentheses are used.

表 B-8:圆括号 (Table B-8: Parentheses)

Table B-8: Parentheses

符号 (Symbol)说明 (Explanation)
()空元组(又名 unit),既是字面值也是类型 (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 structs and tuple enum variants)

表 B-9 显示了使用花括号的上下文。

Table B-9 shows the contexts in which curly brackets are used.

表 B-9:花括号 (Table B-9: Curly Brackets)

Table B-9: Curly Brackets

上下文 (Context)说明 (Explanation)
{...}块表达式 (Block expression)
Type {...}结构体字面值 (Struct literal)

表 B-10 显示了使用方括号的上下文。

Table B-10 shows the contexts in which square brackets are used.

表 B-10:方括号 (Table B-10: Square Brackets)

Table B-10: Square Brackets

上下文 (Context)说明 (Explanation)
[...]数组字面值 (Array literal)
[expr; len]包含 lenexpr 副本的数组字面值 (Array literal containing len copies of expr)
[type; len]包含 lentype 实例的数组类型 (Array type containing len instances of type)
expr[expr]集合索引;可重载 (Index, IndexMut) (Collection indexing; overloadable (Index, IndexMut))
expr[..], expr[a..], expr[..b], expr[a..b]伪装成集合切片的集合索引,使用 RangeRangeFromRangeToRangeFull 作为“索引” (Collection indexing pretending to be collection slicing, using Range, RangeFrom, RangeTo, or RangeFull as the “index”)

C - 可派生的 Traits (C - Derivable Traits)


x-i18n: generated_at: “2026-03-01T09:12:27Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 5ea4664c1cda3c660cf77a247296c730f0d4e3734d702c0f02726cd690474d8e source_path: appendix-03-derivable-traits.md workflow: 16

附录 C:可派生的 Traits (Appendix C: Derivable Traits)

Appendix C: Derivable Traits

在本书的多个地方,我们讨论了 derive 属性,你可以将其应用于结构体或枚举定义。derive 属性生成的代码将会在你使用 derive 语法标注的类型上实现一个带有自身默认实现的 trait。

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 一起使用的 trait 的参考。每个部分涵盖:

In this appendix, we provide a reference of all the traits in the standard library that you can use with derive. Each section covers:

  • 派生此 trait 将启用哪些运算符和方法
  • What operators and methods deriving this trait will enable
  • derive 提供的 trait 实现做了什么
  • What the implementation of the trait provided by derive does
  • 实现该 trait 对类型意味着什么
  • What implementing the trait signifies about the type
  • 允许或不允许实现该 trait 的条件
  • The conditions in which you’re allowed or not allowed to implement the trait
  • 需要该 trait 的操作示例
  • Examples of operations that require the trait

如果你想要不同于 derive 属性所提供的行为,请查阅标准库文档中关于每个 trait 的详细信息,以了解如何手动实现它们。

If you want different behavior from that provided by the derive attribute, consult the standard library documentation for each trait for details on how to manually implement them.

这里列出的 trait 是标准库定义的唯一可以使用 derive 在你的类型上实现的 trait。标准库中定义的其他 trait 没有合理的默认行为,因此由你决定以符合你目标的方式来实现它们。

The 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.

一个不能派生的 trait 示例是 Display,它处理面向最终用户的格式化。你应该始终考虑向最终用户显示类型的适当方式。最终用户应该被允许看到类型的哪些部分?哪些部分是他们认为相关的?什么样的数据格式对他们来说最相关?Rust 编译器没有这些见解,因此它无法为你提供适当的默认行为。

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.

本附录中提供的可派生 trait 列表并不全面:库可以为它们自己的 trait 实现 derive,这使得你可以使用 derive 的 trait 列表实际上是无限开放的。实现 derive 涉及到使用过程宏,这在第 20 章的“自定义 derive 宏”部分有详细介绍。

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 “Custom derive Macros” section in Chapter 20.

用于程序员输出的 Debug (Debug for Programmer Output)

Debug for Programmer Output

Debug trait 在格式化字符串中启用调试格式,你可以通过在 {} 占位符中添加 :? 来表示。

The Debug trait enables debug formatting in format strings, which you indicate by adding :? within {} placeholders.

Debug trait 允许你出于调试目的打印类型的实例,这样你和使用你的类型的其他程序员就可以在程序执行的特定点检查实例。

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.

例如,在使用 assert_eq! 宏时需要 Debug trait。如果相等断言失败,该宏会打印作为参数给出的实例的值,以便程序员看到为什么这两个实例不相等。

The Debug trait is required, for example, in the use of the assert_eq! macro. This macro prints the values of instances given as arguments if the equality assertion fails so that programmers can see why the two instances weren’t equal.

用于相等比较的 PartialEqEq (PartialEq and Eq for Equality Comparisons)

PartialEq and Eq for Equality Comparisons

PartialEq trait 允许你比较一个类型的实例以检查是否相等,并启用 ==!= 运算符的使用。

The PartialEq trait allows you to compare instances of a type to check for equality and enables use of the == and != operators.

派生 PartialEq 会实现 eq 方法。当在结构体上派生 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.

例如,在使用 assert_eq! 宏时需要 PartialEq trait,该宏需要能够比较一个类型的两个实例是否相等。

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.

Eq trait 没有方法。它的目的是表明对于标注类型的每个值,该值都与其自身相等。Eq trait 只能应用于也实现了 PartialEq 的类型,尽管并非所有实现 PartialEq 的类型都能实现 Eq。一个例子是浮点数类型:浮点数的实现规定,非数字值 (NaN) 的两个实例彼此不相等。

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 的一个例子是 HashMap<K, V> 中的键,以便 HashMap<K, V> 可以判断两个键是否相同。

An example of when Eq is required is for keys in a HashMap<K, V> so that the HashMap<K, V> can tell whether two keys are the same.

用于顺序比较的 PartialOrdOrd (PartialOrd and Ord for Ordering Comparisons)

PartialOrd and Ord for Ordering Comparisons

PartialOrd trait 允许你出于排序目的比较一个类型的实例。实现了 PartialOrd 的类型可以与 <><=>= 运算符一起使用。你只能将 PartialOrd trait 应用于也实现了 PartialEq 的类型。

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 会实现 partial_cmp 方法,该方法返回一个 Option<Ordering>,当给定的值无法产生顺序时,它将是 None。一个尽管该类型的大多数值都可以比较,但无法产生顺序的值的例子是 NaN 浮点值。使用任何浮点数和 NaN 浮点值调用 partial_cmp 都会返回 None

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 NaN floating point value. Calling partial_cmp with any floating-point number and the NaN floating-point value will return None.

当在结构体上派生时,PartialOrd 通过按字段在结构体定义中出现的顺序比较每个字段的值来比较两个实例。当在枚举上派生时,在枚举定义中较早声明的枚举变体被认为小于后面列出的变体。

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.

例如,rand crate 中的 gen_range 方法需要 PartialOrd trait,该方法在范围表达式指定的范围内生成随机值。

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.

Ord trait 允许你知晓对于标注类型的任何两个值,都会存在有效的顺序。Ord trait 实现了 cmp 方法,它返回一个 Ordering 而不是 Option<Ordering>,因为有效的顺序总是有可能的。你只能将 Ord trait 应用于也实现了 PartialOrdEq 的类型(而 Eq 要求 PartialEq)。当在结构体和枚举上派生时,cmp 的行为与 PartialOrd 的派生实现对 partial_cmp 的行为相同。

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 的一个例子是在 BTreeSet<T> 中存储值时,这是一种基于值的排序顺序存储数据的数据结构。

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.

用于复制值的 CloneCopy (Clone and Copy for Duplicating Values)

Clone and Copy for Duplicating Values

Clone trait 允许你显式地创建一个值的深拷贝,复制过程可能涉及运行任意代码和复制堆上的数据。有关 Clone 的更多信息,请参阅第 4 章中的“变量与数据交互的方式:Clone”部分。

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 “Variables and Data Interacting with Clone” section in Chapter 4 for more information on Clone.

派生 Clone 会实现 clone 方法,当为整个类型实现该方法时,它会对类型的每个部分调用 clone。这意味着要派生 Clone,类型中的所有字段或值也必须实现 Clone

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 的一个例子是在切片上调用 to_vec 方法时。切片并不拥有它所包含的类型实例,但从 to_vec 返回的 vector 将需要拥有它的实例,因此 to_vec 对每个项调用 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.

Copy trait 允许你仅通过复制存储在栈上的位来复制一个值;不需要运行任意代码。有关 Copy 的更多信息,请参阅第 4 章中的“只在栈上的数据:Copy”部分。

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 trait 没有定义任何方法,以防止程序员重载这些方法并违反不运行任意代码的假设。这样,所有程序员都可以假设复制一个值会非常快。

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 的类型上派生 Copy。实现 Copy 的类型也必须实现 Clone,因为实现 Copy 的类型有一个简单的 Clone 实现,它执行与 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 trait 很少被强制要求;实现 Copy 的类型可以使用优化,这意味着你不必调用 clone,这使代码更简洁。

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 实现的,你也可以通过 Clone 来完成,但代码可能会变慢,或者必须在某些地方使用 clone

Everything possible with Copy you can also accomplish with Clone, but the code might be slower or have to use clone in places.

用于将值映射到固定大小值的 Hash (Hash for Mapping a Value to a Value of Fixed Size)

Hash for Mapping a Value to a Value of Fixed Size

Hash trait 允许你获取任意大小类型的实例,并使用哈希函数将该实例映射到固定大小的值。派生 Hash 会实现 hash 方法。hash 方法的派生实现结合了对类型的每个部分调用 hash 的结果,这意味着要派生 Hash,所有字段或值也必须实现 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 的一个例子是在 HashMap<K, V> 中存储键,以便高效地存储数据。

An example of when Hash is required is in storing keys in a HashMap<K, V> to store data efficiently.

用于默认值的 Default (Default for Default Values)

Default for Default Values

Default trait 允许你为一个类型创建默认值。派生 Default 会实现 default 函数。default 函数的派生实现会对类型的每个部分调用 default 函数,这意味着要派生 Default,类型中的所有字段或值也必须实现 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::default 函数通常与第 5 章“使用结构体更新语法从其他实例创建实例”部分讨论的结构体更新语法结合使用。你可以自定义结构体的几个字段,然后通过使用 ..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().

例如,当你对 Option<T> 实例使用 unwrap_or_default 方法时,就需要 Default trait。如果 Option<T>Noneunwrap_or_default 方法将返回存储在 Option<T> 中的类型 TDefault::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>.

D - 实用的开发工具 (D - Useful Development Tools)


x-i18n: generated_at: “2026-03-01T09:13:15Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 528432253e5d52f4bd0b08de53b634026f85ff993200639f378af9a82295408b source_path: appendix-04-useful-development-tools.md workflow: 16

附录 D:实用的开发工具 (Appendix D: Useful Development Tools)

Appendix D: Useful Development Tools

在本附录中,我们将介绍 Rust 项目提供的一些实用的开发工具。我们将了解自动格式化、应用警告修复的快速方法、linter 以及与 IDE 的集成。

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.

使用 rustfmt 进行自动格式化 (Automatic Formatting with rustfmt)

Automatic Formatting with rustfmt

rustfmt 工具根据社区代码风格重新格式化你的代码。许多协作项目使用 rustfmt 来防止在编写 Rust 时对使用哪种风格产生争论:每个人都使用该工具格式化他们的代码。

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.

Rust 安装默认包含 rustfmt,因此你的系统上应该已经有了 rustfmtcargo-fmt 程序。这两个命令类似于 rustccargo,因为 rustfmt 允许更精细的控制,而 cargo-fmt 理解使用 Cargo 的项目的约定。要格式化任何 Cargo 项目,请输入以下内容:

Rust installations include rustfmt by default, so you should already have the programs rustfmt and cargo-fmt on your system. These two commands are analogous to rustc and cargo in that rustfmt allows finer grained control and cargo-fmt understands conventions of a project that uses Cargo. To format any Cargo project, enter the following:

$ cargo fmt

运行此命令会重新格式化当前 crate 中的所有 Rust 代码。这应该只会改变代码风格,而不会改变代码语义。有关 rustfmt 的更多信息,请参阅其文档

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.

使用 rustfix 修复你的代码 (Fix Your Code with rustfix)

Fix Your Code with rustfix

rustfix 工具包含在 Rust 安装中,可以自动修复编译器警告,这些警告有明确的纠正问题的方法,很可能就是你想要的。你以前可能见过编译器警告。例如,考虑这段代码:

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. You’ve probably seen compiler warnings before. For example, consider this code:

文件名: src/main.rs

Filename: src/main.rs

fn main() {
    let mut x = 42;
    println!("{x}");
}

在这里,我们将变量 x 定义为可变的,但我们从未实际修改它。Rust 会就此向我们发出警告:

Here, we’re defining the variable x as mutable, but we never actually mutate it. Rust warns us about that:

$ cargo build
   Compiling myprogram v0.1.0 (file:///projects/myprogram)
warning: variable does not need to be mutable
 --> src/main.rs:2:9
  |
2 |     let mut x = 0;
  |         ----^
  |         |
  |         help: remove this `mut`
  |
  = note: `#[warn(unused_mut)]` on by default

该警告建议我们删除 mut 关键字。我们可以通过运行 cargo fix 命令使用 rustfix 工具自动应用该建议:

The warning suggests that we remove the mut keyword. We can automatically apply that suggestion using the rustfix tool by running the command 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

当我们再次查看 src/main.rs 时,我们会看到 cargo fix 已经修改了代码:

When we look at src/main.rs again, we’ll see that cargo fix has changed the code:

文件名: src/main.rs

Filename: src/main.rs

fn main() {
    let x = 42;
    println!("{x}");
}

变量 x 现在是不可变的,警告不再出现。

The variable x is now immutable, and the warning no longer appears.

你还可以使用 cargo fix 命令在不同的 Rust 版本 (editions) 之间迁移代码。版本在附录 E中介绍。

You can also use the cargo fix command to transition your code between different Rust editions. Editions are covered in Appendix E.

使用 Clippy 获得更多 Lints (More Lints with Clippy)

More Lints with Clippy

Clippy 工具是一个 lint 集合,用于分析你的代码,以便你可以发现常见错误并改进你的 Rust 代码。Clippy 包含在标准的 Rust 安装中。

The Clippy tool is a collection of lints to analyze your code so that you can catch common mistakes and improve your Rust code. Clippy is included with standard Rust installations.

要在任何 Cargo 项目上运行 Clippy 的 lints,请输入以下内容:

To run Clippy’s lints on any Cargo project, enter the following:

$ cargo clippy

例如,假设你编写了一个程序,该程序使用数学常数(如圆周率 pi)的近似值,如下程序所示:

For example, say you write a program that uses an approximation of a mathematical constant, such as pi, as this program does:

fn main() {
    let x = 3.1415;
    let r = 8.0;
    println!("the area of the circle is {}", x * r * r);
}

在此项目上运行 cargo clippy 会导致此错误:

Running cargo clippy on this project results in this error:

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

此错误让你知道 Rust 已经定义了更精确的 PI 常数,如果你改用该常数,你的程序将更准确。然后,你应该修改代码以使用 PI 常数。

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.

以下代码不会导致 Clippy 产生任何错误或警告:

The following code doesn’t result in any errors or warnings from Clippy:

fn main() {
    let x = std::f64::consts::PI;
    let r = 8.0;
    println!("the area of the circle is {}", x * r * r);
}

有关 Clippy 的更多信息,请参阅其文档

For more information on Clippy, see its documentation.

使用 rust-analyzer 进行 IDE 集成 (IDE Integration Using rust-analyzer)

IDE Integration Using rust-analyzer

为了帮助进行 IDE 集成,Rust 社区建议使用 rust-analyzer。该工具是一组以编译器为中心的实用程序,它们遵循语言服务器协议 (Language Server Protocol, LSP),该协议是 IDE 和编程语言之间通信的规范。不同的客户端可以使用 rust-analyzer,例如 Visual Studio Code 的 Rust analyzer 插件

To help with IDE integration, the Rust community recommends using rust-analyzer. This tool is a set of compiler-centric utilities that speak 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.

请访问 rust-analyzer 项目的主页获取安装说明,然后在你的特定 IDE 中安装语言服务器支持。你的 IDE 将获得自动补全、跳转到定义和内联错误等功能。

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 capabilities such as autocompletion, jump to definition, and inline errors.

E - 版本 (E - Editions)


x-i18n: generated_at: “2026-03-01T09:14:11Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 4f116f147d8f51119240b8aa235be830b86cf1d5f12ebca21c8ceeaa7bcfa73f source_path: appendix-05-editions.md workflow: 16

附录 E:版本 (Appendix E: Editions)

Appendix E: Editions

在第 1 章中,你看到 cargo new 在你的 Cargo.toml 文件中添加了一些关于版本的元数据。这个附录将讨论这代表着什么!

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!

Rust 语言和编译器有一个六周的发布周期,这意味着用户可以不断获得新功能。其他编程语言发布较大更改的频率较低;Rust 发布较小更新的频率更高。一段时间后,所有这些微小的变化都会累积起来。但是,在不同的发布版本之间,很难回顾并说:“哇,从 Rust 1.10 到 Rust 1.31,Rust 发生了很大变化!”

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 版本 (edition)。每个版本都将已经上线的功能整合到一个清晰的软件包中,并带有完整更新的文档和工具。新版本作为通常的六周发布过程的一部分发布。

Every three years or so, 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.

版本对不同的人有不同的目的:

Editions serve different purposes for different people:

  • 对于活跃的 Rust 用户,新版本将渐进式的变化整合到一个易于理解的包中。
  • 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 版本可用:Rust 2015、Rust 2018、Rust 2021 和 Rust 2024。本书使用 Rust 2024 版本的惯用写法编写。

At the time of this writing, four Rust editions are available: Rust 2015, Rust 2018, Rust 2021, and Rust 2024. This book is written using Rust 2024 edition idioms.

Cargo.toml 中的 edition 键指示编译器应为你的代码使用哪个版本。如果该键不存在,出于向后兼容性的原因,Rust 使用 2015 作为版本值。

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.

每个项目都可以选择使用默认 2015 版本以外的其他版本。版本可能包含不兼容的更改,例如包含一个与代码中标识符冲突的新关键字。但是,除非你选择这些更改,否则即使你升级了所使用的 Rust 编译器版本,你的代码也将继续编译。

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.

所有 Rust 编译器版本都支持在该编译器发布之前存在的任何版本,并且它们可以将任何受支持版本的 crates 链接在一起。版本的更改仅影响编译器初始解析代码的方式。因此,如果你使用的是 Rust 2015 且你的依赖项之一使用的是 Rust 2018,你的项目将能够编译并使用该依赖项。相反的情况(你的项目使用 Rust 2018 且依赖项使用 Rust 2015)同样有效。

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 版本的开发人员都将随着新的稳定版本的发布而继续看到改进。但是,在某些情况下(主要是添加新关键字时),某些新功能可能仅在以后的版本中可用。如果你想利用这些功能,则需要切换版本。

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 版本指南》(The Rust Edition Guide)edition-guide。这是一本完整的书,列举了版本之间的差异,并解释了如何通过 cargo fix 自动将代码升级到新版本。

For more details, see The Rust Edition Guide. This is a complete book that enumerates the differences between editions and explains how to automatically upgrade your code to a new edition via cargo fix.

F - 本书的翻译版 (F - Translations of the Book)


x-i18n: generated_at: “2026-03-01T09:15:11Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: abaff80fa1c28b88d5e48518f3954b72b320135787abe542d9b7f09ac51336a2 source_path: appendix-06-translation.md workflow: 16

附录 F:本书的翻译版 (Appendix F: Translations of the Book)

Appendix F: Translations of the Book

针对英语以外的其他语言。大多数翻译版本仍在进行中;请参阅翻译标签来帮助我们或告知我们新翻译的信息!

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!

G - Rust 是如何开发的与 “Nightly Rust” (G - How Rust is Made and “Nightly Rust”)


x-i18n: generated_at: “2026-03-01T09:16:47Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 87fcdd7cc2df1a8430a9044369e077ac60eda4a0902999542a984dc92a2ddc0c source_path: appendix-07-nightly-rust.md workflow: 16

附录 G - Rust 是如何开发的与 “Nightly Rust” (Appendix G - How Rust is Made and “Nightly Rust”)

Appendix G - How Rust is Made and “Nightly Rust”

本附录介绍了 Rust 是如何开发的,以及这会对你作为一名 Rust 开发者产生什么影响。

This appendix is about how Rust is made and how that affects you as a Rust developer.

保持稳定性且不陷于停滞 (Stability Without Stagnation)

Stability Without Stagnation

作为一门语言,Rust 非常重视代码的稳定性。我们希望 Rust 能够成为你可以信赖的坚实基石,如果事物总是在不断变化,那是不可能实现的。与此同时,如果我们不能试验新特性,我们可能直到发布后才能发现重大的缺陷,而那时我们已经无法再进行更改了。

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.

我们对这个问题的解决方案被称为“保持稳定性且不陷于停滞 (stability without stagnation)”,我们的指导原则是:你永远不必担心升级到新的稳定版 (stable) Rust。每一次升级都应该是无痛的,同时也应该为你带来新特性、更少的 Bug 和更快的编译速度。

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.

鸣笛启程!发布通道与乘坐列车 (Choo, Choo! Release Channels and Riding the Trains)

Choo, Choo! Release Channels and Riding the Trains

Rust 的开发遵循“列车进度表 (train schedule)”。也就是说,所有的开发工作都在 Rust 仓库的主分支 (main branch) 上完成。发布过程遵循软件发布列车模型 (software release train model),这一模型已被 Cisco IOS 和其他软件项目所采用。Rust 有三个发布通道 (release channels):

Rust development operates on a train schedule. That is, all development is done in the main 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:

  • 每夜版 (Nightly)
  • Nightly
  • 测试版 (Beta)
  • Beta
  • 稳定版 (Stable)
  • Stable

大多数 Rust 开发者主要使用稳定版 (stable) 通道,但那些想要尝试实验性新特性的人可能会使用每夜版 (nightly) 或测试版 (beta)。

Most Rust developers primarily use the stable channel, but those who want to try out experimental new features may use nightly or beta.

这里有一个关于开发和发布流程如何运作的例子:假设 Rust 团队正在致力于 Rust 1.5 的发布。虽然那次发布发生在 2015 年 12 月,但它能为我们提供真实的版本号参考。当一个新特性被添加到 Rust 时:一个新的提交进入了主分支。每天晚上,都会产生一个新的 Rust 每夜版 (nightly)。每一天都是发布日,这些发布版本由我们的发布基础设施自动创建。因此,随着时间的推移,我们的发布看起来是这样的,每晚一次:

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 main 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:

nightly: * - - * - - *

每隔六周,就到了准备新版本的时候了!Rust 仓库的 beta 分支会从每夜版 (nightly) 使用的主分支中分出来。现在,有了两个发布版本:

Every six weeks, it’s time to prepare a new release! The beta branch of the Rust repository branches off from the main branch used by nightly. Now, there are two releases:

nightly: * - - * - - *
                     |
beta:                *

大多数 Rust 用户并不积极使用测试版 (beta) 发布,但会在其 CI 系统中针对测试版进行测试,以帮助 Rust 发现可能的回归 (regressions)。与此同时,每晚仍然会有每夜版 (nightly) 的发布:

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:

nightly: * - - * - - * - - * - - *
                     |
beta:                *

假设发现了一个回归。幸好我们在回归潜入稳定版 (stable) 发布之前有时间测试测试版 (beta) 发布!修复补丁会被应用到主分支,这样每夜版 (nightly) 就修复了,然后该修复会被移植回 (backported) 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 the main branch, so that nightly is fixed, and then the fix is backported to the beta branch, and a new release of beta is produced:

nightly: * - - * - - * - - * - - * - - *
                     |
beta:                * - - - - - - - - *

在第一个测试版 (beta) 创建六周后,就到了发布稳定版 (stable) 的时候了!stable 分支是从 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:

nightly: * - - * - - * - - * - - * - - * - * - *
                     |
beta:                * - - - - - - - - *
                                       |
stable:                                *

万岁!Rust 1.5 完成了!然而,我们忘了一件事:因为六周已经过去了,我们还需要下一个 Rust 版本 1.6 的新测试版 (beta)。因此,在 stablebeta 分离出来后,下一个版本的 beta 又会从 nightly 分离出来:

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:

nightly: * - - * - - * - - * - - * - - * - * - *
                     |                         |
beta:                * - - - - - - - - *       *
                                       |
stable:                                *

这被称为“列车模型 (train model)”,因为每隔六周,一个发布版本就会“离开车站”,但在作为稳定版发布到达之前,它仍然需要经历测试版 (beta) 通道的旅程。

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 像时钟一样每六周发布一次。如果你知道一个 Rust 发布版本的日期,你就能知道下一个版本的日期:就在六周后。每六周安排一次发布的一个好处是,下一班列车很快就会到来。如果某个特性碰巧错过了某个特定版本,也不必担心:下一个版本很快就会到来!这有助于减轻在临近发布截止日期时强行塞入可能未经打磨的特性的压力。

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 的下一个构建版本,并亲自验证升级是否容易:如果测试版 (beta) 发布的运行结果不如预期,你可以向团队报告并在下一个稳定版发布之前进行修复!测试版发布中的破坏性变化相对较少,但 rustc 仍然是一个软件,Bug 确实存在。

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.

维护周期 (Maintenance time)

Maintenance time

Rust 项目支持最新的稳定版本。当一个新的稳定版本发布时,旧版本就达到了生命周期终点 (EOL)。这意味着每个版本都会获得六周的支持。

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.

不稳定特性 (Unstable Features)

Unstable Features

这个发布模型还有一个限制:不稳定特性 (unstable features)。Rust 使用一种称为“功能标识 (feature flags)”的技术来决定在给定的发布版本中启用哪些特性。如果一个新特性正在开发中,它会进入主分支,从而进入每夜版 (nightly),但隐藏在功能标识之后。如果你作为用户希望尝试开发中的特性,你可以这样做,但你必须使用 Rust 每夜版发布,并在源代码中标注相应的标识以选择加入。

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 the main branch, 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 的测试版 (beta) 或稳定版 (stable) 发布,你将无法使用任何功能标识。这是允许我们在宣布新特性永久稳定之前获得实际使用经验的关键。那些希望尝试前沿特性的人可以这样做,而那些想要获得坚实体验的人可以坚持使用稳定版,并知晓他们的代码不会崩溃。保持稳定性且不陷于停滞。

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.

本书仅包含关于稳定特性的信息,因为开发中的特性仍在不断变化,在本书编写完成到它们在稳定构建中启用之间,它们肯定会有所不同。你可以在线查找仅限每夜版的特性的文档。

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 与 Rust 每夜版的作用 (Rustup and the Role of Rust Nightly)

Rustup and the Role of Rust Nightly

Rustup 让你能够轻松地在 Rust 的不同发布通道之间进行切换,无论是在全局范围内还是针对单个项目。默认情况下,你将安装稳定版 (stable) 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 toolchain install nightly

你也可以查看使用 rustup 安装的所有工具链 (toolchains,即 Rust 的发布版本及相关组件)。这里有一位作者在 Windows 电脑上的示例:

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 toolchain list
stable-x86_64-pc-windows-msvc (default)
beta-x86_64-pc-windows-msvc
nightly-x86_64-pc-windows-msvc

如你所见,稳定版工具链是默认的。大多数 Rust 用户在大部分时间都使用稳定版。你可能希望在大部分时间使用稳定版,但在特定的项目中使用每夜版,因为你关注某个前沿特性。为此,你可以在该项目的目录中使用 rustup override 来设置每夜版工具链,使其成为你在该目录下时 rustup 应使用的工具链:

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:

$ cd ~/projects/needs-nightly
$ rustup override set nightly

现在,每当你在 ~/projects/needs-nightly 内部调用 rustccargo 时,rustup 都会确保你使用的是每夜版 Rust,而不是默认的稳定版 Rust。当你有很多 Rust 项目时,这非常方便!

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!

RFC 流程与团队 (The RFC Process and Teams)

The RFC Process and Teams

那么,你该如何了解这些新特性呢?Rust 的开发模型遵循“征求修正意见 (Request For Comments, RFC) 流程”。如果你想改进 Rust,你可以写一份提案,称为 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.

任何人都可以编写 RFC 来改进 Rust,提案由 Rust 团队进行审查和讨论,该团队由许多主题小组组成。Rust 官网上有团队的完整列表,其中包括项目每个领域的团队:语言设计、编译器实现、基础设施、文档等。相应的团队会阅读提案和评论,撰写自己的评论,并最终达成接受或拒绝该特性的共识。

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.

如果特性被接受,Rust 仓库中就会开启一个 issue,然后有人可以去实现它。实现它的人很可能并不是最初提出该特性的人!当实现准备就绪时,它会进入主分支,并隐藏在功能门 (feature gate) 之后,正如我们在“不稳定特性”部分所讨论的那样。

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 main branch behind a feature gate, as we discussed in the “Unstable Features” section.

一段时间后,一旦使用每夜版发布的 Rust 开发者能够尝试新特性,团队成员将讨论该特性及其在每夜版上的运行效果,并决定是否将其引入稳定版 Rust。如果决定推进,功能门将被移除,该特性现在被视为稳定的了!它将乘坐列车进入 Rust 的新稳定版发布。

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.