Hi Folks, Welcome to another Blog. Today, we'll learn about how to call a rust program using Wasm.
1. We need rust and wasm-pack in our system, lets install them:
a. For Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
b. For wasm-pack
cargo install wasm-pack
Cargo is a Rust package manager. Cargo downloads your Rust package's dependencies, compiles your packages, makes distributable packages, and uploads them to crates.io, the Rust community's package registry.
2. Create a Library, here I've named it
cargo new --lib ary-kaush
3. Move to the library,
and open vs code by using
code . command.
we can see that there is a folder named src and a file named cargo.toml.
4. In order to create a wasm module, we need to specify the type of package.
For adding such specification we need to modify
Cargo.toml file. By adding:
a. crate type:
[lib] crate-type = ["cdylib"]
wasm-bindgen = "0.2.78"
5. Change default code in src/lib.rs to the code that we wan't to run
here we are making a function to add two numbers.
6. Now building the package
after build, a lot of files has been created to support the package.
7. In order to run this program, run:
wasm-pack build --target nodjs
A pkg folder will be created which includes .wasm,.ts, js and .json files.
8. To run our program we need to create a index.js file and where we will make a math library.
const math = require('./ary_kaush.js') console.log(math.add2numbers(10,20));
9. move in pkg by
cd pkg/ and run
and Finally we have the required output.
This was a basic program in rust, whereas we can create multiple projects e.g. a calculator, fibonacci series, to find whether the number is prime or not etc. .
Please check out blog by @moksh_pathak , where he created a calculator using Rust and ran it in Enarx.
Stay tuned for more stuff!
Do comment your ideas and suggestions related to the blog and please share if you found it useful.
Write your queries in comment section, we'll help you to resolve your errors.
Top comments (0)