如何在Rust Wasm中改变数据?获取借用检查器错误

w8f9ii69  于 2023-05-22  发布在  其他
关注(0)|答案(1)|浏览(143)

我尝试了从Rc到Arc和Mutex async_std的所有方法,尽管它显然包含了wasm支持,但它们甚至无法编译。我已经与这个错误斗争了几天了,我无法理解这个问题,当non-wasm似乎工作正常,Promise没有什么不同。我也在非自我上试过,使用无结构代码,同样的问题。

use std::cell::RefCell;
use std::rc::Rc;

use wasm_bindgen_futures::spawn_local;

use wasm_bindgen::prelude::*;

pub struct MyClass {
    value: u32,
}

impl MyClass {
    pub fn new() -> Self {
        return Self { value: 0 };
    }

    pub async fn boot_async(this: Rc<RefCell<&mut Self>>) {
        this.borrow_mut().value += 1;
    }

    pub fn boot(&mut self) {
        let this = Rc::new(RefCell::new(self));
        let async_function = MyClass::boot_async(this.clone());
        spawn_local(async_function);
    }
}

#[wasm_bindgen(start)]
fn start() {
    let mut test = MyClass::new();
    test.boot();
}

我得到:

error[E0521]: borrowed data escapes outside of method
  --> src/main.rs:29:30
   |
27 |     pub fn boot(&mut self) {
   |                 ---------
   |                 |
   |                 `self` is a reference that is only valid in the method body
   |                 let's call the lifetime of this reference `'1`
28 |         let this = Rc::new(RefCell::new(self));
29 |         let async_function = MyClass::boot_async(this.clone());
   |                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |                              |
   |                              `self` escapes the method body here
   |                              argument requires that `'1` must outlive `'static`
   |
   = note: requirement occurs because of the type `RefCell<&mut MyClass>`, which makes the generic argument `&mut MyClass` invariant
   = note: the struct `RefCell<T>` is invariant over the parameter `T`
   = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance
kulphzqa

kulphzqa1#

你就差一点。问题是Rc没有帮助,因为您仍然有一个引用。你必须摆脱它:

impl MyClass {
    pub fn new() -> Self {
        return Self { value: 0 };
    }

    pub async fn boot_async(this: Rc<RefCell<Self>>) {
        this.borrow_mut().value += 1;
    }

    pub fn boot(self) {
        let this = Rc::new(RefCell::new(self));
        let async_function = MyClass::boot_async(this.clone());
        spawn_local(async_function);
    }
}

相关问题