捕捉
闭包是内在的灵活性,并会做哪些需要的功能,使撤销工作无需注释。这允许捕捉灵活适应使用的情况,有时会移动,有时借用。闭包可以捕捉变量:
-
通过参考:%uA0
&T
-
通过可变引用:%uA0
&mut T
-
通过传值:%uA0
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&apost // 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. }
也可以参考:
Box%uA0和%uA0std::mem::drop