如何使用Rust中的引用将FnMut闭包传递给函数? [英] How can I pass a FnMut closure to a function using a reference in Rust?
本文介绍了如何使用Rust中的引用将FnMut闭包传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经学习了如何将闭包参数传递给函数,因此可以两次调用 closure
:
I've learned how to pass a closure argument to a function so I can call closure
twice:
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 _
)的可变引用,但您提供的是不变的引用闭包(& ...
)。采取可变的参考:
It is expecting a mutable reference to something (&mut _
), but you are providing an immutable reference to a closure (&...
). Take a mutable reference:
call(&mut change_string);
哪个会导致下一个错误:
Which leads to the next error:
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
获取可变引用值本身是可变的:
Taking a mutable reference requires that the value itself be mutable:
let mut change_string = || string.push_str(" world");
在这种情况下,您不需要完全采用& mut F
,因为实现了 FnMut
用于可变引用 FnMut
。也就是说,这可行:
In this case, you don't need to take a &mut F
at all, as FnMut
is implemented for mutable references to FnMut
. That is, this works:
fn call(mut f: impl FnMut()) {
f();
}
call(&mut change_string);
call(&mut change_string);
这篇关于如何使用Rust中的引用将FnMut闭包传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文