Search⌘ K
AI Features

Converting Rust into WebAssembly via Cargo

Explore how to use Cargo for compiling Rust code into WebAssembly modules targeting wasm32-unknown-unknown. Learn to create library projects, configure Cargo.toml, and run WebAssembly in the browser using JavaScript. Understand how async-await helps handle module loading and see practical examples with functions like add and Fibonacci.

We'll cover the following...

We’ve seen how to use rustc to generate WebAssembly modules. It uses Emscripten behind the scenes to create them. But Rust provides another abstraction to generate WebAssembly modules via Cargo.

Cargo makes it easier to create, run, download, compile, test, and run your project. The cargo command provides a wrapper that calls the rustc compiler to start the compilation. To create WebAssembly modules using Rust’s toolchain, we’ll use a different target, wasm32-unknown-unknown.

The wasm32-unknown-unknown target adds zero runtime and toolchain footprint. wasm32 makes the compiler assume that only the wasm32 instruction set is present. The first unknown in unknown-unknown indicates that the code can compile on any machine, and the second indicates that the code can run on any machine.

Getting started with the project

To see it in action, let’s create a new project with Cargo:

Shell
cargo new --lib fib_wasm

A new project called fib_wasm is created. The new option creates a Rust project. The ...