value
Conditional value selection without branching.
// Before: five lines to assign one value
var color string
if critical {
color = warn
} else {
color = calm
}
// After
color := value.Of(warn).When(critical).Or(calm)
Five lines become one.
What It Looks Like
Struct Returns
Go struct literals let you build and return a value in one statement — value.Of keeps it that way when fields are conditional:
// Before: pre-compute each field, then assemble
var level string
if overdue {
level = "critical"
} else {
level = "info"
}
var icon string
if overdue {
icon = "!"
} else {
icon = "✓"
}
return Alert{Message: msg, Level: level, Icon: icon}
// After: every field resolves inline
return Alert{
Message: msg,
Level: value.Of("critical").When(overdue).Or("info"),
Icon: value.Of("!").When(overdue).Or("✓"),
}
Defaults with Validation
timeout := value.Of(requested).When(requested > 0).Or(defaultTimeout)
Lazy Evaluation
// expensiveDefault is only called when the cache misses
result := value.OfCall(expensiveDefault).When(!cache.Hit()).Or(cache.Value())
OfCall wraps a func() T and only evaluates it if the condition is true. Use it when the conditional value is expensive to compute.
First Non-Zero (Coalesce)
// Config merge: use override if set, otherwise keep default
result.Region = value.Coalesce(override.Region, defaults.Region)
// Multi-level fallback
host := value.Coalesce(envHost, configHost, "localhost")
Coalesce returns the first non-zero value from its arguments, or zero if all are zero. It requires comparable (same constraint as slice.Compact). Use it when the condition is "non-zero" and you don't need the option intermediary.
Composition
.Or() isn't part of value — it comes from option.Basic[T]. The chain works because .When() returns an option:
value.Of(v) → Cond[T]
.When(c) → option.Basic[T] // Ok(v) if true, NotOk if false
.Or(fb) → T // resolve with fallback
value creates the condition. option resolves it. The packages compose.
When to Use value vs option
|
value |
option |
| Intent |
Select between values |
Handle a potentially absent value |
| Trigger |
Explicit condition or zero-value check |
Value's own existence/validity |
| Pattern |
A or B (condition) / first non-zero (coalesce) |
A or nothing |
// value: both alternatives are known
color := value.Of(warn).When(critical).Or(calm)
// option: the value might not exist
port := option.Getenv("PORT").Or("8080")
Operations
Cond[T] holds a value pending a condition check. LazyCond[T] holds a function for deferred computation.
Of(T) Cond[T] — wrap a value
Cond[T].When(bool) option.Basic[T] — ok if true, not-ok if false
OfCall(func() T) LazyCond[T] — wrap a function (lazy)
LazyCond[T].When(bool) option.Basic[T] — evaluate only if true
Coalesce[T comparable](vals ...T) T — first non-zero value
See pkg.go.dev for complete API documentation, the main README for installation, and option for absent values without conditions.