WebAssembly
WebAssembly (WASM) is a binary instruction format for a stack-based virtual machine that runs in modern browsers and other environments.
Key points:
- It’s platform-independent: Runs on browsers, servers, and embedded systems.
- Near-native performance: Faster than JavaScript for computation-heavy tasks.
- Safe and sandboxed: Executes in a secure environment.
- Interoperable: Can be called from JavaScript and can call JavaScript functions.
WASM use cases in web development:
- Game engines in the browser
- Image/video/audio processing
- Mathematical simulations
- High-performance web apps
- Replacing slow JavaScript in performance-critical parts
Why Rust + WASM?
Rust is a perfect match for WASM because:
- High performance: Rust code compiles to highly optimized WASM bytecode.
- Memory safety: No buffer overflows or unsafe memory access.
- Tooling support: wasm-bindgen and wasm-pack make Rust ↔ JS interop seamless.
- Ecosystem: Rust crates like yew and seed help build full web frontends.
Rust Tools for WASM Development
| Tool | Purpose |
|---|---|
wasm-pack | Compiles Rust → WASM, generates JS bindings |
wasm-bindgen | Connects Rust code to JS easily |
cargo-web | Alternative toolchain for Rust → WASM (older) |
yew, seed | Frontend frameworks in Rust (like React) |
Simple Rust + WASM Example
We’ll create a Rust function compiled to WASM, called from JavaScript in the browser.
Step 1: Install Tools
cargo install wasm-pack
Step 2: Create a New Rust Library
cargo new --lib wasm_demo
cd wasm_demo
Step 3: Update Cargo.toml
[package]
name = "wasm_demo"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
crate-type = ["cdylib"]→ generates WASM-compatible library.wasm-bindgen→ helps JS interop.
Step 4: Write Rust Code (src/lib.rs)
use wasm_bindgen::prelude::*;
// Export a function to JS
#[wasm_bindgen]
pub fn add_numbers(a: i32, b: i32) -> i32 {
a + b
}
// Export a greeting function
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}! Welcome to Rust + WASM!", name)
}
#[wasm_bindgen]→ marks function to be available in JavaScript.- Rust types like
i32and&strare automatically converted to JS types.
Step 5: Compile to WASM
wasm-pack build --target web
--target web → outputs WASM + JS bindings for web browsers.
Result folder: pkg/ contains:
wasm_demo_bg.wasm→ compiled WASMwasm_demo.js→ JS glue code
Step 6: Use WASM in HTML + JS
Create index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rust + WASM Demo</title>
</head>
<body>
<h1>Rust + WASM Demo</h1>
<p id="result"></p>
<script type="module">
import init, { add_numbers, greet } from "./pkg/wasm_demo.js";
async function run() {
await init(); // Initialize WASM
const sum = add_numbers(5, 7);
const message = greet("Alice");
document.getElementById("result").innerHTML =
``;
}
run();
</script>
</body>
</html>
import init, {...}→ imports the WASM module and functions.await init()→ initializes WASM memory and environment.- Rust functions
add_numbersandgreetare callable directly from JS. - Output is rendered in the browser.
Step 7: Run Locally
You can serve the HTML using a simple HTTP server:
python -m http.server 8000
Open http://localhost:8000 to see:
Sum: 12
Message: Hello, Alice! Welcome to Rust + WASM!
Rust WASM in Web & Application Development
- Frontend performance: Rust + WASM can replace heavy JS computations.
- Shared code: You can share logic between server (Rust backend) and client (WASM frontend).
- Web frameworks: Yew or Seed allows building full SPA (Single Page Applications) using Rust + WASM.
- Server-side WASM: WASM can run server-side too (e.g., in wasmtime or Cloudflare Workers).
Key Benefits of Rust + WASM
| Benefit | Description |
|---|---|
| Performance | Near-native speed in browser |
| Safety | Memory-safe and thread-safe |
| Interoperability | Can call JS functions and be called by JS |
| Reusability | Logic can run in browser & server |
| Modern Tooling | wasm-pack, wasm-bindgen, bundlers, frameworks |
Advanced Next Steps
- Build a full SPA using Yew.
- Use async Rust in WASM for web requests.
- Integrate Rust + WASM + WebGL for games or graphics.
- Package WASM as npm modules for JS ecosystems.