Rust and WebAssembly
Rust is one of the best-supported languages for WebAssembly development, thanks to its lack of a garbage collector, small runtime, and predictable performance characteristics. The Rust and WebAssembly working group maintains tooling and documentation to make this integration seamless.
Why Rust for WebAssembly?
- No garbage collector: Produces small, efficient Wasm binaries without runtime overhead
- Memory safety: Rustβs ownership model prevents bugs that are hard to debug in Wasm
- Small binary size: Rust can produce minimal Wasm modules with
#[no_std]and careful dependency management - Mature toolchain: First-class
wasm32-unknown-unknowncompilation target viarustup - Strong ecosystem: Libraries like
wasm-bindgen,web-sys, andjs-sysprovide ergonomic JavaScript interop
Key Tools
- wasm-pack - One-stop shop for building, testing, and publishing Rust-generated Wasm packages
- wasm-bindgen - Facilitates high-level interactions between Rust and JavaScript
- web-sys - Bindings to Web APIs (DOM, Canvas, Fetch, etc.)
- js-sys - Bindings to JavaScript built-in objects and functions
- wee_alloc - A tiny allocator for size-conscious Wasm modules
Typical Workflow
- Create a new Rust library with
cargo new --lib - Set
crate-type = ["cdylib"]inCargo.toml - Add
wasm-bindgenas a dependency - Write Rust functions annotated with
#[wasm_bindgen] - Build with
wasm-pack build - Import the generated package in JavaScript/TypeScript
Example
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}Use Cases
- Performance-critical web features: Image processing, video encoding, physics simulations
- Porting existing Rust libraries to the web
- Shared logic between server (native Rust) and client (Wasm)
- Edge computing with Wasm runtimes (Cloudflare Workers, Fastly Compute)
Related Concepts
- WebAssembly - The compilation target
- Rust - The source language
- wasm-pack - Build tooling
- JavaScript - Host environment for Wasm on the web