繁体   English   中英

理解 Rust 函数参数类型声明

[英]Understanding Rust function parameter type declaration

我正在阅读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是一个引用,为什么我不必在将其值与 limit 或同样令人惊讶的值进行比较之前取消引用它? 为什么我可以将它直接传递给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_squaredi32而不是&i32 看起来这里正在发生某种模式匹配/解构,但我找不到相关文档。

您正在使用函数参数解构

|&n_squared| n_squared < upper

在功能上等同于:

|n_squared| *n_squared < upper

为了更好地理解这一点,假设您将 &(i32, i32) 类型的元组传递给 lambda:

|&(x, y) : &(i32, i32)| x + y

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM