【问题标题】:How can I pass a FnMut closure to a function using a reference in Rust?如何使用 Rust 中的引用将 FnMut 闭包传递给函数?
【发布时间】:2017-03-28 12:09:01
【问题描述】:

我已经学会了如何将闭包参数传​​递给函数,这样我就可以调用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:_]`

我该如何解决?

【问题讨论】:

    标签: reference rust closures


    【解决方案1】:

    正如错误消息所说:

    expected type `&mut _`
       found type `&[closure@src/main.rs:3:25: 3:53 string:_]`
    

    它期望对 something (&amp;mut _) 的可变引用,但您正在提供对闭包 (&amp;...) 的不可变引用。获取可变引用:

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

    在这种情况下,您根本不需要使用&amp;mut F,因为FnMut 是针对FnMut 的可变引用实现的。也就是说,这行得通:

    fn call(mut f: impl FnMut()) {
        f();
    }
    
    call(&mut change_string);
    call(&mut change_string);
    

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2015-07-22
      相关资源
      最近更新 更多