闭包是内在的灵活性,并会做哪些需要的功能,使撤销工作无需注释。这允许捕捉灵活适应使用的情况,有时会移动,有时借用。闭包可以捕捉变量:
&T
&mut T
T
它们优先通过引用捕获变量并仅在需要时使用。
fn main() { |
let color = "green"; |
// A closure to print `color` which immediately borrows (`&`) |
// `color` and stores the borrow and closure in the `print` |
// variable. It will remain borrowed until `print` goes out of |
// scope. `println!` only requires `by reference` so it doesn't |
// impose anything more restrictive. |
let print = || println!("`color`: {}", color); |
// Call the closure using the borrow. |
print(); |
print(); |
let mut count = 0; |
// A closure to increment `count` could take either `&mut count` |
// or `count` but `&mut count` is less restrictive so it takes |
// that. Immediately borrows `count`. |
// |
// A `mut` is required on `inc` because a `&mut` is stored inside. |
// Thus, calling the closure mutates the closure which requires |
// a `mut`. |
let mut inc = || { |
count += 1; |
println!("`count`: {}", count); |
}; |
// Call the closure. |
inc(); |
inc(); |
//let reborrow = &mut count; |
// ^ TODO: try uncommenting this line. |
// A non-copy type. |
let movable = Box::new(3); |
// `drop` requires `T` so this must take by value. A copy type |
// would copy into the closure leaving the original untouched. |
// A non-copy must move and so `movable` immediately moves into |
// the closure. |
let consume = || { |
println!("`movable`: {:?}", movable); |
drop(movable); |
}; |
// `consume` consumes the variable so this can only be called once. |
consume(); |
//consume(); |
// ^ TODO: Try uncommenting this line. |
} |