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


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.