WebAssembly (often abbreviated as Wasm) is a binary instruction format for a stack-based virtual machine. It's designed to be fast, safe, and portable across different web browsers. Rust, known for its performance and safety features, can compile to WebAssembly, making it an excellent choice for building high-performance web applications.
In this tutorial, we'll explore how to compile Rust code to WebAssembly and run it in a web browser. This will allow you to leverage the power of Rust's systems-level capabilities directly within your web projects.
WebAssembly is not just another programming language; it's a compilation target for languages like C, C++, and Rust. It allows these languages to run at near-native speed on the web without compromising security or portability.
Rust's safety features, such as memory safety and concurrency, make it an ideal candidate for WebAssembly. By compiling Rust code to Wasm, you can take advantage of these features while still running in a browser environment.
Before we dive into the examples, ensure that you have Rust installed on your system. You can install Rust using rustup, the official installer for Rust.
Let's create a simple Rust project that will compile to WebAssembly.
Configure Cargo.toml:
Open Cargo.toml and add the following configuration to enable WebAssembly compilation:
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
Write Rust Code:
Replace the contents of src/lib.rs with the following code:
1use wasm_bindgen::prelude::*;23#[wasm_bindgen]4pub fn greet(name: &str) -> String {5format!("Hello, {}!", name)6}
This code defines a function greet that takes a string slice and returns a formatted greeting string. The #[wasm_bindgen] attribute makes this function accessible from JavaScript.
Build the Project:
Use Cargo to build your project for WebAssembly:
Create an HTML File:
Create an index.html file in the same directory with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rust WebAssembly Example</title>
</head>
<body>
<script type="module">
import init, { greet } from './target/wasm32-unknown-unknown/release/hello_wasm.js';
async function run() {
await init();
console.log(greet('World'));
}
run();
</script>
</body>
</html>
This HTML file imports the generated JavaScript module and calls the greet function, logging the result to the console.
Run the Example:
Open your browser and navigate to http://localhost:8080. You should see "Hello, World!" logged in the console.
wasm-bindgen: This crate provides bindings between Rust and JavaScript, allowing you to call Rust functions from JavaScript and vice versa.cdylib: This crate type is used for creating dynamic libraries that can be linked with other languages, including WebAssembly.#[wasm_bindgen]: This attribute marks a function as exportable to JavaScript.Now that you've learned how to compile Rust code to WebAssembly and run it in a web browser, you can explore more advanced topics such as:
wasm-bindgen to interact with the Document Object Model.By leveraging WebAssembly, you can bring the power of Rust to the web, creating high-performance applications that benefit from Rust's safety and efficiency.