Wasm Builders

Cover image for GO with WASM
Kirtee Prajapati
Kirtee Prajapati

Posted on

GO with WASM

Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson.

It is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.

Environment Setup

1. Get Golang

2. Get Tinygo

Note Before installing be carefull abouth the version range because
Tinygo requires golang version 1.15 through 1.17

For Linux user:

$ sudo snap install --classic --channel=1.15/stable go
Enter fullscreen mode Exit fullscreen mode

Verify Installations

$ tinygo version
$ go version
Enter fullscreen mode Exit fullscreen mode

3. Get Wasmtime.dev

Once done with the installation let's move towards the codding part.

# Create directory Ouside_Browser
$ mkdir Outside_Browser
$ cd Outside_browser

# Initialied go directory 
$ go mod init Outside_Browser
Enter fullscreen mode Exit fullscreen mode

This creates a file named go.mod

# Create main.rs file
$ touch main.rs

# open your fav IDE I switched to VSCode.
$ code .
Enter fullscreen mode Exit fullscreen mode

Paste the below Go code inside main.go.

package main
import "fmt"
func main(){
   var n int
   fmt.Print("Enter a number: ")
   fmt.Scanf("%d", &n)
   for i:=0; i<=n; i++{
      for j:=0; j<n-i; j++{
         fmt.Printf(" ")
      }
      for k:=0; k<i; k++{
      fmt.Printf("*")
   }
   fmt.Println()
}
}
Enter fullscreen mode Exit fullscreen mode

Compiling the Go code

  1. Compile Using Go
go run main.go
Enter fullscreen mode Exit fullscreen mode

Image description

  1. Compile to WASM
$ tinygo build -wasm-abi=generic -target=wasi -o main.wasm main.go
Enter fullscreen mode Exit fullscreen mode

This creates a file main.wasm

Image description

  1. wasm runtime
$ wasmtime main.wasm
Enter fullscreen mode Exit fullscreen mode

Image description

So simple right ..!!

Discussion (0)