Rust闭包

闭包*在Rust 是一个稍微专业的语法,可以捕捉到封闭的环境函数。 这种语法和能力使它们在运行使用非常方便。一些特性包括:

  • 使用 || 替代 () 围绕输入变量。
  • 输入和返回类型可以推断出。
  • 输入变量名称必须指定。
  • 主体定界 ({}) 是可选的一个表达式。强制性其他。
  • 外环境变量可能被捕获。
  • 调用闭包和函数与 call(var)完全一样的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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表达式或匿名函数。 
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3