HeadlinesBriefing favicon HeadlinesBriefing.com

Rust WASM Patterns: Practical Tips for wasm-bindgen

Hacker News •
×

After years of working with Rust-based WebAssembly, I've developed patterns that make wasm-bindgen dramatically less painful. The internet has many opinions about WASM, and wasm-bindgen isn't universally beloved, but with experience comes understanding of how to work around its shortcomings.

A key insight is that you're juggling two memory models simultaneously: JavaScript's garbage-collected, re-entrant, async world versus Rust's explicit ownership and borrowing rules. wasm-bindgen generates glue code that lets Rust structs and functions be called from JS/TS, but this creates complexity around memory management. The tool tries to help but both under- and over-fits - some safe patterns get rejected while certain footguns are happily accepted.

My practical approach includes several conventions: prefix Rust-exported types with Wasm and JS-imported interfaces with Js, avoid deriving Copy on exported types, prefer Rc<RefCell<T>> or Arc<Mutex<T>> over &mut for shared state, and use wasm_refgen for types crossing the boundary in collections. I also recommend implementing From<YourError> for JsValue using js_sys::Error for all Rust-exported error types. These patterns have made Rust+WASM dramatically less painful in practice, though I acknowledge there may be better approaches out there.