|x:u8| -> u8
{
let y = x +1;
y
};
|| 45;
|x:u8| x + 1;
|x:u8| -> u8 { x + 1 };
let y = |x:u32| x+10;
print!("{}\n",y(5))

//如果只定义不调用,会报错
let add = |a|{a+1};
add(1);//推导出类型完成计算
如果有两次调用,则第二次推导失败
//如果只定义不调用,会报错
let add = |a|{a+1};
add(1);
add(2.0);
let str = (|x:String|x + &" world".to_string())("hello".to_string());
print!("{}\n",str);
let m = 5;
let add = |a|{a+m};//这里捕获了当前环境外部m的值
print!("{}\n",add(10));//输出15
闭包捕获变量关联的trait定义
pub trait FnOnce<Args> {
type Output;
fn call_once(self, args: Args) -> Self::Output;
}
pub trait FnMut<Args>: FnOnce<Args> {
fn call_mut(&mut self, args: Args) -> Self::Output;
}
pub trait Fn<Args>: FnMut<Args> {
fn call(&self, args: Args) -> Self::Output;
}
7.闭包作为函数参数传递
这样写是不可以的,因为闭包不属于任何类型,本质闭包是trait
fn main()
{
let x = |y:u16| {y+10};
add(x);
}
fn add(x : u16)
{
x(10);
}
这两种写法都可以:
fn main()
{
let x = |y|{print!("{} \n",y)};
foo_1(x);
}
fn foo_1<F : Fn(u16)>(x: F)
{
x(5);
}
fn foo_2(x: impl Fn(u16))
{
x(10);
}
fn return_closure() -> Fn(i32) -> i32
{
|x| x+1
}
