dynamic

package
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package dynamic provides Any, a type-erased value that remembers enough to safely recover its concrete type later — Haskell's Data.Dynamic, or the same shape as protobuf's google.protobuf.Any (a type name plus a payload, resolved through a registry), adapted for JSON.

Unlike Rust's std::any::Any (backed by a language-level TypeId, no registration needed) or Go's own reflect.Type (not stable across process restarts or a JSON round-trip), Any needs every concrete type it will ever hold to be Registered under a caller-chosen name first — JSON has no native concept of a stable, portable type identity.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func As added in v0.13.0

func As[T any](d Any) option.Option[T]

As extracts the boxed value as T, returning None if the assertion fails or d holds no value — the Option-native alternative to a raw type assertion on Value().

func Register

func Register[T any](name string)

Register makes T recoverable from an Any under name — call once, typically from an init(), before any New or UnmarshalJSON call: the registry has no locking, the same assumption gob.Register and protobuf's registry make. name is entirely the caller's choice, never derived from T itself, the same way a protobuf message's type URL comes from its .proto package+name rather than its generated Go type. Register panics on a duplicate name, so a collision fails at init time rather than resolving to the wrong type at some later Unmarshal.

Types

type Any

type Any struct {
	// contains filtered or unexported fields
}

Any holds a value of Registered type, type-erased. Use New to construct; never use the zero value directly (though the zero value does happen to hold no value, the same way None[T]() does for Option).

func New

func New(v any) Any

New boxes v, identified by its own runtime type. Panics if that type was never Registered — the same fail-fast stance Register itself takes, and the same shape as option.Some panicking on a nil value: a programmer error, not a condition to recover from.

func (Any) MarshalJSON

func (d Any) MarshalJSON() ([]byte, error)

MarshalJSON writes null for a zero-value Any (no value ever boxed), or {"@type":...,"value":...} otherwise.

func (*Any) UnmarshalJSON

func (d *Any) UnmarshalJSON(data []byte) error

UnmarshalJSON reads null as a zero-value Any, and {"@type":...,"value":...} as a boxed value of the type "@type" names — an exact lookup, erroring (not panicking — this is untrusted input, unlike New) if that name was never Registered.

func (Any) Value

func (d Any) Value() any

Value returns the boxed value, or nil if none was ever set.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL