问题
I have 2 structs where I can access the Parent
struct from JavaScript and create it with new
:
struct Child {
foo: String,
}
impl Child {
pub fn do_something(&self) {
/* some stuff */
}
}
#[wasm_bindgen]
pub struct Parent {
child: Child,
}
#[wasm_bindgen]
impl Parent {
pub fn new() -> Self {
Self {
child: Child { foo: String::new() },
}
}
pub fn child(&self) -> &Child {
&self.child
}
}
I cannot compile the code because of an error at the child()
method:
cannot return a borrowed ref with #[wasm_bindgen]
Is there any way to get a pointer to child
and access it from JavaScript? Why can Rust not return a borrowed reference to WebAssembly? Is this because JavaScript could modify its value and Rust couldn't guarantee immutability of the data?
回答1:
In WASM, Javascript is like kernel code. It runs at the highest level of privilege and has free access to the entire memory space. Some have mentioned that if Rust were to return an reference into JS, it could end up being a dangling pointer. This would be bad, but it's not Rust's problem. Like kernel code, it's Javascript's responsibility to be safe in that context. The real problem is that there would be no way to ensure the JS didn't abuse an immutable reference in order to mutate data and cause memory corruption.
来源:https://stackoverflow.com/questions/61385031/how-to-return-a-reference-to-a-nested-rust-struct-in-webassembly