DEV Community

Sammy Shear
Sammy Shear

Posted on

Thirty Days of Rust: Day Five

Today I wanted to take it easy a little bit and try some WebAssembly with Rust. Over the years I've gotten very used to JavaScript, but now that I'm doing this challenge, I wanted to dip my feet into WebAssembly, so that's exactly what I did. I found a book that basically told me everything I needed to know, and then I got started.

Rust Setup

So instead of a new Rust app, I needed to make a Rust lib, which I could do with:

$ cargo new day5 --lib
Enter fullscreen mode Exit fullscreen mode

Then I added two things to my Cargo.toml so it looked like this:

[package]
name = "day5"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "rlib"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
wasm-bindgen = "0.2.78"
Enter fullscreen mode Exit fullscreen mode

Then I went ahead and installed wasm-pack with cargo:

$ cargo install wasm-pack
Enter fullscreen mode Exit fullscreen mode

Rust Code

The only thing I wanted this app to do was add two numbers together. It's probably too simple for this challenge to really mean anything, but I didn't want to spend too much time on this because tomorrow I want to rebuild my hangman game in the browser and I figured today could be a little bit shorter.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn add(n1: i32, n2: i32) -> i32 {
    return n1 + n2;
}
Enter fullscreen mode Exit fullscreen mode

So that was simple, as I expected and now I just had to pack it together with:

$ wasm-pack build
Enter fullscreen mode Exit fullscreen mode

JS Setup

$ pnpm init wasm-app www
$ cd www
$ pnpm i
Enter fullscreen mode Exit fullscreen mode

That's all, now I just imported the wasm file and console logged the result of the add function:

import * as wasm from "../pkg";

console.log(wasm.add(21, 19));
Enter fullscreen mode Exit fullscreen mode

Now I could just run pnpm serve and open up localhost:8080 to get to my app. When I opened up the console, it showed the logged value of 40.
That's about it from me today, but I look forward to tomorrow and sorry if this one was a little less exciting.

Top comments (0)