CodeBlanks Logo Icon CodeBlanks

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.

Practice Portable computation

Write the ortam and fib functions above (without wasm_bindgen). Print the results of ortam() and fib(10) separated by a space.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
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));
}

Expected output

yerel 55

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer

Explanation: For size, opt-level = "z", lto = true and wasm-opt are commonly used.

2 Expose to JS

Question
#[____]
pub fn fib(n: u32) -> u64 { .. }
Answer
#[wasm_bindgen]
pub fn fib(n: u32) -> u64 { .. }

Explanation: #[wasm_bindgen] makes the function callable from JavaScript.

3 Tool and role

Term Meaning
wasm32-unknown-unknown Browser target
wasm-bindgen Rust ↔ JS bridge
wasm-pack Produces an npm package
WASI System interface

All lessons in Expert