Wasm dari Go dan C++
Selain Rust, Go dan C/C++ juga bisa compile ke WebAssembly. Setiap bahasa punya trade-off berbeda.
Go → WebAssembly
// main.go
package main
import (
"fmt"
"syscall/js"
)
func add(this js.Value, args []js.Value) interface{} {
a := args[0].Int()
b := args[1].Int()
return a + b
}
func main() {
fmt.Println("Go WebAssembly Initialized")
// Register fungsi Go agar bisa dipanggil dari JS
js.Global().Set("goAdd", js.FuncOf(add))
// Jangan biarkan main() selesai
select {}
}
# Build dengan Go standard
GOOS=js GOARCH=wasm go build -o main.wasm main.go
# ⚠️ Output besar: ~2-5MB karena Go runtime
# Alternatif: TinyGo (output jauh lebih kecil)
tinygo build -o main.wasm -target wasm main.go
# Output: ~50-200KB 🎉
C/C++ → WebAssembly (Emscripten)
// math.c
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
EMSCRIPTEN_KEEPALIVE
double compute_pi(int iterations) {
double pi = 0.0;
for (int i = 0; i < iterations; i++) {
pi += (i % 2 == 0 ? 1.0 : -1.0) / (2 * i + 1);
}
return pi * 4;
}
# Install Emscripten
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk && ./emsdk install latest && ./emsdk activate latest
# Compile
emcc math.c -o math.js -s EXPORTED_FUNCTIONS='["_factorial","_compute_pi"]' \
-s EXPORTED_RUNTIME_METHODS='["ccall","cwrap"]'
// Pakai di JavaScript
const factorial = Module.cwrap("factorial", "number", ["number"]);
const computePi = Module.cwrap("compute_pi", "number", ["number"]);
console.log(factorial(10)); // 3628800
console.log(computePi(1000000)); // 3.14159165...
Perbandingan
- Rust — Output terkecil (~20-100KB), tooling terbaik untuk Wasm, no runtime
- Go (TinyGo) — Mudah dipelajari, output ~50-200KB, limited std library
- Go (standard) — Full std library, tapi output 2-5MB (membawa GC runtime)
- C/C++ (Emscripten) — Paling mature, ideal untuk porting library existing (ffmpeg, SQLite)