Rust 闭包提供了简洁、富有表现力的匿名函数来捕获周围的变量。它们简化了代码,提供了存储、参数传递和函数重构方面的灵活性。它们与泛型的交互增强了灵活性,而捕获模式则促进了有效的所有权和可变性管理。从本质上讲,闭包是 Rust 的基础,可以提高代码的清晰度和简洁性。
Introduction 介绍
We used a closure in themini_grep
project, here’s what it looked like
我们在 mini_grep
项目中使用了闭包,如下所示
let config = Config::new(&args).unwrap_or_else(|err|{
eprintln!("Problem parsing arguments: {}",err);
eprintln!("Expected: {} search_query filename", args[0]);
process::exit(1);
});
Closures are like anonymous functions, and we can store them in variables as well, pass them as function arguments etc.
闭包就像匿名函数,我们也可以将它们存储在变量中,将它们作为函数参数传递等。
In Rust, closures are anonymous functions that can capture variables from their surrounding environment. They are similar to lambda functions or blocks in other programming languages. Closures in Rust have a flexible and powerful syntax, allowing them to be used in various contexts.
在 Rust 中,闭包是可以从周围环境捕获变量的匿名函数。它们类似于其他编程语言中的 lambda 函数或块。 Rust 中的闭包具有灵活而强大的语法,允许它们在各种上下文中使用。
fn main() {
let add_one = |x| x + 1;
let result = add_one(5);
println!("Result: {}", result); // Output: 6
}
In this example, add_one
is a closure that takes one parameter x
and returns x + 1
. It's assigned to a variable, and then called with an argument 5
. The result is printed out.
在此示例中, add_one
是一个闭包,它采用一个参数 x
并返回 x + 1
。它被分配给一个变量,然后使用参数 5
进行调用。结果被打印出来。
This is a basic example of what a closure looks like.
这是闭包的基本示例。
Refactoring Functions to Closures
将函数重构为闭包
Refactoring functions with closures can often lead to more concise and expressive code.
使用闭包重构函数通常可以生成更简洁、更具表现力的代码。
Let’s consider a function that applies a given operation to each element in a vector:
让我们考虑一个将给定操作应用于向量中每个元素的函数:
fn apply_operation_to_vec(values: Vec<i32>, operation: fn(i32) -> i32) -> Vec<i32> {
let mut result = Vec::new();
for value in values {
result.push(operation(value));
}
result
}
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
let values = vec![1, 2, 3, 4, 5];
let doubled_values = apply_operation_to_vec(values, double);
println!("Doubled values: {:?}&#