問題一覧に戻る
中級クロージャ
問題76: クロージャの型
クロージャは変数のキャプチャ方法によってFn、FnMut、FnOnceトレイトを実装します。Fnは不変借用、FnMutは可変借用、FnOnceは所有権を取ります。moveキーワードは所有権キャプチャを強制します。これらのトレイトの理解は、関数へのクロージャ渡しや構造体への格納に重要です。
// Fnトレイト
fn apply_fn<F>(f: F) -> i32
where F: () -> i32
{
f()
}
// FnMutトレイト
fn apply_twice<F>(mut f: F) -> i32
where F: () -> i32
{
f() + f()
}
// FnOnceトレイト
fn consume<F>(f: F) -> String
where F: () -> String
{
f()
}
fn main() {
let x = 5;
// Fnクロージャ
let double = x * 2;
println!("{}", apply_fn(double));
// FnMutクロージャ
let mut count = 0;
let mut counter = {
count 1;
count
};
println!("{}", apply_twice(counter));
// moveクロージャ
let s = String::from("hello");
let take_s = s;
println!("{}", consume(take_s));
}