IfLazy
Overview
IfLazy evaluates a or b lazily via thunks (Node: cond ? a() : b()).
If you are coming from Node.js, the closest pattern is cond ? f() : g().
Signature
go
func IfLazy[T any](cond bool, a, b func() T) TCompare: Node.js · Standard Go · gox
js
const v = cond ? expensive() : fallback();go
var v T
if cond {
v = expensive()
} else {
v = fallback()
}go
import "github.com/sahilkhaire/gox/cond"
called := 0
got := IfLazy(false, func() int { called++; return 1 }, func() int { return 2 })
got = IfLazy(true, func() int { return 3 }, func() int { called++; return 4 })Example
go
import "github.com/sahilkhaire/gox/cond"
called := 0
got := IfLazy(false, func() int { called++; return 1 }, func() int { return 2 })
got = IfLazy(true, func() int { return 3 }, func() int { called++; return 4 })Tips
Import github.com/sahilkhaire/gox/cond and call IfLazy directly. See the comparison below for the standard library equivalent.
Standard library alternative
Use the standard library directly:
go
var v T
if cond {
v = expensive()
} else {
v = fallback()
}