繁体   English   中英

如何使用Rust中的引用将FnMut闭包传递给函数?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM