[英]How can I use a function as a closure when the function needs to take a reference to the closures argument?
[英]How can I pass a FnMut closure to a function using a reference in Rust?
我已經學會了如何將一個閉包參數傳遞給一個函數,所以我可以調用兩次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
的可變引用FnMut
。 也就是說,這有效:
fn call(mut f: impl FnMut()) {
f();
}
call(&mut change_string);
call(&mut change_string);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.