First Component in Go

Build the cargo-domain component in Go against the same WIT world with wit-bindgen-go and TinyGo, and see why standard go build can't finish the job.

⏱ 24 min readChapter 7Building Components in Rust & Go

Learning objectives

By the end of this chapter you can:

  • Generate Go bindings for world cargo with wit-bindgen-go generate and read what it produces: an Exports struct of function-valued fields per interface, and a table keyed by cm.Rep for cargo-tracker.
  • Implement every exported function and the cargo-tracker constructor, destructor and three methods as plain Go.
  • Reproduce the go:wasmexport errors that stop standard go build, and explain them as a pointer-width problem, not a Go limitation.
  • Run the working recipe (wit-bindgen-go generate, tinygo build -target=wasip1 -buildmode=c-shared, wasm-tools component embed, wasm-tools component new with the reactor adapter) and confirm it with wasm-tools component wit.
  • Say why a TinyGo component needs a hand-provided cabi_realloc when the Rust one doesn’t, and what breaks without it.

Why this matters

The Rust provider gets a Go counterpart built against the identical contract: the same three interfaces, the same functions, the same cargo-tracker resource. A native host built once against world cargo runs either component and gets byte-identical results. Composition and conformance check the WIT identifiers a component exports, not the language that produced it.

Getting there in Go means using a compiler other than the one on your PATH. GOOS=wasip1 GOARCH=wasm go build is the documented target for ordinary Wasm modules, and against these generated bindings it fails with a specific, repeatable diagnostic. TinyGo compiles the same source into a reactor component with no change to the domain logic. Only the compiler differs.

Three bands top to bottom: generation (contracts/wit through wit-bindgen-go generate into internal/cargo bindings, feeding hand-written main.go and cabi_realloc.go), compilation (tinygo build -target=wasip1 -buildmode=c-shared producing core.wasm, the one step that must be TinyGo), and componentization (wasm-tools component embed then component new with the reactor adapter, producing cargo-go.wasm).
Figure 7.1: The Go build pipeline. Generation and componentization use ordinary tools either way; only compilation, where TinyGo replaces go build, differs.

Generating the bindings

wit-bindgen-go reads the same contracts/wit directory and the same --world cargo the Rust build used:

wit-bindgen-go generate -o internal/cargo \
  -p example.com/cargo-go/internal/cargo \
  --world cargo ../../../contracts/wit

It writes a package tree under internal/cargo/patterncatalyst/cargo/, one subpackage per interface (types, booking, handling). Every file opens with // Code generated by wit-bindgen-go. DO NOT EDIT.

What matters for the domain code is the Exports struct each interface package declares. booking.exports.go is short enough to read whole:

// Exports represents the caller-defined exports from "patterncatalyst:cargo/booking@0.1.0".
var Exports struct {
	// BookCargo represents the caller-defined, exported function "book-cargo".
	//
	// Book a new cargo shipment against a route specification.
	//
	//	book-cargo: func(spec: route-spec, weight-kg: f64) -> result<booking, cargo-error>
	BookCargo func(spec RouteSpec, weightKg float64) (result cm.Result[BookingShape, Booking, CargoError])

	// RequestPossibleRoutes represents the caller-defined, exported function "request-possible-routes".
	//
	// Request the candidate itineraries that satisfy a booking's route
	// spec.
	//
	//	request-possible-routes: func(booking-id: string) -> result<list<itinerary>, cargo-error>
	RequestPossibleRoutes func(bookingID string) (result cm.Result[CargoErrorShape, cm.List[Itinerary], CargoError])

	// AssignRoute represents the caller-defined, exported function "assign-route".
	//
	// Assign one of the candidate itineraries to a booking.
	//
	//	assign-route: func(booking-id: string, itinerary: itinerary) -> result<booking,
	//	cargo-error>
	AssignRoute func(bookingID string, itinerary Itinerary) (result cm.Result[BookingShape, Booking, CargoError])

	// GetCargo represents the caller-defined, exported function "get-cargo".
	//
	// Look up a cargo by its tracking ID.
	//
	//	get-cargo: func(tracking-id: string) -> result<cargo, cargo-error>
	GetCargo func(trackingID string) (result cm.Result[CargoShape, Cargo, CargoError])
}

Exports isn’t an interface a type implements. It is a package-level struct of function-valued fields, each nil until the domain code assigns a closure; generated //go:wasmexport functions call whatever is assigned. cm.Result[BookingShape, Booking, CargoError] is wit-bindgen-go’s rendering of result<booking, cargo-error>: an Ok of Booking or an Err of CargoError, with BookingShape a same-size byte array that fixes the storage layout. cm.List[Itinerary] renders list<itinerary>. A result<_, cargo-error> with no success value, such as register-handling-event, becomes cm.Result[CargoError, struct{}, CargoError].

A resource adds one shape. handling.Exports.CargoTracker has Constructor, Destructor, CurrentStatus, History and TrackingID fields, and its constructor is:

		Constructor func(trackingID string) (result CargoTracker)

Every method takes a cm.Rep, an opaque handle the host passes back after the constructor returns one. It stands for “this cargo-tracker” without a pointer crossing the sandbox boundary. The component keeps whatever state the handle refers to.

Implementing the exports

go/main.go assigns every field in one init(). Result aliases declared once (type cargoResult = cm.Result[booking.CargoShape, types.Cargo, types.CargoError]) keep signatures short. cm.OK[...] and cm.Err[...] build the two sides of a result, and types.CargoErrorNotFound is a generated helper for the not-found case. GetCargo looks up a map; for an unknown ID it ends:

		c, ok := cargos[trackingID]
		if !ok {
			return cm.Err[cargoResult](types.CargoErrorNotFound("no cargo " + trackingID))
		}
		return cm.OK[cargoResult](c)

(Like the Rust provider, it panics on the sentinel ID __TRAP__, which the host sees as a trap rather than a cargo-error.)

BookCargo does the most work and is still ordinary Go: validation, deterministic IDs, two map writes, a typed return.

	booking.Exports.BookCargo = func(spec types.RouteSpec, weightKg float64) bookingResult {
		if spec.Origin.Unlocode == "" || spec.Destination.Unlocode == "" {
			return cm.Err[bookingResult](types.CargoErrorInvalidLocation(
				"origin and destination must each have a UN/LOCODE"))
		}
		if weightKg <= 0 {
			return cm.Err[bookingResult](types.CargoErrorInvalidBooking(
				"weight-kg must be greater than zero"))
		}

		trackingID := trackingIDFor(spec.Origin, spec.Destination)
		bookingID := bookingIDFor(spec.Origin, spec.Destination)

		cargos[trackingID] = types.Cargo{
			TrackingID:  trackingID,
			Origin:      spec.Origin,
			Destination: spec.Destination,
			WeightKg:    weightKg,
		}
		b := types.Booking{
			BookingID: bookingID,
			CargoID:   trackingID,
			RouteSpec: spec,
			Price:     types.Money{Amount: priceAmount, Currency: priceCurrency},
			Status:    types.RoutingStatusNotRouted,
		}
		bookings[bookingID] = b
		return cm.OK[bookingResult](b)
	}

Nothing there touches cm.Rep or linear memory beyond the cm.Result return type. trackingIDFor, bookingIDFor and the price constants match the Rust values, because the host diffs the two components’ output, so they must agree on every derived ID and fixed price, not only on WIT shapes.

RequestPossibleRoutes builds a cm.List, and AssignRoute reads one with Legs.Len() to reject an itinerary with no legs:

	booking.Exports.RequestPossibleRoutes = func(bookingID string) itinerariesResult {
		b, ok := bookings[bookingID]
		if !ok {
			return cm.Err[itinerariesResult](types.CargoErrorNotFound("no booking " + bookingID))
		}
		spec := b.RouteSpec
		itinerary := types.Itinerary{
			BookingID: bookingID,
			Legs: cm.ToList([]types.Leg{{
				VoyageID:       voyageID,
				LoadLocation:   spec.Origin,
				UnloadLocation: spec.Destination,
				LoadTime:       legLoadTime,
				UnloadTime:     spec.ArrivalDeadline,
				Status:         types.TransportStatusPlanned,
			}}),
		}
		return cm.OK[itinerariesResult](cm.ToList([]types.Itinerary{itinerary}))
	}

cm.ToList wraps a Go slice as the cm.List[T] that list<T> expects. The generated lowering code turns it into the (pointer, length) pair the canonical ABI puts on the wire.

The cargo-tracker resource

The resource’s state has to outlive any one export call, and cm.Rep carries no storage. The Go pattern is a package-level table keyed by cm.Rep:

type trackerState struct {
	trackingID string
}

var (
	trackers           = map[cm.Rep]*trackerState{}
	nextTracker cm.Rep = 1
)

The constructor, destructor and TrackingID maintain it:

	handling.Exports.CargoTracker.Constructor = func(trackingID string) handling.CargoTracker {
		rep := nextTracker
		nextTracker++
		trackers[rep] = &trackerState{trackingID: trackingID}
		return handling.CargoTrackerResourceNew(rep)
	}

	handling.Exports.CargoTracker.Destructor = func(self cm.Rep) {
		delete(trackers, self)
	}

	handling.Exports.CargoTracker.TrackingID = func(self cm.Rep) string {
		if t, ok := trackers[self]; ok {
			return t.trackingID
		}
		return ""
	}

handling.CargoTrackerResourceNew is generated. It turns a cm.Rep into the typed handling.CargoTracker handle the constructor returns by registering the rep with the host’s resource table. The component stores no pointer in that handle; the integer and the trackers map are the whole state.

CurrentStatus and History read the shared events map instead of copying events into trackerState:

	handling.Exports.CargoTracker.CurrentStatus = func(self cm.Rep) types.TransportStatus {
		t, ok := trackers[self]
		if !ok {
			return types.TransportStatusUnspecified
		}
		history := events[t.trackingID]
		if len(history) == 0 {
			return types.TransportStatusUnspecified
		}
		return statusFromLastEvent(history[len(history)-1].EventType)
	}

A tracker built before three events were recorded still reports the current status after they land, as with the Rust Tracker.

Why go build stops here

The natural next step is the compiler already on PATH:

GOOS=wasip1 GOARCH=wasm go build -o core.wasm .

On Go 1.26.9 it fails the same way every time, in generated files and not in main.go:

# example.com/cargo-go/internal/cargo/patterncatalyst/cargo/handling
internal/cargo/patterncatalyst/cargo/handling/handling.wasm.go:52:6: go:wasmexport: unsupported result type *cm.List[...types.HandlingEvent]
internal/cargo/patterncatalyst/cargo/handling/handling.wasm.go:61:6: go:wasmexport: unsupported result type *string
internal/cargo/patterncatalyst/cargo/handling/handling.wasm.go:70:6: go:wasmexport: unsupported result type *cm.Result[...types.CargoError,struct {},...types.CargoError]
# example.com/cargo-go/internal/cargo/patterncatalyst/cargo/booking
internal/cargo/patterncatalyst/cargo/booking/booking.wasm.go:14:6: go:wasmexport: unsupported result type *cm.Result[...booking.BookingShape,...types.Booking,...types.CargoError]
internal/cargo/patterncatalyst/cargo/booking/booking.wasm.go:33:6: go:wasmexport: unsupported parameter type *types.Leg

Each rejected function carries a //go:wasmexport pragma, for example in booking.wasm.go:

//go:wasmexport patterncatalyst:cargo/booking@0.1.0#book-cargo
//export patterncatalyst:cargo/booking@0.1.0#book-cargo
func wasmexport_BookCargo(spec0 *uint8, spec1 uint32, spec2 *uint8, spec3 uint32, spec4 *uint8, spec5 uint32, spec6 *uint8, spec7 uint32, spec8 *uint8, spec9 uint32, spec10 *uint8, spec11 uint32, spec12 *uint8, spec13 uint32, weightKg0 float64) (result *cm.Result[BookingShape, Booking, CargoError]) {

go:wasmexport is the standard toolchain’s own way to export a function to a Wasm host. The restriction is about pointer width, not about cm.Result or cm.List as types. GOOS=wasip1 GOARCH=wasm is Go’s 64-bit-pointer Wasm target, and go:wasmexport refuses a pointer to a pointerful multi-word type, which is the shape WIT’s result, list, string and records need. The compiler’s own text says these signatures would be allowed on GOARCH=wasm32, but wasip1/wasm32 has no buildable build mode on the installed Go (c-shared, c-archive, pie and the default all refuse), and there is no wasm32 GOEXPERIMENT.

Two side-by-side panels compiling the identical main.go and generated bindings: the left panel, GOOS=wasip1 GOARCH=wasm go build, flags 64-bit pointers against the generated wasmexport signatures and rejects *cm.Result, *cm.List, *string, and *types.Leg, failing with no core.wasm produced; the right panel, tinygo build -target=wasip1, targets wasm32 natively with no such pointer-width restriction and accepts the same signatures, producing core.wasm with reactor exports.
Figure 7.2: Same source, two compilers. go build's 64-bit Wasm target rejects the pointerful wasmexport signatures; TinyGo's 32-bit target accepts them unchanged.

This isn’t a Go dialect. main.go, the generated bindings and the cm package are identical under either compiler. Only one of the two currently targets 32-bit Wasm the way the canonical ABI’s generated signatures require. One more pin: go.bytecodealliance.org/cm resolves only to v0.3.0, because the later tags were cut on the monorepo root module and Go rejects them for the /cm import path.

The TinyGo build

TinyGo targets wasm32 natively, so the same tree compiles:

tinygo build -target=wasip1 -buildmode=c-shared -o core.wasm .

-target=wasip1 selects the WASI Preview 1 calling convention at the core-module level; the next two steps add the Component Model. -buildmode=c-shared produces a reactor (_initialize, callable exports, no startup main) rather than a command (_start, runs main() once and exits). A cargo provider must be a reactor because the host instantiates it once and calls its exports repeatedly. The Go toolchain still requires a main, which a reactor never runs:

// main is required by the Go toolchain for the module build, but a reactor
// component never runs it: the host instantiates the component and calls the
// exported functions directly.
func main() {}

Without -buildmode=c-shared you get a command. Paired with the reactor adapter it doesn’t fail at build time: it instantiates, the runtime never initializes, and the first export call panics inside runtime.wasmExportCheckRun.

cabi_realloc

wasm-tools component new requires the core module to export cabi_realloc, the canonical ABI’s allocator that the runtime calls to size the buffers for strings and lists crossing the boundary. Without it, component new fails with “module does not export a function named cabi_realloc.” The upstream go.bytecodealliance.org/x/cabi package has the right logic but no //export directive, so the project provides cabi_realloc.go:

//export cabi_realloc
func cabiRealloc(ptr unsafe.Pointer, size, align, newsize uintptr) unsafe.Pointer {
	if newsize <= size {
		return ptr
	}
	newptr := cabiAlloc(newsize, align)
	if size > 0 {
		copy(unsafe.Slice((*byte)(newptr), newsize), unsafe.Slice((*byte)(ptr), size))
	}
	return newptr
}

cabiAlloc picks a slice element type matching the requested alignment and allocates with make, so the TinyGo runtime and its garbage collector own the memory the host reads and writes. Rust’s cargo-component needs no such file because the wit-bindgen crate it depends on already exports cabi_realloc.

Componentizing: embed, then wrap

Two wasm-tools subcommands turn the wasip1 core module into the component. cargo-component runs the same tool internally.

  • component embed attaches the cargo world’s type information to the core module, which on its own exports only flat i32, i64, f32 and f64 functions.
  • component new wraps the result in the component binary format. It also needs an adapter that translates the wasip1 syscalls TinyGo’s runtime makes into the wasip2 WASI interfaces (wasi:cli, wasi:io, wasi:filesystem) a component host supplies. adapters/wasi_snapshot_preview1.reactor.wasm is that adapter, vendored from a Wasmtime release. Use the reactor variant for a reactor core. The command variant is for a core built without the flag, and mixing them fails silently until a call reaches the component.

wit-bindgen-go generate and wasm-tools component embed read the contract through a Wasmtime filesystem sandbox that resolves only paths relative to the current directory. build.sh changes into the Go example’s directory and passes ../../../contracts/wit for that reason; an absolute path fails with “failed to find a pre-opened file descriptor”. (wasm-tools component wit, used only to inspect, accepts an absolute path.)

build.sh runs all four steps and validates the result:

echo "build.sh: [1/4] generating Go bindings from the contract ..."
wit-bindgen-go generate -o internal/cargo \
  -p example.com/cargo-go/internal/cargo \
  --world cargo "$CONTRACT_DIR"

echo "build.sh: [2/4] tinygo build (wasip1 reactor core module) ..."
tinygo build -target=wasip1 -buildmode=c-shared -o core.wasm .

echo "build.sh: [3/4] embedding the cargo world ..."
wasm-tools component embed "$CONTRACT_DIR" --world cargo core.wasm -o embedded.wasm

echo "build.sh: [4/4] creating the component (wasip1 -> wasip2 via adapter) ..."
wasm-tools component new embedded.wasm \
  --adapt "wasi_snapshot_preview1=$ADAPTER" \
  -o "$OUT"

rm -f core.wasm embedded.wasm

echo "build.sh: wrote $OUT"
wasm-tools validate "$OUT"

Confirming the export surface

wasm-tools component wit reads the export list back from the binary:

$ wasm-tools component wit cargo-go.wasm
world root {
  import wasi:cli/environment@0.2.12;
  import wasi:io/streams@0.2.12;
  import wasi:clocks/monotonic-clock@0.2.12;
  import wasi:filesystem/types@0.2.12;
  import wasi:random/random@0.2.12;
  ...

  export patterncatalyst:cargo/types@0.1.0;
  export patterncatalyst:cargo/booking@0.1.0;
  export patterncatalyst:cargo/handling@0.1.0;
}

The imports are the wasip2 WASI surface the adapter satisfies; TinyGo’s runtime calls WASI even when the reactor touches no file. The three exports are exactly what world cargo declares and what the Rust cargo_rust.wasm exports, so a consumer or host reads the same world either way.

Running it through the host

host/ is the native Wasmtime binary from the Rust component’s chapter, built with wasmtime::component::bindgen!({ world: "cargo" }). It drives one scenario: book USNYC to DEHAM at 1200.5 kg, fetch the cargo, request routes, assign one, register three handling events, list them, then construct a cargo-tracker and read its ID, status and history.

./host/target/release/cargo-host go/cargo-go.wasm fixtures/scenario.json go

It prints [go] all assertions passed to stderr and a pretty-printed JSON summary to stdout: the booking (BOOKING-USNYC-DEHAM, price 1500.00 USD, status not-routed), the cargo, the itinerary leg, the assigned status routed, the event count, and the tracker (CARGO-USNYC-DEHAM, in-transit, three history entries). The same command against the Rust component, with rust as the label, prints a byte-identical summary.

Decision

Build Component Model providers in Go with TinyGo, not standard go build. The constraint is mechanical: GOARCH=wasm has 64-bit pointers, //go:wasmexport rejects pointers to pointerful result and parameter types on that target, and wit-bindgen-go emits exactly those shapes for any WIT result, list, string or record. The rejected signatures live in generated code, so no rewrite of main.go avoids it. TinyGo targets wasm32 natively and compiles the same source and bindings unchanged. Watch for a wasm32 GOARCH or GOEXPERIMENT in standard Go (the compiler’s error already names GOARCH=wasm32 as where the signatures are legal), and for cm or wit-bindgen-go shipping their own cabi_realloc, which would remove the only other TinyGo-specific file. Until then everything around the single compile step is toolchain-neutral: the contract, the bindings, the domain logic and the wasm-tools componentization.

🤖 Explore with your agent

“In examples/part2-building-components/go/main.go, implement booking.Exports.GetCargo so it returns types.CargoErrorNotFound for an unknown ID, then rebuild with go/build.sh (wit-bindgen-go generate, tinygo build -target=wasip1 -buildmode=c-shared, wasm-tools component embed, wasm-tools component new with the reactor adapter). Next run GOOS=wasip1 GOARCH=wasm go build -o core.wasm . in the same directory and explain, from the go:wasmexport errors, which generated signatures it rejects and why TinyGo accepts them.”

Check: build.sh ends by validating cargo-go.wasm, and the go build output names go:wasmexport: unsupported result type for files under internal/cargo/.

Build, run, observe

cd examples/part2-building-components && ./verify.sh

The script builds the Go provider with build.sh, builds the Rust provider and the native host, then runs the host against both over one fixture. It checks the full booking, handling and tracker scenario, a recoverable cargo-error::not-found against an unrecoverable trap, that both artifacts export exactly world cargo, and that the two JSON summaries match byte for byte. It then composes the consumer components with each provider using wac plug and runs all four pairs under wasmtime run. Expect PASS.

  • Drop -buildmode=c-shared from the tinygo build line: the component builds and instantiates, and the first export call panics in runtime.wasmExportCheckRun.
  • Delete cabi_realloc.go: wasm-tools component new fails with “module does not export a function named cabi_realloc”.
  • Pass an absolute path for the contract directory: wit-bindgen-go generate and component embed fail with “failed to find a pre-opened file descriptor”.
  • Run GOOS=wasip1 GOARCH=wasm go build on the same tree: it fails with the go:wasmexport errors above and produces no core.wasm.

For deeper coverage

  • Danilo Chiarlone, Server-Side WebAssembly (Manning): compiling Go and TinyGo sources into components, including the WASI Preview 1 to 2 adapter boundary the reactor adapter crosses.
  • Shashank Jain, WebAssembly for Cloud (Apress): cross-language Component Model interoperability, the proof one host driving two independently built components provides.
  • wit-bindgen-go repository: the generator and the cm package that Exports, cm.Result and cm.List come from.
  • TinyGo documentation: WebAssembly guide: the wasip1 and wasip2 targets and -buildmode options this recipe uses.
  • Go Wiki: WebAssembly: the GOOS=wasip1 GOARCH=wasm target and the //go:wasmexport directive whose restriction is reproduced here.