polymorphic

package
v0.1.0-alpha.46 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2025 License: MIT Imports: 3 Imported by: 21

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearRegistry

func ClearRegistry()

func MarshalPolymorphicJSON

func MarshalPolymorphicJSON(obj Polymorphic) ([]byte, error)

Marshal an object with a discriminator

func Register

func Register[T Polymorphic](factory func() T)

func RegisterType

func RegisterType[T any]()

func RegisterWithDiscriminator

func RegisterWithDiscriminator(discriminator string, factory TypeFactory)

Register stores a factory function with its discriminator.

Types

type Envelope

type Envelope struct {
	Discriminator string `json:"$type"`
	Content       any    `json:"-"`
}

Envelope holds type info and raw JSON data

func NewEnvelope

func NewEnvelope(obj Polymorphic) *Envelope

Create a new Envelope with a discriminator and content

func UnmarshalPolymorphicJSON

func UnmarshalPolymorphicJSON(data []byte) (*Envelope, error)

func (*Envelope) MarshalJSON

func (e *Envelope) MarshalJSON() ([]byte, error)

Implements json.Marshaler

func (*Envelope) UnmarshalJSON

func (e *Envelope) UnmarshalJSON(data []byte) error

Implements json.Unmarshaler UnmarshalJSON is a custom JSON unmarshaler for the Envelope type. It extracts the raw JSON data into a map and looks for a discriminator field named "$type" to determine the concrete type of the content. The content is then unmarshaled into the appropriate type using a factory function registered for the discriminator. If any required fields are missing or if unmarshaling fails, an error is returned.

Parameters: - data: The JSON-encoded data to be unmarshaled.

Returns: - error: An error if unmarshaling fails or if required fields are missing.

type Polymorphic

type Polymorphic interface {
	GetDiscriminator() string
}

Polymorphic ensures types implement GetDiscriminator().

func CreateInstance

func CreateInstance(discriminator string) (Polymorphic, error)

CreateInstance creates an instance based on the discriminator.

type TypeFactory

type TypeFactory = func() any

TypeFactory creates instances of registered types.

func LoadFactory

func LoadFactory(discriminator string) (TypeFactory, error)

Jump to

Keyboard shortcuts

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