WebAssembly (Wasm) is a portable bytecode format that compiled languages such as Rust, C++, and Go can target instead of a particular processor. A Wasm module can run in a browser through a suitable runtime. The format offers a way to move selected JavaScript functionality into Rust without rewriting an entire web application. section 9.1 section 9.2
Consider moving a search function from a JavaScript frontend to Rust. Keep the surrounding page in JavaScript and HTML, compile the Rust function to Wasm, then load and call its exported function from JavaScript. Safety and speed are reasons to consider this change, not guarantees that every function will benefit. section 9.1 section 9.2 section 9.3.2
A small Rust-to-JavaScript integration has three parts:
- Define the data crossing the boundary. A search request can contain a term, page, and limit. section 9.3.2
- Export a Rust function with wasm_bindgen. In the search example, it converts a JavaScript value to a Rust struct, runs the search asynchronously, and converts the result back for JavaScript. section 9.3.2
- Build for the web with wasm-pack build --target web. Its generated package includes JavaScript loading code and declarations for the exported functions and types. section 9.3.2
Listing 9.8 lib.rs: Creating the search function
#[wasm_bindgen] #1
pub async fn paper_search(val: JsValue) -> JsValue{
let term: Search= serde_wasm_bindgen::from_value(val).unwrap(); #2
let resp = search(term.term, term.page, term.limit).await.unwrap(); #3
serde_wasm_bindgen::to_value(&resp).unwrap() #4
}
The exported search function shows the boundary in one place: a JavaScript value enters, Rust performs the search, and a converted result returns. section 9.3.2
Wasm is not limited to browsers: it can also be used with Node.js, and a Wasm module can run inside a Rust application. The JavaScript boundary differs from calling Rust through a C foreign-function interface, where the programmer directly manages allocation, deallocation, and ownership across languages. WebAssembly standards continue to evolve, so distinguish an established workflow from a promise about future capabilities. section 1.7.1 section 9.1 section 10.7




