Summary - WASM and embedded
- Go course
- Expert
- Lesson 30/34
- 4 min
Combine WASM and TinyGo to write a platform analysis.
WASM and embedded summary
Go produces very different targets from the same code: the browser with GOOS=js GOARCH=wasm, WASI runtimes with GOOS=wasip1, embedded Linux with GOOS=linux GOARCH=arm, and microcontrollers with TinyGo. Target-specific code is separated with //go:build and file suffixes; business logic stays shared in pure functions.
An architecture tip
In a multi-target project split the code in three: the core (pure Go, side-effect-free, builds for every target), adapters (target-specific: syscall/js, os, machine) and entry points (a separate main per target). The core is tested with ordinary go test; hardware and browser stay only in the thin adapter layer.
Practice Shared core
Write a pure core that runs on every target: ortalama(olcum []float64) float64 returns 0 for an empty slice. Pass the result to fmt.Println through func yaz(f func(string), v float64), which imitates an adapter. Run it for []float64{20, 22, 24}.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func ortalama(olcum []float64) float64 {
if len(olcum) == 0 {
return 0
}
t := 0.0
for _, v := range olcum {
t += v
}
return t / float64(len(olcum))
}
func yaz(f func(string), v float64) {
f(fmt.Sprintf("%.1f", v))
}
func main() {
yaz(func(s string) { fmt.Println(s) }, ortalama([]float64{20, 22, 24}))
}Expected output
22.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If a Go module under 200 KB is needed in the browser, which is chosen?
- cgo
- GOOS=wasip1
- WASM with TinyGo Correct answer
- WASM with standard Go
Explanation: Standard Go WASM output is MB-sized because of the runtime; TinyGo can produce modules of tens of KB.
2 WASI target
GOOS=____ GOARCH=wasm go build -o app.wasm
GOOS=wasip1 GOARCH=wasm go build -o app.wasm
Explanation: wasip1 is the GOOS value targeting the WASI Preview 1 interface.
3 Group summary
| Term | Meaning |
|---|---|
js/wasm |
Browser |
wasip1/wasm |
Wasmtime, Wasmer |
linux/arm |
Embedded Linux |
TinyGo |
Microcontroller |