我已经学会了如何将闭包参数传递给函数,以便我可以调用closure
两次:
let closure = || println!("hello");
fn call<F>(f: &F)
where
F: Fn(),
{
f();
}
call(&closure);
call(&closure);
当我使用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:10:10
|
10 | call(&change_string);
| ^^^^^^^^^^^^^^ types differ in mutability
|
= note: expected type `&mut _`
found type `&[closure@src/main.rs:3:25: 3:53 string:_]`
我该如何解决?
正如错误消息所说:
expected type `&mut _`
found type `&[closure@src/main.rs:3:25: 3:53 string:_]`
它期望对某物(&mut _
(的可变引用,但您正在提供对闭包(&...
(的不可变引用。采用可变引用:
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");
在这种情况下,您根本不需要&mut F
,因为FnMut
是为对FnMut
的可变引用实现的。也就是说,这有效:
fn call(mut f: impl FnMut()) {
f();
}
call(&mut change_string);
call(&mut change_string);