我有这样的事情:
use std::sync::Arc;
fn main() {
let arc = Arc::new(42);
move || { arc.clone() };
move || { arc.clone() };
}
Run Code Online (Sandbox Code Playgroud)
我正进入(状态:
error[E0382]: capture of moved value: `arc`
--> src/main.rs:6:19
|
5 | move || { arc.clone() };
| ------- value moved (into closure) here
6 | move || { arc.clone() };
| ^^^ value captured here after move
|
= note: move occurs because `arc` has type `std::sync::Arc<i32>`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud)
我理解为什么我得到这个:clone之前没有被调用arc …
我想在两个闭包之间共享一个引用;在一个封闭中可变。这是一个人为的情况,但我发现在学习 Rust 的背景下它很有趣。
为了使其工作,我不得不利用Rc,Weak和RefCell。有没有更简单的方法来实现这一目标?
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
struct Foo {
i: i32,
}
impl Foo {
fn get(&self) -> i32 {
self.i
}
fn incr(&mut self) {
self.i += 1
}
}
fn retry<O, N>(mut operation: O, mut notify: N) -> i32
where
O: FnMut() -> i32,
N: FnMut() -> (),
{
operation();
notify();
operation()
}
fn something(f: &mut Foo) {
let f_rc = Rc::new(RefCell::new(f));
let f_weak = Rc::downgrade(&f_rc);
let operation = …Run Code Online (Sandbox Code Playgroud)