Should I worry about using forget
method with Closure
?
#3007
-
I have an html form that checks password validation on submit by using wasm-bindgen's I experimented if the onsubmit function works without Is there a documentation of how exactly I can be careful with this |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I asked the same question on stackoverflow here just in case someone is curious. |
Beta Was this translation helpful? Give feedback.
-
Using Here's an example of a case where forget shouldn't be used: use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
fn requestAnimationFrame(callback: &Closure<dyn FnMut()>);
}
#[wasm_bindgen(start)]
pub fn start() {
// Start the rAF loop.
frame_handler();
}
fn frame_handler() {
let closure = Closure::new(frame_handler);
requestAnimationFrame(&closure);
// Don't do this - this will leak memory every frame.
closure.forget();
} Since this example uses the same closure every time, we can instead create the closure once and give it a reference to itself to call use std::mem;
use std::rc::{Rc, Weak};
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
fn requestAnimationFrame(callback: &Closure<dyn FnMut()>);
}
#[wasm_bindgen(start)]
pub fn start() {
// Give the closure a reference to itself using `Rc::new_cyclic`, which
// initializes the `Rc` with a closure taking a `Weak` reference as an
// argument.
let closure = Rc::new_cyclic(|this: &Weak<_>| {
// &Weak -> Weak
let this = this.clone();
Closure::new(move || {
// Upgrade the `Weak` to an `Rc`.
// We can't do this outside the closure because the `Weak` only
// becomes `upgrade`able after `Rc::new_cyclic` returns.
let this = this.upgrade().unwrap();
requestAnimationFrame(&this);
})
});
// Leak the `Rc` so that the closure will live forever.
// Since this only happens once, it's fine.
mem::forget(closure);
} |
Beta Was this translation helpful? Give feedback.
Using
forget
is fine as long as you only call it once or a fixed number of times. So in your case, it's fine as long as you only setonsubmit
once upon startup.Here's an example of a case where forget shouldn't be used:
Since this example uses the same closure every time, we can instead cre…