[英]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_while
和filter
接受一個通過引用接受參數的函數。 這對我來說很有意義,您想借用而不是使用地圖中的值。
但是,如果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_squared
是i32
而不是&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.