Skip to main content

WebAssembly with Rust


Environment setup

To get started, you must install the following:


Go to and follow the instructions using rustup.


You will find wasmtime at

Install the WebAssembly Rust toolchain:

 rustup target install wasm32-wasi

To get started, lets use a demo that caculates a Fibonacci sequence (i.e. every number after the first two is the sum of the two preceding ones).

Rust Code

First create a new project using the command below:

cargo new demo

You can use any IDE of your choice and open up this project folder, add this to the file:

use std::io;

fn fib (n: u32) -> u32 {
if n <= 0 {
return 0;
} else if n == 1 {
return 1;
} fib(n - 1) + fib(n - 2)

fn main() {
let mut nth = String::new();

println!("Enter input: ");

.read_line(&mut nth)
.expect("Failed to read line");

let nth: u32 = nth.trim().parse().expect("Please type a number!");

println!("Fibonacci: {}", fib(nth));


Compiling Rust Code

  1. Compile using cargo
cargo build
cargo run

Rust Screenshot1

  1. Compile to wasm
cargo build --target=wasm32-wasi

Rust Screenshot2

  1. The wasm file created in release folder of wasi32
file target/wasm32-wasi/release/demo.wasm
  1. Wasm runtime

wasmtime target/wasm32-wasi/release/demo.wasm

Rust Screenshot3