为什么没有为包裹FnMut的`std :: cell :: RefMut`实现DerefMut?

问题描述 投票:1回答:1

我想将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个回答
0
投票

这看起来像是编译器错误。似乎这里报道的可能是同一问题:Cannot borrow as mutable despite DerefMut

如果您进行更改,您的代码将可用

cl.borrow_mut()();

改为成为

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

在调用它之前将值显式地取消引用为可变的。

© www.soinside.com 2019 - 2024. All rights reserved.