4Manuals

  • PDF Cloud HOME

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

    货物建造未在wasm项目上生成pkg目录 如何为Rustdoc上下文解释“在此范围内找不到派生宏`Cacheable`” 受约束的特征`tokio :: net :: tcp :: stream :: TcpStream:tokio_io :: async_read :: AsyncRead`不满意 如何在Rust中将`Fn`特征与`impl trait`返回类型一起使用? 如何在选项数组中正确分配值? 在Hyper Body结构上添加换行符 更改其他线程中的值并断言后一个(在“主”线程中) 了解rust Option as_mut方法 使用PhantomData <T>时,不满足特征绑定`T:std :: default :: Default` 有没有一种方法可以编写泛型函数,从而通过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)

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

一个例子:

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



Similar searches
    卷毛显示难以理解的字符而不是答案 根据熊猫DFS中的部分字符串匹配进行合并 为什么滚动指示器更改了它在表视图上的位置? 显示单个URL以在Ionic 4 PWA中导航 并行功能执行而无需在场景之间重置驱动程序?