WebAssembly Basics
10 examples introducing WebAssembly and Rust's wasm32 compilation targets.
Busca en todas las páginas de la documentación
10 examples introducing WebAssembly and Rust's wasm32 compilation targets.
wasm32-unknown-unknown target installedrustup target add wasm32-unknown-unknown// src/lib.rs
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
a + b
}cargo build --target wasm32-unknown-unknown --release#[no_mangle] keeps symbol names stable.wasm binary in target/wasm32-unknown-unknown/release/main function in library-style modules| Target | Host environment |
|---|---|
wasm32-unknown-unknown | Browsers via wasm-bindgen |
wasm32-wasi | WASI runtimes (Wasmtime, Node) |
Choose the target matching your deployment environment.
[profile.release]
opt-level = "s"
lto = true
strip = true
codegen-units = 1opt-level = "s" optimizes for size over speedwasm-opt for further shrinking#![no_std] WASM#![no_std]
#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
loop {}
}
#[no_mangle]
pub extern "C" fn double(x: i32) -> i32 {
x * 2
}String or Vec without an allocator crateuse wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
pub fn info(msg: &str) {
log(msg);
}console.log is the simplest debug pathweb_sys::console in real projectsRelated: wasm-bindgen
use console_error_panic_hook;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn init() {
console_error_panic_hook::set_once();
}#[wasm_bindgen(start)][lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
wasm-bindgen = "0.2"cdylib produces the .wasm artifactrlib allows Rust integration tests on native targetwasm-objdump -x target/wasm32-unknown-unknown/release/mylib.wasm
wasm2wat target/wasm32-unknown-unknown/release/mylib.wasm | headwasm-objdump shows exports, imports, and sizeswasm2wat disassembles to text format for debuggingwasm-tools or WABT<script type="module">
const { default: init, add } = await import("./pkg/mylib.js");
await init();
console.log(add(2, 3));
</script>wasm-pack generates the JS glueinit() async-loads the .wasm fileContent-Type: application/wasmRelated: wasm-pack & Bundling
Rust WASM shines for compute-heavy work: parsers, codecs, crypto, and simulations.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026