...

/

Sharing Classes from Rust with JavaScript

Sharing Classes from Rust with JavaScript

Learn how to import Rust class/struct in JavaScript.

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:

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

Press + to interact
[package]
name = "class_world"
version = "0.1.0"
authors = ["Educative"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.68"
  1. Open the src/lib.rs file and replace the content with the following:

Press + to interact
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct Point {
x: i32,
y: i32,
}
#[wasm_bindgen]
impl Point {
pub fn new(x: i32, y: i32) -> Point {
Point { x: x, y: y}
}
pub fn get_x(&self) -> i32 {
self.x
}
pub fn get_y(&self) -> i32 {
self.y
}
pub fn set_x(&mut self, x: i32) {
self.x = x;
}
pub fn set_y(&mut self, y:i32) {
self.y = y;
}
pub fn add(&mut self, p: Point) {
self.x = self.x + p.x;
self.y = self.y + p.y;
}
}
...