This content originally appeared on DEV Community and was authored by Sammy Shear
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
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"
Then I went ahead and installed wasm-pack
with cargo:
$ cargo install wasm-pack
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;
}
So that was simple, as I expected and now I just had to pack it together with:
$ wasm-pack build
JS Setup
$ pnpm init wasm-app www
$ cd www
$ pnpm i
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));
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.
This content originally appeared on DEV Community and was authored by Sammy Shear
Sammy Shear | Sciencx (2022-01-16T19:09:15+00:00) Thirty Days of Rust: Day Five. Retrieved from https://www.scien.cx/2022/01/16/thirty-days-of-rust-day-five/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.