liveBook · Manning

Option

As explained in Server-Side WebAssembly

Option is Rust's enum type for representing either a present value or the absence of a value.

Option represents a value that may be present or absent. In a Rust-backed key-value store, HashMap::get returns Option<String>: a stored value becomes Some, while a missing key becomes None. Keeping that possibility in the return type avoids pretending every lookup succeeds. section 3.4.2

For a WebAssembly component interface, express the same contract as option<string>. WIT supplies optional values as an interface-level type, and the Canonical ABI marshals richer interface values across host and guest boundaries rather than adding them as core Wasm primitives. section 2.4 section 3.4.2

A key-value lookup across the component boundary

Define get as returning option<string>, then return the HashMap lookup directly instead of calling unwrap. A JavaScript guest sees the generated declaration as string | undefined, where undefined corresponds to None. This makes the interface honest, but a guest that promises a string can still crash at runtime when a key is absent. section 3.4.2 section 3.4.3

Listing 3.8 The TypeScript declaration file for our key-value store interface
/** @module Interface component:smartcms/kvstore **/
export function get(key: string): string | undefined;
export function set(key: string, value: string): void;

Inspect the generated TypeScript declaration to see option<string> represented as string | undefined for the JavaScript guest. section 3.4.3

How Server-Side WebAssembly covers it

How deep it goes
Works through a HashMap lookup, WIT signature, generated TypeScript mapping, and the runtime failure risk of assuming presence.
Examples
Uses a SmartCMS kvstore get operation, a guest-hello value, Rust Option<String>, and a generated string | undefined declaration.
What you can do after
Apply it via WIT by declaring option<string> and returning a Rust HashMap lookup without unwrap.
How it connects
Connects Option to HashMap, WebAssembly Interface Types, Canonical ABI, TypeScript, and JavaScript.

Also explained in

Compare how 9 books explain option →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Server-Side WebAssembly. The section links point to the parts of the book it draws on.