Migration, interop & safety guarantees: how to port C++ code to Rust — sum types instead of inheritance, ownership transfer, cxx/bindgen, incremental Ship-of-Theseus migration and verifying what you translated.
Migration, interop & safety guarantees: how to port C++ code to Rust — sum types instead of inheritance, ownership transfer, cxx/bindgen, incremental Ship-of-Theseus migration and verifying what you translated.
WebAssembly (Wasm) is a compact binary format that runs in modern browsers at near-native speed. It is not a replacement for JavaScript but a complement: JS remains the language for DOM manipulation and UI logic, while Wasm handles the compute-intensive tasks — image processing, cryptography, simulations, game engines.
Rust is the language of choice for Wasm because it requires no garbage collector and is memory-safe. C and C++ are also possible but require manual memory management. Rust compiles directly to Wasm and delivers predictable performance without runtime overhead.
// Minimal example: a function that compiles to Wasm
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
// → called from JS: add(2, 3) yields 5
a + b
}
The #[no_mangle] attribute prevents the compiler from altering the name. extern "C" ensures C ABI compatibility so that JavaScript can call the function.
Wasm shines for compute-intensive tasks: image processing, cryptography, simulations, game engines. For simple DOM manipulation, JavaScript is more efficient — the marshalling overhead between JS and Wasm would negate the performance gain. The rule of thumb: Wasm for compute, JS for interaction.
Check: Why is Rust the preferred language for WebAssembly?
Answer: Rust is memory-safe and requires no garbage collector — this ensures predictable performance in Wasm
Rust is memory-safe and requires no GC — this ensures predictable performance and small binaries in Wasm (Module 27, Lesson 1).
⚠ Common mistake: Dropping
#[no_mangle]orextern "C"— without#[no_mangle]the export gets a mangled symbol name, and on the JS sideinstance.exports.addis simplyundefined. You only notice in the browser; the Rust compiler stays silent.
Takeaways:
wasm-pack is the standard tool for compiling Rust to Wasm and producing an npm package. It combines cargo build --target wasm32-unknown-unknown with wasm-bindgen and generates JS glue code.
# Add the Rust Wasm target (one-time)
rustup target add wasm32-unknown-unknown
# Build the project and produce an npm package
wasm-pack build --target web
The result is a pkg/ directory containing the .wasm binary and a .js file that provides the imports for JavaScript.
wasm-bindgen generates the bindings that let Rust and JavaScript communicate type-safely. It converts Rust types to JS types and vice versa — without manual marshalling.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
// → greet("World") returns "Hello, World!"
format!("Hello, {}!", name)
}
The #[wasm_bindgen] attribute makes the function callable from JavaScript. Strings are converted automatically — no manual marshalling required.
Check: What is the main purpose of wasm-pack?
Answer: It compiles Rust to Wasm, generates JS glue via wasm-bindgen, and produces an npm package
wasm-pack combines cargo build --target wasm32-unknown-unknown with wasm-bindgen and produces an npm package with a .wasm binary and JS glue code (Module 27, Lesson 2).
⚠ Common mistake: Running
wasm-pack buildwithout--target— the default isbundler, whose glue code relies onimport.meta.urland a bundler like Vite or webpack. Loading the files frompkg/directly via a<script>tag or following the--target webworkflow then breaks at runtime; always pass the target explicitly (webfor the browser,nodejsfor tests).
Takeaways:
With wasm-bindgen, Rust can call JavaScript functions. This is useful for DOM access, console.log, or Fetch API calls.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen]
pub fn debug_info(msg: &str) {
log(&format!("Rust says: {msg}"));
}
Here we declare the console.log function in Rust and call it. The js_namespace = console attribute tells wasm-bindgen that log maps to console.log in JS.
In JavaScript, we import the Rust function from the generated package:
import init, { greet, debug_info } from "./pkg/my_wasm.js";
async function run() {
await init();
console.log(greet("World")); // "Hello, World!"
debug_info("Wasm is running!"); // "Rust says: Wasm is running!"
}
run();
The init() call loads the .wasm binary. After that, all #[wasm_bindgen] functions are available as normal JS functions.
Check: How do you declare JavaScript's console.log in Rust with wasm-bindgen?
Answer: With an extern 'C' block and #[wasm_bindgen(js_namespace = console)]
You declare console.log in an extern 'C' block with #[wasm_bindgen(js_namespace = console)] and call it like a normal Rust function (Module 27, Lesson 3).
⚠ Common mistake: Calling an exported function before
await init()has resolved — at that point the.wasmbinary is not instantiated yet, and the call dies in the browser with aTypeError. Awaitinit()first, then usegreetand the other exports.
Takeaways:
Wasm binaries can be large. With wasm-opt and linker flags, the size can be drastically reduced — often by 50–70 %.
# Cargo.toml — release profile for small Wasm binaries
[profile.release]
opt-level = "z" # size optimization
lto = true # link-time optimization
codegen-units = 1 # better optimization, longer compile time
strip = true # remove debug symbols
# wasm-opt for further size reduction
wasm-opt pkg/my_wasm_bg.wasm -o pkg/my_wasm_bg.wasm -Oz
Wasm has a linear memory. Rust manages this memory itself (ownership model). When passing large amounts of data between JS and Rust, it is more efficient to pass references rather than copying values.
use wasm_bindgen::Clamped;
#[wasm_bindgen]
pub fn process_pixels(pixels: Clamped<Vec<u8>>) -> Clamped<Vec<u8>> {
let mut data = pixels.0;
// Invert each pixel (simple image filter)
for byte in &mut data {
*byte = 255 - *byte;
}
Clamped(data)
}
Clamped<Vec<u8>> avoids copies — the data stays in Wasm memory and is passed as a reference.
Check: Which Cargo profile setting reduces Wasm binary size the most?
Answer: opt-level = "z" with lto = true, codegen-units = 1, and strip = true
opt-level 'z' (size optimization), lto = true, codegen-units = 1, and strip = true minimize binary size (Module 27, Lesson 4).
⚠ Common mistake: Putting
[profile.release]into a workspace member'sCargo.toml— cargo silently ignores it (just the warning "profiles for the non root package will be ignored") and the binary stays needlessly large. Profile settings belong in the workspace root'sCargo.toml.
Takeaways:
The typical workflow: write Rust code, compile with wasm-pack build, integrate the pkg/ directory into a frontend framework (React, Vue, Svelte), and serve it via a static server.
// lib.rs — a simple image processor (grayscale filter)
use wasm_bindgen::Clamped;
#[wasm_bindgen]
pub fn grayscale(pixels: Clamped<Vec<u8>>) -> Clamped<Vec<u8>> {
let mut data = pixels.0;
for chunk in data.chunks_mut(4) {
let r = chunk[0] as f32;
let g = chunk[1] as f32;
let b = chunk[2] as f32;
let gray = (0.299 * r + 0.587 * g + 0.114 * b) as u8;
// → a red pixel [255, 0, 0, 255] becomes [76, 76, 76, 255]
chunk[0] = gray;
chunk[1] = gray;
chunk[2] = gray;
// chunk[3] = alpha (unchanged)
}
Clamped(data)
}
import init, { grayscale } from "./pkg/image_filter.js";
async function applyFilter(imageData) {
await init();
const filtered = grayscale(new Clamped(imageData));
return filtered;
}
Wasm errors are often hard to debug because stack traces are minimized. With console_error_panic_hook, Rust panics can be rendered as readable JS error messages:
// lib.rs — panic hook for better error messages
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn main() {
console_error_panic_hook::set_once();
// ... app initialization
}
The #[wasm_bindgen(start)] function runs automatically when the Wasm binary loads — ideal for setup code.
Check: Which tool compiles Rust code to Wasm and simultaneously produces an npm package with JS glue code?
Answer: wasm-pack
wasm-pack combines cargo build --target wasm32-unknown-unknown with wasm-bindgen and generates an npm package with a .wasm binary and JS glue code (Module 27, Lesson 2).
⚠ Common mistake: Waiting for
println!output in the browser — onwasm32-unknown-unknownthere is nostdout, those lines simply vanish. Use theconsolebinding from lesson 138 for visible logs; and callconsole_error_panic_hook::set_once()early in the#[wasm_bindgen(start)]function, otherwise a panic leaves nothing but a cryptic "Unreachable executed".
Takeaways:
Course navigation: ← Module 26 · All 27 modules