Building a WebAssembly Module with Rust
Introduction
WebAssembly (Wasm) is a binary instruction format designed for stack-based virtual machines. It enables high-performance applications on the web. Rust, a modern programming language, has excellent support for creating WebAssembly modules. In this tutorial, we will walk through the process of building a simple WebAssembly module using Rust.
Prerequisites
Before we begin, ensure you have the following installed on your system:
- Rust: You can install it from rust-lang.org.
- WasmPack: This is a tool that helps build and package Rust-generated WebAssembly. Install it with the following command:
Creating a New Rust Project
Start by creating a new Rust project for your WebAssembly module. Open your terminal and run:
This command creates a new library project named wasm_example
. Change into the project directory:
Writing the Rust Code
Open the src/lib.rs
file. We will write a simple function that adds two numbers and returns the result. Replace the contents of lib.rs
with the following code:
#[no_mangle] pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b }
Here, #[no_mangle]
prevents Rust from renaming the function during compilation, allowing it to be called from JavaScript.
Building the WebAssembly Module
To compile your Rust code into WebAssembly, run the following command:
This command will create a pkg
directory containing the compiled WebAssembly binary and the necessary JavaScript bindings.
Integrating with JavaScript
Now, let's create an HTML file to utilize our WebAssembly module. Create a new file named index.html
in the root of your project. Add the following code:
Wasm Example Wasm Example