学习Rust的第23天:闭包

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: {:?}&#
  • 35
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老父亲的能量嘎嘣脆

感谢支持,共同成长

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值