How can I pass a FnMut closure to a function using a reference in Rust? -


i've learnt how pass closure argument function. below:

let closure = || println!("hello"); fn call<f>(f: &f)     f: fn() {     f(); } call(&closure); call(&closure); 

so can call closure twice.

but when use fnmut:

let mut string: string = "hello".to_owned(); let change_string = || string.push_str(" world"); fn call<f>(mut f: &mut f)     f: fnmut() {     f(); } call(&change_string); call(&change_string); 

it turn out error:

error[e0308]: mismatched types  --> src/main.rs:9:10   | 9 |     call(&change_string);   |          ^^^^^^^^^^^^^^ types differ in mutability   |   = note: expected type `&mut _`              found type `&[closure@src/main.rs:3:25: 3:53 string:_]` 

how can solve it?

as error message says:

expected type `&mut _`    found type `&[closure@src/main.rs:3:25: 3:53 string:_]` 

it expecting mutable reference something (&mut _), providing immutable reference closure (&...). take mutable reference:

call(&mut change_string); 

which leads next error:

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

taking mutable reference requires value mutable:

let mut change_string = || string.push_str(" world"); 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -