DEV Community

Phil IPS
Phil IPS

Posted on

Webassembly Tutorial

Intro to WebAssembly with Rust

Introduction

WebAssembly (Wasm) is a binary instruction format for a stack-based virtual machine. It enables near-native performance in web browsers and is supported by all major browsers. Rust is a systems programming language that compiles to WebAssembly, making it an excellent choice for high-performance web applications.

Why WebAssembly?

  • Performance: Execute computationally intensive tasks at near-native speed
  • Portability: Runs in any browser that supports Wasm
  • Language Flexibility: Bring Rust, C++, and other languages to the web
  • Security: Sandboxed execution environment

Setting Up Rust for WebAssembly

First, install Rust with Wasm support:

rustup target add wasm32-unknown-unknown
Enter fullscreen mode Exit fullscreen mode

Install the wasm-pack tool, which simplifies building and packaging Wasm modules:

cargo install wasm-pack
Enter fullscreen mode Exit fullscreen mode

Creating a Simple Example

Let's create a basic Rust module that adds two numbers:

// src/lib.rs
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
    a + b
}
Enter fullscreen mode Exit fullscreen mode

This function takes two i32 parameters and returns their sum. The #[no_mangle] attribute ensures the function name isn't mangled during compilation.

Building the Module

Build the project with:

wasm-pack build --target web
Enter fullscreen mode Exit fullscreen mode

This creates a pkg directory containing the compiled Wasm file and JavaScript bindings.

Using the Module in JavaScript

Create an HTML file to test the module:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Wasm Demo</title>
</head>
<body>
    <script type="module">
        import init, { add } from './pkg/your_module.js';

        async function run() {
            await init();
            const result = add(5, 7);
            console.log('5 + 7 =', result);
        }

        run();
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. The Rust code is compiled to Wasm bytecode
  2. wasm-pack generates JavaScript bindings
  3. The browser loads the Wasm module and executes the add function
  4. Results are returned to JavaScript

Conclusion

WebAssembly with Rust provides a powerful way to bring high-performance code to the web. With just a few steps, you can compile Rust code to run in browsers, enabling complex applications that were previously impossible in JavaScript alone. Try experimenting with more complex examples like image processing or game physics!

Top comments (0)