optional

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 3 Imported by: 0

README

optional-go

Generics-friendly Optional/Field type for Go. Enables explicit presence/absence, ergonomic helpers, and clean JSON handling with omitempty.

Quick Start

type User struct {
  Name string
  Age  optional.Field[int] `json:"age,omitempty"`
}

u := User{Name: "Ava"}
// Age is absent; omitted in JSON due to IsZero.
b, _ := json.Marshal(u) // {"Name":"Ava"}

// Set a value
u.Age.Set(0) // present with zero; still serialized
_ = json.Unmarshal([]byte(" {\n  \"age\": null\n} "), &u) // clears Age (absent)

// Get with defaults
age := u.Age.OrElse(18)
age2 := u.Age.OrElseGet(func() int { return 21 })

// Functional helpers
plusOne := optional.Map(u.Age, func(v int) int { return v + 1 })

// Constructors
none := optional.None[int]()
some := optional.NewField(42)
adopt := optional.AdoptPtr(&[]int{1,2,3}[0]) // advanced: shares pointer

API Highlights

  • New/None:
    • NewField[T](v T) creates a present value.
    • NewFieldFromPtr[T](*T) copies from pointer if non-nil.
    • AdoptPtr[T](*T) adopts pointer, enabling aliasing.
    • None[T]() creates an absent value.
  • Presence:
    • Present() bool, Clear().
    • Get() (T, bool), MustGet() T, ToPtr() *T (pointer to copy), Ref() (*T, bool) (internal pointer).
  • Defaults and flow:
    • OrElse(T) T, OrElseGet(func() T) T.
    • If(func(T)), IfPresentOrElse(func(T), func()).
  • Functors:
    • Map[T,U](Field[T], func(T) U) Field[U].
    • FlatMap[T,U](Field[T], func(T) Field[U]) Field[U].
    • Filter[T](Field[T], func(T) bool) Field[T].
  • JSON:
    • Implements json.Marshaler/Unmarshaler.
    • Robust null handling (whitespace tolerant).
    • Implements IsZero() so omitempty omits absent fields on Go 1.20+.

Notes

  • Absent vs. present-nil: For pointer/interface T, both absent and present-with-nil serialize to null and look identical in JSON.
  • Concurrency: Field[T] is not synchronized; guard with your own locks if sharing between goroutines.
  • ToPtr() returns a pointer to a copy to avoid unintended aliasing. Use Ref() or AdoptPtr() only if you need shared mutation.
License

optional-go is released under the MIT license. See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Field

type Field[T any] struct {
	// contains filtered or unexported fields
}

func AdoptPtr

func AdoptPtr[T any](v *T) Field[T]

AdoptPtr creates a Field[T] that references the provided pointer directly. Mutations through the returned reference will affect the original value.

func Filter

func Filter[T any](in Field[T], pred func(T) bool) Field[T]

Filter returns the same field if the predicate holds, otherwise None.

func FlatMap

func FlatMap[T, U any](in Field[T], f func(T) Field[U]) Field[U]

FlatMap transforms the Field[T] to Field[U] using f when present.

func Map

func Map[T, U any](in Field[T], f func(T) U) Field[U]

Map transforms the Field[T] to Field[U] using f when present.

func NewField

func NewField[T any](v T) Field[T]

func NewFieldFromPtr

func NewFieldFromPtr[T any](v *T) Field[T]

func None

func None[T any]() Field[T]

None returns an absent Field[T].

func (*Field[T]) Clear

func (i *Field[T]) Clear()

Clear marks the field as absent.

func (*Field[T]) Get

func (i *Field[T]) Get() (T, bool)

func (*Field[T]) If

func (i *Field[T]) If(fn func(T))

func (*Field[T]) IfPresentOrElse

func (i *Field[T]) IfPresentOrElse(fn func(T), elseFn func())

IfPresentOrElse executes fn if present, otherwise elseFn.

func (Field[T]) IsZero

func (i Field[T]) IsZero() bool

IsZero enables json omitempty to treat an absent field as zero.

func (*Field[T]) MarshalJSON

func (i *Field[T]) MarshalJSON() ([]byte, error)

func (*Field[T]) MustGet

func (i *Field[T]) MustGet() T

func (*Field[T]) OrElse

func (i *Field[T]) OrElse(v T) T

func (*Field[T]) OrElseGet

func (i *Field[T]) OrElseGet(supplier func() T) T

OrElseGet returns the contained value if present, otherwise uses supplier.

func (*Field[T]) Present

func (i *Field[T]) Present() bool

func (*Field[T]) Ref

func (i *Field[T]) Ref() (*T, bool)

Ref returns the internal pointer and whether it is present. Mutating through the returned pointer (when ok) affects the stored value.

func (*Field[T]) Set

func (i *Field[T]) Set(v T)

func (Field[T]) String

func (i Field[T]) String() string

String returns a human-friendly representation for diagnostics.

func (*Field[T]) ToPtr

func (i *Field[T]) ToPtr() *T

func (*Field[T]) UnmarshalJSON

func (i *Field[T]) UnmarshalJSON(data []byte) error

Jump to

Keyboard shortcuts

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