Wasm Builders 🧱

Cover image for Golang to WASI  #PART1
Jennifer
Jennifer

Posted on

Golang to WASI #PART1

Go, also known as Golang, is an open-source, compiled, and statically typed programming language designed by Google. It is built to be simple, high-performing, readable, and efficient. lets try to compile Go to WASI

Prerequisites

  • Install Golang,go to go.dev and follow the instructions.

  • Install tinygo, go to tinygo.org and follow the instructions.
    NB: please note: tinygo requires go version 1.15 through 1.17

  • Install wasmtime,you will find wasmtime at wasmtime.dev

First example, we would create a simple Go program that checks in an integer input is odd or even.
Create a folder with a name of your choice, i would be using "Golang-to-WASI" as the name of my folder.

cd Golang-to-WASI
Enter fullscreen mode Exit fullscreen mode

create a file main.go, add following code into your main.go file and save the file.

// Simple Program to Check Entered Number is Even or Odd

package main

import "fmt"

func main(){
    fmt.Print("Enter number : ")
    var n int
    fmt.Scanln(&n)

    if(n%2==0){
        fmt.Println(n,"is an Even number")
    }else{
        fmt.Println(n,"is Odd number")
    }
}

Enter fullscreen mode Exit fullscreen mode

Run your code and provide input to see the result

go run main.go
Enter fullscreen mode Exit fullscreen mode

screenshot 1
We will can compile to WASM using the following command:

tinygo build -wasm-abi=generic -target=wasi -o main.wasm main.go
Enter fullscreen mode Exit fullscreen mode

Now let us run the WebAssembly generated using wasmtime

wasmtime main.wasm
Enter fullscreen mode Exit fullscreen mode

screenshot 2

See full code at github
In part 2, we will look at file systems with Golang and wasi, cheers!

Latest comments (0)