Module 10 • Lesson 55

WebAssembly with Rust

📚 10 min💻 Free🦀 nixus.pro

WebAssembly with Rust

Rust is the premier language for WebAssembly. It compiles to WASM with no garbage collector overhead, runs in browsers and server-side WASM runtimes.

# Setup
rustup target add wasm32-unknown-unknown
cargo install wasm-pack

# Create a wasm-pack project
cargo new --lib my-wasm-lib
# Cargo.toml
[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["console", "Window", "Document"] }
// src/lib.rs
use wasm_bindgen::prelude::*;

// Export to JavaScript
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}! From Rust+WASM", name)
}

#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u64 {
    let mut a = 0u64;
    let mut b = 1u64;
    for _ in 0..n {
        let c = a + b;
        a = b;
        b = c;
    }
    a
}

// Access browser APIs
#[wasm_bindgen]
pub fn log_to_console(msg: &str) {
    web_sys::console::log_1(&msg.into());
}

// JavaScript interop
#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}

#[wasm_bindgen]
pub fn say_hello() {
    alert("Hello from Rust!");
}
# Build
wasm-pack build --target web

# Generated files in pkg/:
# my_wasm_lib.js       - JavaScript glue code
# my_wasm_lib_bg.wasm  - WebAssembly binary
# my_wasm_lib.d.ts     - TypeScript types
<!-- Use in HTML -->
<script type="module">
import init, { greet, fibonacci } from './pkg/my_wasm_lib.js';
await init();
console.log(greet("World"));        // "Hello, World! From Rust+WASM"
console.log(fibonacci(10));          // 55
</script>

🎯 Practice

  1. Create a wasm module that exports an image processing function (grayscale filter on pixel arrays)
  2. Export a struct to JavaScript using #[wasm_bindgen] with methods
  3. Build and test your WASM module in a simple HTML page

🎉 Key Takeaways