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

时间:2017-03-28 12:09:01

标签: reference rust closures

我已经学会了如何将闭包参数传​​递给函数,以便我可以调用UpdateBuilder<Customer, Integer> updateBuilder = customerDao.updateBuilder(); updateBuilder.updateColumnValue( "customerAddress1", address ); updateBuilder.where().eq( "id", id ); updateBuilder.update(); 两次:

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);

我该如何解决?

1 个答案:

答案 0 :(得分:0)

正如错误消息所示:

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);