WebAssembly
WebAssembly is a binary format for executing code on the web that was developed by a consortium of browser vendors. It allows developers to write high-performance code in languages like C and Rust and run that code in the browser. Here's an example of using WebAssembly to calculate the factorial of a number:
#[no_mangle]
pub extern fn factorial(n: u32) -> u32 {
match n {
0 => 1,
_ => n * factorial(n - 1)
}
}
In this code, we're using Rust to define a factorial function that calculates the factorial of a number. We're using the #[no_mangle] attribute to tell the Rust compiler not to change the name of the function when it's compiled to WebAssembly. Once compiled, we can call this function from JavaScript like this:
const wasmModule = new WebAssembly.Module(wasmCode);
const wasmInstance = new WebAssembly.Instance(wasmModule);
console.log(wasmInstance.exports.factorial(5)); // 120
In this code, we're using the WebAssembly.Module and WebAssembly.Instance classes to load and instantiate the WebAssembly code. We're calling the factorial function on the exports object of the wasmInstance to calculate the factorial of 5.
No comments:
Post a Comment