The ternary
package provides utilities to write ternary operations in Go. It includes both strict and lazy evaluation of ternary expressions, allowing for more concise and functional programming.
-
ternary.Op[T any](cond bool, trueVal, falseVal T) T
:
Evaluates a ternary operation based on the conditioncond
. ReturnstrueVal
ifcond
istrue
, otherwise returnsfalseVal
. Type inference is utilized here.result := ternary.Op[int](5 > 3, 10, 20) // result will be 10 result = ternary.Op(5 > 3, 10, 20) // type inference will infer the type of result to be int
-
ternary.LazyOp[T any](cond bool, trueVal, falseVal func() T) T
:
Similar toOp
, but evaluates thetrueVal
andfalseVal
lazily by accepting them as functions. This avoids unnecessary computations. Can be useful for nil checks or expensive operations.var err error result1 := ternary.LazyOp[string](err != nil, func() int { return "not nil" }, func() int { return "nil" }) // result will be "nil" result2 := ternary.LazyOp(5 > 3, func() int { return 10 }, func() int { return 20 }) // type inference will infer the type of result to be int
You can also use it to avoid nil pointer dereferences:
type Foo struct { Bar string } var foo *Foo result := ternary.LazyOp[string](foo != nil, func() string { return foo.Bar }, func() string { return "nil" }) // result will be "nil"
-
ternary.TernaryIf[T any]
:
Represents the conditional part of a ternary expression. -
ternary.TernaryThen[T any]
:
Represents the true value of a ternary expression. -
ternary.LazyTernaryThen[T any]
:
Represents the true value of a ternary expression with lazy evaluation.
-
ternary.If[T any](cond bool) *TernaryIf[T]
:
Begins a ternary expression by evaluating a condition.ternary.If[int](5 > 3).Then(10).Else(20) // returns 10
-
Then(trueVal T) *TernaryThen[T]
:
Specifies the true value of a ternary expression. -
Else(falseVal T) T
:
Specifies the false value of a ternary expression and completes it.ternary.If[int](5 < 3).Then(10).Else(20) // returns 20
-
LThen(trueVal func() T) *LazyTernaryThen[T]
:
Specifies the true value of a ternary expression with lazy evaluation. -
LElse(falseVal func() T) T
:
Specifies the false value of a ternary expression with lazy evaluation and completes it.ternary.If[int](5 > 3).LThen(func() int { return 10 }).LElse(func() int { return 20 }) // returns 10
For longer ternary statements, the ternary methods can be nested:
var bar string = ternary.If[string](false).
Then("foo").
Else(ternary.If[string](true).
Then("bar").
Else("baz"),
)
The ternary
package provides a convenient way to write and evaluate ternary expressions in Go. By supporting both strict and lazy evaluation and allowing for nesting, it enables developers to write more concise and expressive code. Type inference in the Op
method further enhances readability.