[英]Understanding Rust function parameter type declaration
I was reading the chapter on higher order functions of Rust by Example .我正在阅读Rust by Example 的高阶函数一章。 Where they present the following canonical 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
}
Simple enough.足够简单。 But I realized that I don't understand the type of parameter n_squared
.但我意识到我不了解参数n_squared
的类型。 Both take_while
and filter
accept a function that takes a parameter by reference. take_while
和filter
接受一个通过引用接受参数的函数。 That makes sense to me, you want to borrow instead of consuming the values in the map.这对我来说很有意义,您想借用而不是使用地图中的值。
However, if n_squared
is a reference, why don't I have to dereference it before comparing its value to limit or equally surprising;但是,如果n_squared
是一个引用,为什么我不必在将其值与 limit 或同样令人惊讶的值进行比较之前取消引用它? why can I pass it directly to is_odd()
without dereferencing?为什么我可以将它直接传递给is_odd()
而无需取消引用?
Ie why isn't it?即为什么不是?
|&n_squared| *n_squared < upper
When I try that the compiler gives the following error:当我尝试编译器给出以下错误时:
error[E0614]: type `{integer}` cannot be dereferenced
--> src\higherorder.rs:13:34
|
13 | .take_while(|&n_squared| *n_squared <= upper)
|
Indicating that n_squared
is an i32
and not &i32
.表示n_squared
是i32
而不是&i32
。 Looks like some sort pattern matching/destructuring is happening here, but I was unable to find the relevant documentation.看起来这里正在发生某种模式匹配/解构,但我找不到相关文档。
You are using function parameter destructuring :您正在使用函数参数解构:
|&n_squared| n_squared < upper
is functionally equivalent to:在功能上等同于:
|n_squared| *n_squared < upper
To understand this better, imagine you're passing a tuple of type &(i32, i32) to a lambda:为了更好地理解这一点,假设您将 &(i32, i32) 类型的元组传递给 lambda:
|&(x, y) : &(i32, i32)| x + y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.