0Pricing
Learn Rust Coding · Lesson

Rust to WebAssembly (WASM)

Compile Rust code to WebAssembly, enabling high-performance modules to run in web browsers and other WASM runtimes.

Rust to WebAssembly (WASM) is a free Learn Rust Coding lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is WebAssembly (WASM)?

WebAssembly, or WASM, is a binary instruction format for a stack-based virtual machine. It's designed to be a portable compilation target for high-level languages like Rust, C/C++, and Go.

Think of it as a low-level assembly-like language that runs efficiently in web browsers and other environments. It allows you to run performance-critical code at near-native speeds.

Rust's Advantages for WASM

Rust is an excellent choice for WebAssembly development due to its unique strengths:

  • Performance: Rust is known for its speed, close to C/C++.
  • Memory Safety: Rust's ownership system prevents common bugs without a garbage collector.
  • Small Binaries: Rust's minimal runtime leads to compact WASM modules.
  • Tooling: Excellent support with tools like wasm-pack and wasm-bindgen.

Setting Up Your WASM Tools

To compile Rust to WebAssembly, you'll primarily use wasm-pack. It's a command-line tool that handles the entire build process.

You'll also use wasm-bindgen, a Rust crate and CLI tool that facilitates high-level interactions between WASM modules and JavaScript.

To install wasm-pack, open your terminal and run:

cargo install wasm-pack

Your First WASM Project

Let's create a new Rust project tailored for WebAssembly. We'll use cargo generate with a specific template:

cargo install cargo-generate
cargo generate --git https://github.com/rustwasm/wasm-pack-template

Follow the prompts to name your project. This sets up a lib.rs file ready for WASM code and a www directory for a simple web interface.

Rust Function for JavaScript

To make a Rust function callable from JavaScript, we use the #[wasm_bindgen] attribute from the wasm-bindgen crate.

This attribute instructs wasm-bindgen to generate the necessary glue code for JavaScript to interact with your Rust function.

use wasm_bindgen::prelude::*;

// This attribute makes the `greet` function available to JavaScript.
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

// In a WASM library, `main` is not used. This code is compiled to a .wasm module.

Integrate WASM with JavaScript

After writing your Rust code, you build it into a WASM module using wasm-pack build. This command creates a pkg directory with your .wasm file and JS glue code.

Then, in your JavaScript, you can easily import and use the exported Rust functions:

// www/index.js (simplified)
import { greet } from "../pkg/your_project_name"; // Adjust path

// Call the Rust function
const message = greet("CoddyKit Learner");
console.log(message); // Outputs: "Hello, CoddyKit Learner!"

// You'd typically connect this to HTML elements.

Rust Calling JavaScript

Rust can also call JavaScript functions. You declare them in an extern "C" block and use #[wasm_bindgen] to map them to JS global objects or functions.

The js_namespace argument lets you specify where to find the function in the JavaScript environment, like the console object.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    // Import JS console.log as a Rust function named 'log'
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);

    // You can import other JS functions too
    #[wasm_bindgen(js_name = alert)]
    fn js_alert(s: &str);
}

#[wasm_bindgen]
pub fn log_and_alert_from_rust(message: &str) {
    log(&format!("Rust log: {}", message));
    js_alert(&format!("Rust alert: {}", message));
}

Passing Strings Between Rust & JS

wasm-bindgen intelligently handles common data types like numbers and booleans. For strings, it uses UTF-8 encoding.

When you pass a &str or String from Rust, wasm-bindgen converts it to a JavaScript String, and vice-versa. This abstraction makes interop smooth.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn uppercase_and_reverse(s: String) -> String {
    s.to_uppercase().chars().rev().collect()
}

// This function takes a String, processes it, and returns a new String.
// wasm-bindgen handles the conversion to/from JS strings.

WASM Outside the Browser

While often associated with web browsers, WebAssembly isn't limited to them! WASM runtimes exist for many environments, opening up new possibilities:

  • Serverless Functions: Deploy fast, isolated functions.
  • Blockchain: Smart contracts execution.
  • Plugins/Extensions: Securely extend applications.
  • Desktop Apps: Embed high-performance modules.

This expands Rust's reach far beyond traditional systems programming.

WebAssembly Key Concepts

Let's check your understanding of Rust and WebAssembly.

Recap: Rust to WASM

You've learned how to bring Rust's performance and safety to WebAssembly!

  • WASM provides a fast, portable runtime for compiled code.
  • Rust excels at WASM thanks to its performance, small binaries, and safety.
  • Tools like wasm-pack and wasm-bindgen simplify the development process.
  • You can easily export Rust functions to JavaScript and import JavaScript functions into Rust.
  • WASM's applications extend far beyond just web browsers.

Keep exploring to build powerful, high-performance web and non-web applications with Rust!

Frequently asked questions

Is the “Rust to WebAssembly (WASM)” lesson free?

Yes — the full text of “Rust to WebAssembly (WASM)” is free to read here on the web, and the Learn Rust Coding course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.

What will I learn in “Rust to WebAssembly (WASM)”?

Compile Rust code to WebAssembly, enabling high-performance modules to run in web browsers and other WASM runtimes. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn Rust Coding?

No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Rust to WebAssembly (WASM)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn Rust Coding lesson?

Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Foreign Function Interface (FFI)
  2. Rust to WebAssembly (WASM)
  3. Benchmarking and Performance Tuning
← Back to Learn Rust Coding