WebAssembly with Rust
Build high-performance WebAssembly modules in Rust using wasm-bindgen and more
Get Started with Rust+WASMGetting Started
1. Install Tooling
cargo install wasm-pack
wasm-pack init
2. Example: Hello World
// src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
3. Build & Publish
wasm-pack build
wasm-pack publish
Advanced Rust + WASM
Memory Management
Rust's ownership model with wasm-bindgen provides safe FFI boundaries between Rust and JavaScript:
#[wasm_bindgen]
pub struct Point {
x: f64,
y: f64,
}
#[wasm_bindgen]
impl Point {
#[wasm_bindgen(constructor)]
pub fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
}
Performance Tips
- Use
#[wasm_bindgen(start)]
for initialization - Enable LTO optimization with
--release
- Use
no_std
for smaller wasm binaries - Minify WASM with
wasm-opt
Interactive Example
Add Two Numbers
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: u32, b: u32) -> u32 {
a + b
}