Rust
WebAssembly
Produce WebAssembly with the wasm32 target.
WebAssembly
Rust can compile to WebAssembly, which runs in browsers and on servers: rustup target add wasm32-unknown-unknown. wasm-bindgen exposes Rust functions to JavaScript and handles type conversions; wasm-pack produces an npm package:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn fib(n: u32) -> u64 {
let (mut a, mut b) = (0u64, 1u64);
for _ in 0..n { (a, b) = (b, a + b); }
a
}
// JavaScript:
// import init, { fib } from "./pkg/hesap.js";
// await init(); console.log(fib(10)); // 55
The wasm32-unknown-unknown target has no file system or threads; wasm32-wasip1 (WASI) offers a limited system interface.
Conditional code by target
The same crate can be compiled for both native and wasm; platform-specific parts are separated with cfg:
fn ortam() -> &'static str {
if cfg!(target_arch = "wasm32") { "wasm" } else { "yerel" }
}
#[cfg(target_arch = "wasm32")]
fn zaman() -> f64 { /* js_sys::Date::now() */ 0.0 }
#[cfg(not(target_arch = "wasm32"))]
fn zaman() -> f64 { /* std::time */ 0.0 }
Pure computation functions (like fib above) run on both targets without any change.
Exercise Portable computation
Write the ortam and fib functions above (without wasm_bindgen). Print the results of ortam() and fib(10) separated by a space.
Show example solution
fn ortam() -> &'static str {
if cfg!(target_arch = "wasm32") {
"wasm"
} else {
"yerel"
}
}
pub fn fib(n: u32) -> u64 {
let (mut a, mut b) = (0u64, 1u64);
for _ in 0..n {
(a, b) = (b, a + b);
}
a
}
fn main() {
println!("{} {}", ortam(), fib(10));
}
Test yourself
-
Why is Rust strong for WebAssembly?
- It's easier than JavaScript
- It's the only option
- It isn't strong
- It produces small, fast modules since it needs no garbage collector or big runtime
Show answer
It produces small, fast modules since it needs no garbage collector or big runtime — For size, opt-level = "z", lto = true and wasm-opt are commonly used.
-
Expose to JS
#[____]
pub fn fib(n: u32) -> u64 { .. }
Show answer
#[wasm_bindgen]
pub fn fib(n: u32) -> u64 { .. }
-
Tool and role
- wasm32-unknown-unknown
- Browser target
- wasm-bindgen
- Rust ↔ JS bridge
- wasm-pack
- Produces an npm package
- WASI
- System interface
Next lesson: Panic handler