Wasm Builders

Cover image for WebAssembly with zig
sahitya
sahitya

Posted on

WebAssembly with zig

Enviroment setup

TO compline this demo, you must install these packages listed below.

zig

Install zig.

Install zig on Fedora 34 Using dnf

sudo dnf makecache --refresh
Enter fullscreen mode Exit fullscreen mode

After updating yum database, We can install zig using dnf by running the following command:

sudo dnf -y install zig
Enter fullscreen mode Exit fullscreen mode

Note : if you are using other operating system Go to ziglang.org and follow the instructions.

Wasmtime

You will find wasmtime at wasmtime.dev

Zig Code

const std = @import("std");

fn fibonacci(index: u32) u32 {
    if (index < 2) return index;
    return fibonacci(index - 1) + fibonacci(index - 2);
}

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    var x: u32 = 7;

    try stdout.print("fibonacci of {d} ", .{x});
    try stdout.print("is: {d} \n ", .{fibonacci(x)}  );
}
Enter fullscreen mode Exit fullscreen mode

Compiling zig code

  1. compile using zig
zig run main.zig
Enter fullscreen mode Exit fullscreen mode
  1. compile to WASM using the following command:
zig build-exe main.zig -target wasm32-wasi
Enter fullscreen mode Exit fullscreen mode
  1. file main.wasm
file main.wasm
Enter fullscreen mode Exit fullscreen mode
  1. wasm runtime
wasmtime main.wasm
Enter fullscreen mode Exit fullscreen mode

final result.

vmware_2vH0ylY6ne

Discussion (2)

Collapse
anara profile image
Silvana

Great Sahitya, I never used zig. Seems interesting!

Collapse
ydvsahitya profile image
sahitya Author

ThANKS.