Closures and Iterators
闭包与迭代器
What you’ll learn: How Rust closures compare to Java lambdas and how iterators relate to the Stream API.
本章将学习: Rust 闭包如何对应 Java lambda,以及迭代器如何对应 Stream API。Difficulty: 🟡 Intermediate
难度: 🟡 中级
Closures feel familiar to Java developers because lambdas are already common. The difference is in capture behavior and ownership.
闭包对 Java 开发者来说不算陌生,因为 lambda 早就很常见了。真正的差异主要落在捕获行为和所有权上。
Closures
闭包
#![allow(unused)]
fn main() {
let factor = 2;
let multiply = |x: i32| x * factor;
}
Rust closures can capture by borrow or by move. That makes them more explicit in ownership-sensitive contexts such as threads and async tasks.
Rust 闭包既可以按借用捕获,也可以按 move 捕获,所以在线程、异步任务这类所有权敏感场景里会更明确。
Fn, FnMut, FnOnce
Fn、FnMut、FnOnce
These traits describe how a closure interacts with captured state:
这三个 trait 描述的是闭包和捕获状态的关系:
Fn: immutable capture
不可变捕获。FnMut: mutable capture
可变捕获。FnOnce: consumes captured values
消耗捕获值。
This is a deeper model than Java lambdas usually expose.
这一层模型比 Java lambda 平时显露出来的语义更深。
Iterators vs Streams
迭代器与 Stream
Both are lazy pipelines. Rust iterators tend to compose with less framework overhead and with stronger compile-time specialization.
两者都是惰性流水线,不过 Rust 迭代器通常框架负担更小,编译期特化更强。
#![allow(unused)]
fn main() {
let result: Vec<_> = values
.iter()
.filter(|x| **x > 10)
.map(|x| x * 2)
.collect();
}
Advice
建议
- closures are easy; closure capture semantics are the real lesson
闭包本身不难,真正要学的是捕获语义。 - iterator chains are normal Rust, not niche functional style
迭代器链是 Rust 日常写法,不是什么小众函数式花活。 - if ownership errors appear in iterator code, inspect whether the chain borrows or consumes values
迭代器代码里一旦冒出所有权报错,先查这条链到底是在借用还是在消耗值。