0
私は関数にクロージャ引数を渡す方法を学びました。以下のように:Rustのリファレンスを使用して関数にFnMutクロージャを渡すにはどうすればよいですか?
let closure = || println!("hello");
fn call<F>(f: &F)
where F: Fn()
{
f();
}
call(&closure);
call(&closure);
closure
を2回呼び出すことができます。
しかし、ときに私がFnMut
を使用します。
let mut string: String = "hello".to_owned();
let change_string = || string.push_str(" world");
fn call<F>(mut f: &mut F)
where F: FnMut()
{
f();
}
call(&change_string);
call(&change_string);
それはエラーを消します:
error[E0308]: mismatched types
--> src/main.rs:9:10
|
9 | call(&change_string);
| ^^^^^^^^^^^^^^ types differ in mutability
|
= note: expected type `&mut _`
found type `&[[email protected]/main.rs:3:25: 3:53 string:_]`
私はそれを解決できますか?エラーメッセージとして
あなたの閉鎖は、 'する必要がありますmut'ableで、 'call'に変更可能な参照を渡す必要があります。 – ljedrz
'change_string'と' call(&change_string) 'の前に' mut'を追加してコードを実行します。ありがとうございました! – wind2412