Rust教學
Rust下載和安裝
Rust簡介
Rust Hello World
Rust的特點
Rust註釋
Rust開發環境安裝
Rust文檔
Rust第一個程序
Rust格式化打印
Rust調試
Rust顯示
測試用例:列表
Rust格式化
Rust原語
Rust常量和運算符
Rust元組
Rust數組和切片
Rust自定義類型
Rust結構
Rust可視性
Rust枚舉
Rust常量
Rust變量綁定
Rust變量綁定-可變性
Rust變量綁定-範圍和陰影
Rust變量綁定-聲明
Rust類型轉換
Rust類型轉換 - 字面量
Rust類型轉換-推導
Rust類型轉換 - 別名
Rust表達式
Rust if/else語句
Rust循環
Rust嵌套和標籤
Rust while循環
Rust for和範圍
Rust匹配/match
Rust匹配析構元組
Rust解構枚舉
Rust指針和引用
Rust解構結構
Rust Guards
Rust綁定
Rust if let
Rust while let
Rust函數
Rust方法
Rust閉包
Rust捕捉
Rust作爲輸入參數
Rust匿名類型
Rust輸入函數
Rust作爲輸出參數
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