如何在rust(和stdweb)中使用Rc Refcell

时间:2019-12-31 00:59:38

标签: rust

我的这段代码有点问题:

我有两个闭包,并且我想在两个变量中都使用变量 counter

fn main() {
    stdweb::initialize();


    let counter_div = document().query_selector(DIV_SELECTOR_NAME).unwrap().unwrap();
    // create Rc RefCell struct here 
    let mut counter = Rc::new(RefCell::new(ClickCounter::new()));

    counter_div.clone().add_event_listener(move |_: MouseDownEvent| {
        // ERROR move How make this work?
        counter.clone().borrow_mut().increment();
    });


    let upgrade_div = document().query_selector(UPGRADE_DIV_SELECTOR_NAME).unwrap().unwrap();
    upgrade_div.clone().add_event_listener( move |_: MouseDownEvent|{

       // ERROR move! 
       counter.clone().borrow_mut().upgrade_click(upgrade);
    });


    stdweb::event_loop();
}

1 个答案:

答案 0 :(得分:1)

Rcmove闭包一起使用时,您需要先克隆 ,然后将变量移到闭包中。使用已编写的代码,您首先要在变量 之后将其克隆到闭包中,这意味着在第二个闭包尝试执行此操作时,该变量不可用。

一个例子:

let counter = Rc::new(RefCell::new(ClickCounter::new()));

{
    // Clone into a new variable outside of the closure.
    let cloned_counter = counter.clone();

    counter_div.add_event_listener(move |_: MouseDownEvent| {
        // Note: We're no longer cloning here.
        cloned_counter.borrow_mut().increment();
    });
}

// ...

{
    // Clone the counter variable on line 1 again.
    let cloned_counter = counter.clone();
    upgrade_div.add_event_listener(move |_: MouseDownEvent| {
        cloned_counter.borrow_mut().upgrade_click(upgrade);
    });
}