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 ¶
- func Equal[T comparable](a, b Option[T]) bool
- type Bool
- type Byte
- type Field
- func (f Field[T]) IsAbsent() bool
- func (f Field[T]) IsNull() bool
- func (f Field[T]) IsValue() bool
- func (f Field[T]) IsZero() bool
- func (f Field[T]) MarshalJSON() ([]byte, error)
- func (f Field[T]) Or(fallback T) T
- func (f Field[T]) OrZero() T
- func (f Field[T]) Ptr() *T
- func (f Field[T]) ToOption() Option[T]
- func (f *Field[T]) UnmarshalJSON(data []byte) error
- type Float
- type Int
- type Int16
- type Int32
- type Option
- func (v Option[T]) IsZero() bool
- func (v Option[T]) MarshalJSON() ([]byte, error)
- func (v Option[T]) Or(fallback T) T
- func (v Option[T]) OrElse(fn func() T) T
- func (v Option[T]) OrZero() T
- func (v Option[T]) Ptr() *T
- func (v *Option[T]) SetValid(val T)
- func (v *Option[T]) UnmarshalJSON(data []byte) error
- type String
- type Time
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 ¶
Bool is a nullable bool with optimized JSON and Text marshaling.
func BoolFromPtr ¶
BoolFromPtr creates a Bool from a pointer. Nil results in null.
func BoolOrNull ¶ added in v0.2.0
BoolOrNull creates a valid Bool if b is true, null if false. Use BoolFrom(false) when false is an explicit value, not absence.
func (Bool) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Bool) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Bool) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Bool) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Byte ¶
Byte is a nullable byte (uint8) with JSON marshaling.
func ByteFromPtr ¶
ByteFromPtr creates a Byte from a pointer. Nil results in null.
func ByteOrNull ¶ added in v0.2.0
ByteOrNull creates a valid Byte if b is non-zero, null otherwise.
func (Byte) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Byte) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Byte) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Byte) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Field ¶
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 FieldFromOption ¶ added in v0.3.0
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 (Field[T]) MarshalJSON ¶
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
ToOption converts Field to Option, collapsing absent and null into invalid.
func (*Field[T]) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. Called only when the field IS present in JSON — so we set Present=true.
type Float ¶
Float is a nullable float64 with optimized JSON marshaling. It rejects Inf and NaN during JSON serialization.
func FloatFromPtr ¶
FloatFromPtr creates a Float from a pointer. Nil results in null.
func FloatOrNull ¶ added in v0.2.0
FloatOrNull creates a valid Float if f is non-zero, null otherwise.
func (Float) MarshalJSON ¶
MarshalJSON implements json.Marshaler. Rejects Inf and NaN.
func (Float) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Float) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Float) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Int ¶
Int is a nullable int64 with optimized JSON marshaling. It accepts both numbers and string-encoded numbers in JSON.
func IntFrom ¶
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 ¶
IntFromPtr creates an Int from a pointer. Nil results in null.
func (Int) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Int) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Int) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Int) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Int16 ¶
Int16 is a nullable int16 with optimized JSON marshaling.
func Int16FromPtr ¶
Int16FromPtr creates an Int16 from a pointer. Nil results in null.
func Int16OrNull ¶ added in v0.2.0
Int16OrNull creates a valid Int16 if n is non-zero, null otherwise.
func (Int16) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Int16) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Int16) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Int16) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Int32 ¶
Int32 is a nullable int32 with optimized JSON marshaling.
func Int32FromPtr ¶
Int32FromPtr creates an Int32 from a pointer. Nil results in null.
func Int32OrNull ¶ added in v0.2.0
Int32OrNull creates a valid Int32 if n is non-zero, null otherwise.
func (Int32) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Int32) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Int32) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Int32) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Option ¶ added in v0.3.0
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 ¶
FlatMap transforms the inner value with a function that itself returns an Option. Enables chaining of operations that may produce null.
func Map ¶
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 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
IsZero returns true when the Option is null. Supports Go 1.24+ omitzero.
func (Option[T]) MarshalJSON ¶ added in v0.3.0
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
UnmarshalJSON implements json.Unmarshaler.
type String ¶
String is a nullable string with optimized JSON and Text marshaling.
func StringFrom ¶
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 ¶
StringFromPtr creates a String from a pointer. Nil results in null.
func StringOrNull ¶ added in v0.2.0
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) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (String) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*String) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*String) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Time ¶
Time is a nullable time.Time with RFC3339 JSON marshaling.
func TimeFromPtr ¶
TimeFromPtr creates a Time from a pointer. Nil results in null.
func TimeOrNull ¶ added in v0.2.0
TimeOrNull creates a valid Time if t is non-zero, null otherwise.
func (Time) Equal ¶
Equal reports whether two Times represent the same instant (timezone-independent).
func (Time) ExactEqual ¶
ExactEqual reports whether two Times are exactly equal (including timezone).
func (Time) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Time) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Time) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Time) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
Source Files
¶
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. |