了解Rust函数参数类型声明

问题描述 投票:1回答:1

我正在读chapter on higher order functions of Rust by Example。他们在哪里提出以下规范示例:

fn is_odd(n: u32) -> bool {
    n % 2 == 1
}

fn main() {
   let upper = 1000;

   println!("imperative style: {}", acc);

   let sum_of_squared_odd_numbers: u32 =
       (0..).map(|n| n * n)                             // All natural numbers squared
            .take_while(|&n_squared| n_squared < upper) // Below upper limit
            .filter(|&n_squared| is_odd(n_squared))     // That are odd
            .fold(0, |acc, n_squared| acc + n_squared); // Sum them
}

很简单。但我意识到我不理解参数n_squared的类型。 take_whilefilter都接受一个通过引用获取参数的函数。这对我来说很有意义,你想借用而不是消耗地图中的值。

但是,如果n_squared是一个参考,为什么我不必去除它之前将它的值比作限制或等于令人惊讶;为什么我可以直接将它传递给is_odd()而无需解除引用?

即为什么不呢?

   |&n_squared| *n_squared < upper

当我尝试编译器时出现以下错误:

error[E0614]: type `{integer}` cannot be dereferenced
  --> src\higherorder.rs:13:34
   |
13 |         .take_while(|&n_squared| *n_squared <= upper)
   |      

表明n_squared是i32而不是&i32。看起来这里发生了一些排序模式匹配/解构,但我无法找到相关文档。

rust
1个回答
5
投票

您正在使用function parameter destructuring

|&n_squared| n_squared < upper

在功能上等同于:

|n_squared| *n_squared < upper

为了更好地理解这一点,想象一下你将类型&(i32,i32)的元组传递给lambda:

|&(x, y) : &(i32, i32)| x + y
© www.soinside.com 2019 - 2024. All rights reserved.