opt

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 9 Imported by: 0

README

opt

Optional types for Go — a Go-idiomatic Option<T>
Full SQL + JSON integration. Three-state PATCH support. Zero dependencies beyond stdlib.

CI Go Reference Go Report Card License


Why opt?

Go's sql.Null[T] handles SQL but will never get JSON support (closed as infeasible). Pointers (*string) work but have overhead and awkward ergonomics. opt fills this gap permanently.

type User struct {
    Name  opt.String `json:"name"`
    Email opt.String `json:"email,omitzero"`
    Age   opt.Int    `json:"age"`
}
// {"name":"Alice","age":null}  — Email omitted (omitzero), Age is explicit null

Features

  • Generic foundationOption[T] works with any type via sql.Null[T]
  • 9 concrete types — String, Int, Int32, Int16, Float, Bool, Byte, Time
  • Three-state Field[T] — distinguish absent / null / value for PATCH APIs
  • Functional APIMap, FlatMap, Equal for composable transformations
  • Zero dependencies — only Go stdlib (database/sql, encoding/json)
  • FieldFromOption — lossless Option→Field conversion for PATCH workflows
  • SQL-readyScanner/Valuer via sql.Null[T], works with pgx, database/sql
  • JSON-ready — proper null marshaling, omitzero support (Go 1.24+)
  • json/v2 compatible — works with encoding/json/v2 without changes
  • zero/ subpackage — alternative semantics where zero value = null
  • Benchmarked — zero-allocation unmarshal, Bool marshal in <1ns

Installation

go get github.com/coregx/opt

Requires Go 1.24+

Quick Start

package main

import (
    "encoding/json"
    "fmt"

    "github.com/coregx/opt"
)

func main() {
    // Create optional values
    name := opt.StringFrom("Alice")
    age := opt.NewInt(0, false) // null

    // Safe access with fallbacks
    fmt.Println(name.Or("unknown")) // "Alice"
    fmt.Println(age.Or(18))         // 18

    // JSON marshaling — just works
    type User struct {
        Name opt.String `json:"name"`
        Age  opt.Int    `json:"age"`
    }
    data, _ := json.Marshal(User{Name: name, Age: age})
    fmt.Println(string(data)) // {"name":"Alice","age":null}
}

API

Constructors

opt.From(value)          // Always valid: opt.From("hello"), opt.From(42)
opt.New(value, valid)    // Explicit: opt.New("", false) → null
opt.FromPtr(ptr)         // From pointer: nil → null, &v → valid
opt.OrNull(value)        // Zero value → null: opt.OrNull("") → null, opt.OrNull(42) → valid

// Type-specific shortcuts
opt.StringFrom("hello")      opt.StringOrNull("")     // "" → null
opt.IntFrom(42)              opt.IntOrNull(0)         // 0 → null
opt.FloatFrom(3.14)          opt.FloatOrNull(0.0)     // 0 → null
opt.BoolFrom(true)           opt.BoolOrNull(false)    // false → null
opt.TimeFrom(t)              opt.TimeOrNull(t)        // zero time → null
opt.ByteFrom(0x42)           opt.ByteOrNull(0)        // 0 → null

From = value is always valid. OrNull = zero value means "not set" → null. Choose based on your semantics.

Value Access

v.Or(fallback)           // Value or fallback
v.OrZero()               // Value or zero value of T
v.OrElse(func() T)       // Value or lazy-computed fallback
v.Ptr()                  // *T or nil
v.IsZero()               // true when null (for omitzero)

Functional

opt.Map(v, func(T) U) Option[U]              // Transform if valid
opt.FlatMap(v, func(T) Option[U]) Option[U]  // Chain optional operations
opt.Equal(a, b)                               // Nil-safe comparison

Three-State Field (PATCH API)

type PatchUser struct {
    Name  opt.Field[string] `json:"name,omitzero"`
    Email opt.Field[string] `json:"email,omitzero"`
}

// {}                    → Name.IsAbsent()=true  — don't touch
// {"name": null}        → Name.IsNull()=true    — set to NULL
// {"name": "Alice"}     → Name.IsValue()=true   — set to "Alice"

Zero Subpackage

import "github.com/coregx/opt/zero"

s := zero.StringFrom("")   // Invalid — empty string = null
i := zero.IntFrom(0)       // Invalid — zero = null
data, _ := json.Marshal(i) // "0" (not "null")
Behavior opt opt/zero
From("") Valid (empty string) Invalid (empty = null)
From(0) Valid (zero int) Invalid (zero = null)
Marshal null null "" / 0 / false

SQL Usage

// Works with database/sql
var user struct {
    Name opt.String
    Age  opt.Int
}
db.QueryRow("SELECT name, age FROM users WHERE id=$1", id).Scan(&user.Name, &user.Age)

// Also works with pgx, sqlx, and other drivers

Comparison with Alternatives

Feature opt guregu/null *T (pointer) sql.Null[T]
Generic Option[T] Full Partial (MarshalText commented out) N/A No JSON
Three-state (PATCH) Field[T] No No No
Map / FlatMap Yes No No No
OrElse (lazy) Yes No No No
JSON marshal Yes Yes Yes Broken ({"V":...,"Valid":...})
SQL Scanner/Valuer Yes Yes Yes Yes
omitzero Yes Yes No No
Zero-is-null variant zero/ zero/ No No
json/v2 compatible Yes Yes Yes No
Legacy code None v1→v6 N/A N/A

Benchmarks

BenchmarkBoolMarshalJSON     0.85 ns/op    0 allocs
BenchmarkBoolUnmarshalJSON   2.1 ns/op     0 allocs
BenchmarkIntMarshalJSON      48 ns/op      2 allocs
BenchmarkIntUnmarshalJSON    193 ns/op     1 alloc
BenchmarkStringUnmarshalJSON 137 ns/op     0 allocs
BenchmarkStructMarshalJSON   876 ns/op     9 allocs
BenchmarkStructUnmarshalJSON 1116 ns/op    2 allocs

Contributing

See CONTRIBUTING.md for guidelines.

License

MIT License — see LICENSE for details.

Documentation

Overview

Package opt provides optional types for Go — a Go-idiomatic Option<T> with full SQL, JSON, and Text serialization support.

opt distinguishes between null and zero values: opt.IntFrom(0) is valid, not null. Use OrNull constructors when zero values mean "not set": opt.StringOrNull("") is null. For full zero-is-null semantics (including JSON marshaling), use the opt/zero subpackage.

Core Types

Option[T] is the generic foundation. Concrete types (String, Int, Float, Bool, Time, Int32, Int16, Byte) provide optimized marshaling for common SQL/JSON types.

Field[T] adds three-state semantics (absent/null/value) for PATCH API support.

Functional API

Map, FlatMap, and Equal are top-level generic functions for transforming and comparing optional values.

SQL Integration

All types implement sql.Scanner and driver.Valuer through the embedded sql.Null[T], working seamlessly with database/sql, pgx, and other SQL drivers.

JSON Integration

All types marshal to their value when valid and to null when invalid. Unmarshal accepts null JSON values. Int and Float also accept string-encoded numbers. Use the omitzero struct tag to omit null fields from JSON output.

Package opt provides optional types for Go — a Go-idiomatic Option<T> with full SQL, JSON, and Text serialization support.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Equal

func Equal[T comparable](a, b Option[T]) bool

Equal compares two Options for equality. Both must be null, or both valid with equal inner values.

Types

type Bool

type Bool struct {
	Option[bool]
}

Bool is a nullable bool with optimized JSON and Text marshaling.

func BoolFrom

func BoolFrom(b bool) Bool

BoolFrom creates a Bool that is always valid.

func BoolFromPtr

func BoolFromPtr(b *bool) Bool

BoolFromPtr creates a Bool from a pointer. Nil results in null.

func BoolOrNull added in v0.2.0

func BoolOrNull(b bool) Bool

BoolOrNull creates a valid Bool if b is true, null if false. Use BoolFrom(false) when false is an explicit value, not absence.

func NewBool

func NewBool(b bool, valid bool) Bool

NewBool creates a Bool with the given value and validity.

func (Bool) Equal

func (b Bool) Equal(other Bool) bool

Equal reports whether two Bools are equal.

func (Bool) MarshalJSON

func (b Bool) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Bool) MarshalText

func (b Bool) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Bool) UnmarshalJSON

func (b *Bool) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Bool) UnmarshalText

func (b *Bool) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Byte

type Byte struct {
	Option[byte]
}

Byte is a nullable byte (uint8) with JSON marshaling.

func ByteFrom

func ByteFrom(b byte) Byte

ByteFrom creates a Byte that is always valid.

func ByteFromPtr

func ByteFromPtr(b *byte) Byte

ByteFromPtr creates a Byte from a pointer. Nil results in null.

func ByteOrNull added in v0.2.0

func ByteOrNull(b byte) Byte

ByteOrNull creates a valid Byte if b is non-zero, null otherwise.

func NewByte

func NewByte(b byte, valid bool) Byte

NewByte creates a Byte with the given value and validity.

func (Byte) Equal

func (b Byte) Equal(other Byte) bool

Equal reports whether two Bytes are equal.

func (Byte) MarshalJSON

func (b Byte) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Byte) MarshalText

func (b Byte) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Byte) UnmarshalJSON

func (b *Byte) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Byte) UnmarshalText

func (b *Byte) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Field

type Field[T any] struct {
	V       T
	Present bool
	Valid   bool
}

Field is a three-state nullable type for PATCH API semantics.

Three states:

  • Absent: Present=false, Valid=false → field was not in JSON ("don't touch")
  • Null: Present=true, Valid=false → field was explicitly null ("set to NULL")
  • Value: Present=true, Valid=true → field has a value ("set to value")

The zero value of Field is the Absent state, which is safe by default. When encoding/json encounters a missing field, UnmarshalJSON is never called, so Present stays false — distinguishing "absent" from "null".

Example (PatchAPI)
package main

import (
	"encoding/json"
	"fmt"

	"github.com/coregx/opt"
)

func main() {
	type PatchUser struct {
		Name  opt.Field[string] `json:"name,omitzero"`
		Email opt.Field[string] `json:"email,omitzero"`
		Age   opt.Field[int]    `json:"age,omitzero"`
	}

	input := `{"name":"John","email":null}`
	var patch PatchUser
	json.Unmarshal([]byte(input), &patch)

	fmt.Println("name absent:", patch.Name.IsAbsent())
	fmt.Println("name value:", patch.Name.Or(""))
	fmt.Println("email null:", patch.Email.IsNull())
	fmt.Println("age absent:", patch.Age.IsAbsent())
}
Output:
name absent: false
name value: John
email null: true
age absent: true

func FieldFrom

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

FieldFrom creates a present, valid Field.

func FieldFromOption added in v0.3.0

func FieldFromOption[T any](v Option[T]) Field[T]

FieldFromOption creates a present Field from an Option (lossless upcast). Valid Option becomes a present+valid Field. Invalid Option becomes a present+null Field (not absent).

func FieldNull

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

FieldNull creates a present but null Field ("set to NULL").

func NewField

func NewField[T any](v T, present, valid bool) Field[T]

NewField creates a Field with all three components.

func (Field[T]) IsAbsent

func (f Field[T]) IsAbsent() bool

IsAbsent returns true if the field was not present in the input.

func (Field[T]) IsNull

func (f Field[T]) IsNull() bool

IsNull returns true if the field was present but null.

func (Field[T]) IsValue

func (f Field[T]) IsValue() bool

IsValue returns true if the field is present and has a value.

func (Field[T]) IsZero

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

IsZero supports omitzero: absent fields are omitted from JSON output.

func (Field[T]) MarshalJSON

func (f Field[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. Absent fields should be omitted via `json:",omitzero"` tag, not marshaled. If marshaled explicitly: null when invalid, value when valid.

func (Field[T]) Or

func (f Field[T]) Or(fallback T) T

Or returns the value if present and valid, otherwise the fallback.

func (Field[T]) OrZero

func (f Field[T]) OrZero() T

OrZero returns the value if valid, otherwise the zero value.

func (Field[T]) Ptr

func (f Field[T]) Ptr() *T

Ptr returns a pointer to the value, or nil if absent or null.

func (Field[T]) ToOption added in v0.3.0

func (f Field[T]) ToOption() Option[T]

ToOption converts Field to Option, collapsing absent and null into invalid.

func (*Field[T]) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler. Called only when the field IS present in JSON — so we set Present=true.

type Float

type Float struct {
	Option[float64]
}

Float is a nullable float64 with optimized JSON marshaling. It rejects Inf and NaN during JSON serialization.

func FloatFrom

func FloatFrom(f float64) Float

FloatFrom creates a Float that is always valid.

func FloatFromPtr

func FloatFromPtr(f *float64) Float

FloatFromPtr creates a Float from a pointer. Nil results in null.

func FloatOrNull added in v0.2.0

func FloatOrNull(f float64) Float

FloatOrNull creates a valid Float if f is non-zero, null otherwise.

func NewFloat

func NewFloat(f float64, valid bool) Float

NewFloat creates a Float with the given value and validity.

func (Float) Equal

func (f Float) Equal(other Float) bool

Equal reports whether two Floats are equal.

func (Float) MarshalJSON

func (f Float) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. Rejects Inf and NaN.

func (Float) MarshalText

func (f Float) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Float) UnmarshalJSON

func (f *Float) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Float) UnmarshalText

func (f *Float) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Int

type Int struct {
	Option[int64]
}

Int is a nullable int64 with optimized JSON marshaling. It accepts both numbers and string-encoded numbers in JSON.

func IntFrom

func IntFrom(i int64) Int

IntFrom creates an Int that is always valid.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/coregx/opt"
)

func main() {
	i := opt.IntFrom(42)
	data, _ := json.Marshal(i)
	fmt.Println(string(data))
	fmt.Println(i.OrZero())

	zero := opt.IntFrom(0)
	fmt.Println(zero.IsZero()) // false — 0 is valid, not null
}
Output:
42
42
false

func IntFromPtr

func IntFromPtr(i *int64) Int

IntFromPtr creates an Int from a pointer. Nil results in null.

func IntOrNull added in v0.2.0

func IntOrNull(n int64) Int

IntOrNull creates a valid Int if n is non-zero, null otherwise.

func NewInt

func NewInt(i int64, valid bool) Int

NewInt creates an Int with the given value and validity.

func (Int) Equal

func (i Int) Equal(other Int) bool

Equal reports whether two Ints are equal.

func (Int) MarshalJSON

func (i Int) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Int) MarshalText

func (i Int) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Int) UnmarshalJSON

func (i *Int) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Int) UnmarshalText

func (i *Int) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Int16

type Int16 struct {
	Option[int16]
}

Int16 is a nullable int16 with optimized JSON marshaling.

func Int16From

func Int16From(i int16) Int16

Int16From creates an Int16 that is always valid.

func Int16FromPtr

func Int16FromPtr(i *int16) Int16

Int16FromPtr creates an Int16 from a pointer. Nil results in null.

func Int16OrNull added in v0.2.0

func Int16OrNull(n int16) Int16

Int16OrNull creates a valid Int16 if n is non-zero, null otherwise.

func NewInt16

func NewInt16(i int16, valid bool) Int16

NewInt16 creates an Int16 with the given value and validity.

func (Int16) Equal

func (i Int16) Equal(other Int16) bool

Equal reports whether two Int16s are equal.

func (Int16) MarshalJSON

func (i Int16) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Int16) MarshalText

func (i Int16) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Int16) UnmarshalJSON

func (i *Int16) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Int16) UnmarshalText

func (i *Int16) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Int32

type Int32 struct {
	Option[int32]
}

Int32 is a nullable int32 with optimized JSON marshaling.

func Int32From

func Int32From(i int32) Int32

Int32From creates an Int32 that is always valid.

func Int32FromPtr

func Int32FromPtr(i *int32) Int32

Int32FromPtr creates an Int32 from a pointer. Nil results in null.

func Int32OrNull added in v0.2.0

func Int32OrNull(n int32) Int32

Int32OrNull creates a valid Int32 if n is non-zero, null otherwise.

func NewInt32

func NewInt32(i int32, valid bool) Int32

NewInt32 creates an Int32 with the given value and validity.

func (Int32) Equal

func (i Int32) Equal(other Int32) bool

Equal reports whether two Int32s are equal.

func (Int32) MarshalJSON

func (i Int32) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Int32) MarshalText

func (i Int32) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Int32) UnmarshalJSON

func (i *Int32) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Int32) UnmarshalText

func (i *Int32) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Option added in v0.3.0

type Option[T any] struct {
	sql.Null[T]
}

Option is a generic nullable type backed by sql.Null[T]. It marshals to JSON null when invalid and to the value when valid. For SQL, it inherits Scanner and Valuer from sql.Null[T].

Example (StructJSON)
package main

import (
	"encoding/json"
	"fmt"

	"github.com/coregx/opt"
)

func main() {
	type User struct {
		Name  opt.String `json:"name"`
		Age   opt.Int    `json:"age"`
		Score opt.Float  `json:"score,omitzero"`
	}

	user := User{
		Name: opt.StringFrom("Alice"),
		Age:  opt.NewInt(0, false),
	}

	data, _ := json.Marshal(user)
	fmt.Println(string(data))
}
Output:
{"name":"Alice","age":null}

func FlatMap

func FlatMap[T, U any](v Option[T], fn func(T) Option[U]) Option[U]

FlatMap transforms the inner value with a function that itself returns an Option. Enables chaining of operations that may produce null.

func From

func From[T any](v T) Option[T]

From creates an Option that is always valid.

func FromPtr

func FromPtr[T any](ptr *T) Option[T]

FromPtr creates an Option from a pointer. Nil pointer results in a null Option.

func Map

func Map[T, U any](v Option[T], fn func(T) U) Option[U]

Map transforms the inner value if valid, returning a new Option. If the source is null, returns a null Option of the target type.

Example
package main

import (
	"fmt"

	"github.com/coregx/opt"
)

func main() {
	name := opt.From("John")
	length := opt.Map(name, func(s string) int { return len(s) })
	fmt.Println(length.OrZero())

	null := opt.New("", false)
	result := opt.Map(null, func(s string) int { return len(s) })
	fmt.Println(result.IsZero())
}
Output:
4
true

func New

func New[T any](v T, valid bool) Option[T]

New creates an Option with the given value and validity.

func OrNull added in v0.2.0

func OrNull[T comparable](v T) Option[T]

OrNull creates a valid Option if v is non-zero, null otherwise. Use From(v) when the zero value is meaningful, OrNull(v) when it means "not set".

Example
package main

import (
	"fmt"

	"github.com/coregx/opt"
)

func main() {
	i := opt.OrNull(42)
	fmt.Println(i.OrZero()) // 42

	z := opt.OrNull(0)
	fmt.Println(z.IsZero()) // true — 0 means "not set"

	s := opt.OrNull("hello")
	fmt.Println(s.Or("default")) // hello
}
Output:
42
true
hello

func (Option[T]) IsZero added in v0.3.0

func (v Option[T]) IsZero() bool

IsZero returns true when the Option is null. Supports Go 1.24+ omitzero.

func (Option[T]) MarshalJSON added in v0.3.0

func (v Option[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. Encodes null when invalid.

func (Option[T]) Or added in v0.3.0

func (v Option[T]) Or(fallback T) T

Or returns the inner value if valid, otherwise the fallback.

func (Option[T]) OrElse added in v0.3.0

func (v Option[T]) OrElse(fn func() T) T

OrElse returns the inner value if valid, otherwise calls fn and returns its result.

func (Option[T]) OrZero added in v0.3.0

func (v Option[T]) OrZero() T

OrZero returns the inner value if valid, otherwise the zero value of T.

func (Option[T]) Ptr added in v0.3.0

func (v Option[T]) Ptr() *T

Ptr returns a pointer to the value, or nil if null.

func (*Option[T]) SetValid added in v0.3.0

func (v *Option[T]) SetValid(val T)

SetValid sets the value and marks it as valid.

func (*Option[T]) UnmarshalJSON added in v0.3.0

func (v *Option[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type String

type String struct {
	Option[string]
}

String is a nullable string with optimized JSON and Text marshaling.

func NewString

func NewString(s string, valid bool) String

NewString creates a String with the given value and validity.

func StringFrom

func StringFrom(s string) String

StringFrom creates a String that is always valid.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/coregx/opt"
)

func main() {
	s := opt.StringFrom("hello")
	data, _ := json.Marshal(s)
	fmt.Println(string(data))
	fmt.Println(s.Or("default"))

	null := opt.NewString("", false)
	data, _ = json.Marshal(null)
	fmt.Println(string(data))
	fmt.Println(null.Or("default"))
}
Output:
"hello"
hello
null
default

func StringFromPtr

func StringFromPtr(s *string) String

StringFromPtr creates a String from a pointer. Nil results in null.

func StringOrNull added in v0.2.0

func StringOrNull(s string) String

StringOrNull creates a valid String if s is non-empty, null otherwise. Use StringFrom(s) when empty string is a meaningful value.

Example
package main

import (
	"fmt"

	"github.com/coregx/opt"
)

func main() {
	valid := opt.StringOrNull("Moscow")
	fmt.Println(valid.Or("unknown"))

	null := opt.StringOrNull("")
	fmt.Println(null.Or("unknown"))
	fmt.Println(null.IsZero())
}
Output:
Moscow
unknown
true

func (String) Equal

func (s String) Equal(other String) bool

Equal reports whether two Strings are equal (both null, or same value).

func (String) MarshalJSON

func (s String) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (String) MarshalText

func (s String) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*String) UnmarshalJSON

func (s *String) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*String) UnmarshalText

func (s *String) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Time

type Time struct {
	Option[time.Time]
}

Time is a nullable time.Time with RFC3339 JSON marshaling.

func NewTime

func NewTime(t time.Time, valid bool) Time

NewTime creates a Time with the given value and validity.

func TimeFrom

func TimeFrom(t time.Time) Time

TimeFrom creates a Time that is always valid.

func TimeFromPtr

func TimeFromPtr(t *time.Time) Time

TimeFromPtr creates a Time from a pointer. Nil results in null.

func TimeOrNull added in v0.2.0

func TimeOrNull(t time.Time) Time

TimeOrNull creates a valid Time if t is non-zero, null otherwise.

func (Time) Equal

func (t Time) Equal(other Time) bool

Equal reports whether two Times represent the same instant (timezone-independent).

func (Time) ExactEqual

func (t Time) ExactEqual(other Time) bool

ExactEqual reports whether two Times are exactly equal (including timezone).

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Time) MarshalText

func (t Time) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Time) UnmarshalText

func (t *Time) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

Directories

Path Synopsis
Package internal provides shared marshal/unmarshal helpers for opt and opt/zero packages.
Package internal provides shared marshal/unmarshal helpers for opt and opt/zero packages.
Package zero provides nullable types where zero values are treated as null.
Package zero provides nullable types where zero values are treated as null.

Jump to

Keyboard shortcuts

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