显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 # 30. 闭包 ## 学习目标 - 理解闭包是什么以及它与函数的区别。 - 掌握闭包的语法和类型推断。 - 理解闭包如何捕获环境变量。 - 区分 `Fn`、`FnMut`、`FnOnce` 三种 trait。 - 学会将闭包作为函数参数和与迭代器配合使用。 ## 30.1 什么是闭包 闭包(closure)是一种可以捕获其所在作用域变量的匿名函数。与普通函数不同,闭包可以从定义它的环境中“借用”或“移动”变量。 ```rust let factor = 2; let multiply = |x| x * factor; println!("{}", multiply(5)); // 输出: 10 ``` ## 30.2 闭包语法 闭包使用 `|参数| { 表达式 }` 定义: ```rust let add_one = |x| x + 1; let sum = |a, b| a + b; println!("{}", add_one(3)); // 4 println!("{}", sum(2, 3)); // 5 ``` 闭包可以省略参数类型和返回值类型,编译器会根据使用场景推断: ```rust let closure = |x: i32| -> i32 { x + 1 }; ``` ## 30.3 捕获环境 闭包可以捕获其定义环境中的变量: ```rust let mut counter = 0; let mut increment = || { counter += 1; counter }; println!("{}", increment()); // 1 println!("{}", increment()); // 2 ``` 捕获方式取决于闭包如何使用环境变量:借用、可变借用或获取所有权。 ## 30.4 Fn、FnMut、FnOnce Rust 根据闭包对环境变量的捕获方式,将其分为三种 trait: | Trait | 捕获方式 | 调用次数 | | `Fn` | 不可变借用 | 可多次调用 | | `FnMut` | 可变借用 | 可多次调用,但需可变引用 | | `FnOnce` | 获取所有权 | 只能调用一次 | ```rust fn call_with_fn<F>(f: F) where F: Fn(), { f(); f(); } let text = String::from("hello"); let print_text = || println!("{}", text); call_with_fn(print_text); ``` ```rust fn call_with_fnmut<F>(mut f: F) where F: FnMut(), { f(); f(); } let mut counter = 0; let mut inc = || { counter += 1; }; call_with_fnmut(inc); println!("{}", counter); // 2 ``` ```rust fn call_with_fnonce<F>(f: F) where F: FnOnce(), { f(); } let text = String::from("hello"); let consume = || drop(text); call_with_fnonce(consume); // text 已被移动,不能再使用 ``` ## 30.5 闭包作为参数 函数可以接受闭包作为参数,实现灵活的逻辑: ```rust fn process<T, F>(value: T, f: F) -> T where F: Fn(T) -> T, { f(value) } let result = process(5, |x| x * 2); println!("{}", result); // 10 ``` ## 30.6 迭代器与闭包 闭包经常与迭代器适配器一起使用: ```rust let v = vec![1, 2, 3, 4, 5]; let evens: Vec<_> = v.iter() .filter(|x| *x % 2 == 0) .collect(); println!("{:?}", evens); // [2, 4] ``` ```rust let squared: Vec<i32> = v.iter() .map(|x| x * x) .collect(); println!("{:?}", squared); // [1, 4, 9, 16, 25] ``` ## 30.7 闭包与 move 关键字 使用 `move` 关键字可以让闭包获取环境中变量的所有权: ```rust let s = String::from("hello"); let closure = move || println!("{}", s); closure(); // println!("{}", s); // 错误:s 已被移动 ``` > `move` 闭包常用于多线程或需要延长变量生命周期的场景。 ## 30.8 小结 | 特性 | 说明 | 示例 | | 匿名函数 | 没有名字,可内联定义 | `\|x\| x + 1` | | 捕获环境 | 借用或移动外部变量 | `\|\| println!("{}", s)` | | `Fn` | 不可变借用捕获 | 可多次调用 | | `FnMut` | 可变借用捕获 | 需 `mut` 绑定 | | `FnOnce` | 移动捕获 | 只能调用一次 | | `move` | 强制获取所有权 | `move \|\| ...` | ## 30.9 思考题 1. 下面代码为什么会报错?如何修改? ```rust let s = String::from("hello"); let closure = || println!("{}", s); closure(); println!("{}", s); ``` 2. 什么时候应该使用 `move` 闭包? 3. 写一个函数,接收一个整数向量和一个闭包,返回满足闭包条件的所有元素。 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 rust/闭包.txt 最后更改: 2026/08/12 23:56由 张叶安 登录