Files
wazero/examples/basic
Crypt Keeper b758344212 API BREAK: renames InstantiateModuleFromBinary to Instantiate (#1129)
This renames `InstantiateModuleFromBinary` to `Instantiate` to both make
first time use simpler to write and also de-complicate adding a
`WithConfig` variant as requested in #1105

End users in simple case need to change their signature like so.
```diff
-       mod, err := r.InstantiateModuleFromBinary(ctx, addWasm)
+       mod, err := r.Instantiate(ctx, addWasm)
```

In practice, many will not need to change their signature because they
had to use the `InstantiateModule` function in order to assign
configuration such as the module name, filesystem or use a real clock.
Instead, they had to use the more complicated chain of `CompileModule`
and `InstantiateModule` even when only assigning config. Users in this
situation can opt into the more simplified syntax below:

```go
mod, err := r.InstantiateWithConfig(ctx, addWasm,
	wazero.NewModuleConfig().WithName("adder"))
```



```diff
-       mod, err := r.InstantiateModuleFromBinary(ctx, addWasm)
+       mod, err := r.Instantiate(ctx, addWasm)
```

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-02-15 14:52:17 -10:00
..

Basic example

This example shows how to extend a Go application with an addition function defined in WebAssembly.

$ go run add.go 7 9
7 + 9 = 16

Compilation

wazero is a WebAssembly runtime, embedded in your host application. To run WebAssembly functions, you need access to a WebAssembly Binary (Wasm), typically a %.wasm file.

add.wasm was compiled from add.go with TinyGo, as it is the most common way to compile Go source to Wasm. Here's the minimal command to build a %.wasm binary.

cd testdata; tinygo build -o add.wasm -target=wasi add.go

Notes

  • Many other languages compile to (target) Wasm including AssemblyScript, C, C++, Rust, and Zig!
  • The embedding application is often called the "host" in WebAssembly.
  • The Wasm binary is often called the "guest" in WebAssembly. Sometimes they need imports to implement features such as console output. TinyGo's wasi target, requires WASI imports.