【问题标题】:why DerefMut is not implemented for `std::cell::RefMut<'_, [..]>` which wraps FnMut?为什么没有为包装 FnMut 的`std::cell::RefMut<'_, [..]>` 实现 DerefMut?
【发布时间】:2020-05-07 03:24:02
【问题描述】:

我想将 FnMut 闭包包装在 RefCell 中,如下所示:

fn borrow_mut_closure() {
    let mut temp = 3i32;
    let cl = RefCell::new(move || {
        temp += 1;
        println!("{}", temp);
    });
    cl.borrow_mut()();
}

但令我惊讶的是,编译器报告:

cannot borrow data in a dereference of `std::cell::RefMut<'_, [closure@src/main.rs:17:25: 20:4 temp:i32]>` as mutable

cannot borrow as mutable

help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `std::cell::RefMut<'_, [closure@src/main.rs:17:25: 20:4 temp:i32]>`rustc(E0596)

但为什么不为此实施呢?我该如何克服呢?

【问题讨论】:

    标签: rust closures mutable


    【解决方案1】:

    这看起来像一个编译器错误。看起来可能与此处报告的问题相同:Cannot borrow as mutable despite DerefMut

    如果您更改,您的代码将起作用

    cl.borrow_mut()();
    

    改为

    (&mut *cl.borrow_mut())();
    

    在调用它之前显式取消引用该值作为可变值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 2017-10-27
      • 2017-01-03
      • 1970-01-01
      相关资源
      最近更新 更多