Rust Daily Learning - Day 22
- Overview
- Installing wasm-pack
- Creating a Rust Library
- Exporting Functions to WebAssembly
- Building the WebAssembly Module
- Using WebAssembly in JavaScript
Overview
Today’s Rust daily learning series will introduce you to Rust and WebAssembly (Wasm). By compiling Rust code to WebAssembly, you can create high-performance web applications that leverage Rust’s safety and speed. We’ll cover how to use tools like wasm-bindgen
and wasm-pack
to compile Rust code to Wasm and integrate it into web projects.
Installing wasm-pack
First, install wasm-pack
using the following command:
cargo install wasm-pack
wasm-pack
helps you build, test, and publish Rust-generated WebAssembly packages.
Creating a Rust Library
Next, create a new Rust library:
cargo new --lib wasm_example
Change into the wasm_example
directory:
cd wasm_example
Update the Cargo.toml
file with the following dependencies:
[dependencies]
wasm-bindgen = "0.2"
[lib]
crate-type = ["cdylib"]
Exporting Functions to WebAssembly
Edit the src/lib.rs
file to create a simple Rust function and use the #[wasm_bindgen]
attribute to make it available to WebAssembly:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
Building the WebAssembly Module
Run wasm-pack
to build the WebAssembly module:
wasm-pack build --target web
This command generates a pkg
directory containing the WebAssembly binary and a JavaScript wrapper.
Using WebAssembly in JavaScript
Create an index.html
file in your project directory and include the following content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Rust and WebAssembly Example</title>
</head>
<body>
<script type="module">
import init, { greet } from "./pkg/wasm_example.js";
async function run() {
await init();
console.log(greet("Rust and WebAssembly"));
}
run();
</script>
</body>
</html>
Serve the index.html
file using a local web server (e.g., python3 -m http.server
or npx serve
). Open the web page in a browser and check the console for the greeting message generated by the Rust function compiled to WebAssembly.
That’s it for today’s lesson on Rust and WebAssembly. Keep experimenting and exploring how to integrate Rust code into your web projects using WebAssembly for improved performance and safety. Happy coding!