Rust閉包

閉包

閉包*在Rust 是一個稍微專業的語法,可以捕捉到封閉的環境函數。 這種語法和能力使它們在運行使用非常方便。一些特性包括:

  • 使用 || 替代 () 圍繞輸入變量。
  • 輸入和返回類型可以推斷出。
  • 輸入變量名稱必須指定。
  • 主體定界 ({}) 是可選的一個表達式。強制性其他。
  • 外環境變量可能被捕獲。
  • 調用閉包和函數與 call(var)是完全一樣的

fn main() {
// Increment via closures and functions.
fn function (i: i32) -> i32 { i + 1 }

// Annotation is identical to function annotation but is optional
// as are the \`{}\` wrapping the body. These nameless functions
// are assigned to appropriately named variables.
let closure\_annotated = |i: i32| -> i32 { i + 1 };
let closure\_inferred  = |i     |          i + 1  ;

let i = 1;
// Call the function and closures.
println!("function: {}", function(i));
println!("annotated closure: {}", closure\_annotated(i));
println!("inferred closure: {}", closure\_inferred(i));

// A closure taking no arguments which returns an \`i32\`.
// The return type is inferred.
let one = || 1;
println!("closure returning one: {}", one());

// It is possible to capture variables from the enclosing
// environment; something which is impossible with functions.
let professor\_x = "Charles Xavier";

// A closure which takes no argument, returning nothing, prints
// a variable from the enclosing scope.
let print = || println!("Professor X's name is: {}", professor\_x);

// Call the closure.
print();

}

*.也被稱爲lambda表達式或匿名函數。