Rust捕捉

捕捉

閉包是內在的靈活性,並會做哪些需要的功能,使撤銷工作無需註釋。這允許捕捉靈活適應使用的情況,有時會移動,有時借用。閉包可以捕捉變量:

  • 通過參考: &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.

}

也可以參考:

Box 和 std::mem::drop