鍍金池/ 教程/ Java/ Rust捕捉
Rust解構(gòu)枚舉
Rust類型轉(zhuǎn)換 - 別名
Rust枚舉
Rust閉包
Rust捕捉
Rust while let
Rust調(diào)試
Rust教程
Rust數(shù)組和切片
Rust自定義類型
Rust綁定
Rust for和范圍
Rust類型轉(zhuǎn)換
Rust作為輸入?yún)?shù)
Rust Hello World
Rust格式化
Rust類型轉(zhuǎn)換 - 字面量
Rust變量綁定-聲明
Rust常量
Rust循環(huán)
Rust Guards
Rust作為輸出參數(shù)
Rust結(jié)構(gòu)
Rust指針和引用
Rust解構(gòu)結(jié)構(gòu)
Rust方法
Rust下載和安裝
Rust函數(shù)
Rust匹配/match
Rust類型轉(zhuǎn)換-推導(dǎo)
Rust while循環(huán)
Rust嵌套和標簽
Rust匹配析構(gòu)元組
Rust顯示
Rust變量綁定-范圍和陰影
Rust表達式
Rust if/else語句
Rust變量綁定-可變性
Rust文檔
Rust匿名類型
Rust變量綁定
Rust注釋
Rust原語
Rust可視性
測試用例:列表
Rust格式化打印
Rust元組
Rust if let
Rust輸入函數(shù)
Rust常量和運算符

Rust捕捉

捕捉

閉包是內(nèi)在的靈活性,并會做哪些需要的功能,使撤銷工作無需注釋。這允許捕捉靈活適應(yīng)使用的情況,有時會移動,有時借用。閉包可以捕捉變量:

  • 通過參考: &T
  • 通過可變引用: &mut T
  • 通過傳值: T

它們優(yōu)先通過引用捕獲變量并僅在需要時使用。

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


上一篇:Rust常量下一篇:Rust循環(huán)