Search⌘ K
AI Features

Converting Rust into WebAssembly via wasm-bindgen

Explore converting Rust code into WebAssembly using wasm-bindgen. Learn to create binding JavaScript files to manage data transfer between JavaScript and WebAssembly and understand how wasm-bindgen facilitates this process. Gain skills to generate, load, and run WebAssembly modules from Rust efficiently.

So far, we’ve seen simple examples. But how can we pass functions and classes from JavaScript into WebAssembly and vice versa? In order to do more advanced bindings, Rust provides us with wasm-bindgen. Let’s start with a “Hello World” example with wasm-bindgen.

Getting started with the project

  1. Create a new project with Cargo:

Shell
cargo new --lib hello_world

This will create a new Rust project with all the necessary files.

  1. Open the Cargo.toml file to add crate-type and add the wasm-bindgen dependency:

Rust 1.40.0
[package]
name = "hello_world"
version = "0.1.0"
authors = ["Educative"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.38"

We define the wasm-bindgen dependency under the [dependencies] (line 9).

  1. Open the src/lib.rs file and replace the contents with the following:

C++
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn hello_world() -> String {
"Hello World".to_string()
}

We import the wasm_bindgen library using use wasm_bingen::prelude::* (line 1) and then annotate the function with #[wasm_bindgen] (line 2). The hello function returns String (line 4).

To generate the WebAssembly module, we’ll first run the following command:

Shell
cargo build --target=wasm32-unknown-unknown

This will generate the WebAssembly module. But this module cannot run by itself. WebAssembly only supports passing numbers between the native code and JavaScript. But we’re returning a String ...