Search⌘ K
AI Features

Sharing Classes from Rust with JavaScript

Explore how to share classes between Rust and JavaScript using wasm-bindgen. Learn to create Rust structs with public methods, generate WebAssembly modules, and handle memory safely. This lesson guides you through setting up projects, writing code, and running examples that demonstrate smooth cross-language interaction.

We'll cover the following...

wasm-bindgen enables sharing classes from JavaScript with Rust and vice versa using simple annotations. It handles all the boilerplate stuff, such as translating a value from JavaScript to WebAssembly or WebAssembly to JavaScript, as well as complex memory manipulations and error-prone pointer arithmetic. Thus, wasm-bindgen makes everything easier.

Getting started with the project

Let’s see how easy it is to share classes between JavaScript and WebAssembly (from Rust):

  1. Create a new project:

C++
cargo new --lib class_world
  1. Define the wasm-bindgen dependency for the project. Open the cargo.toml file and add the following content: ...

C++
[package]
name = "class_world"
version = "0.1.0"
authors = ["Educative"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.68"
...