函数式语言特性:迭代器和闭包
Functional Language Features: Iterators and Closures
Rust 的设计从许多现有的语言和技术中汲取了灵感,其中一个显著的影响就是“函数式编程”。以函数式风格编程通常包括将函数作为值使用,例如将其作为参数传递、从其他函数返回、将其赋值给变量以供以后执行等等。
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),一种可以存储在变量中的类似函数的结构
-
Closures, a function-like construct you can store in a variable
-
迭代器(Iterators),一种处理一系列元素的方式
-
Iterators, a way of processing a series of elements
-
如何使用闭包和迭代器来改进第 12 章中的 I/O 项目
-
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.