2017-03-28 8 views
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:_]` 

私はそれを解決できますか?エラーメッセージとして

+1

あなたの閉鎖は、 'する必要がありますmut'ableで、 'call'に変更可能な参照を渡す必要があります。 – ljedrz

+1

'change_string'と' call(&change_string) 'の前に' mut'を追加してコードを実行します。ありがとうございました! – wind2412

答えて

0

は言う:それは何か&mut _)に変更可能な参照を期待していますが、クロージャ(&...)への不変の参照を提供している

expected type `&mut _` 
    found type `&[[email protected]/main.rs:3:25: 3:53 string:_]` 

。変更可能な参照してください:次のエラーにつながる

call(&mut change_string); 

error: cannot borrow immutable local variable `change_string` as mutable 
--> src/main.rs:9:15 
    | 
3 |  let change_string = || string.push_str(" world"); 
    |   ------------- use `mut change_string` here to make mutable 
... 
9 |  call(&mut change_string); 
    |    ^^^^^^^^^^^^^ cannot borrow mutably 

変更可能な参照を取るには、値そのものが変更可能であることを要求:

let mut change_string = || string.push_str(" world"); 
関連する問題