Skip to content
Node: obj?.field ?? "guest"github.com/sahilkhaire/gox/cond

CoalesceFn

Overview

CoalesceFn returns the first non-zero result from the given functions, in order.

If you are coming from Node.js, the closest pattern is obj?.field ?? "guest".

Signature

go
func CoalesceFn[T comparable](fns ...func() T) T

Compare: Node.js · Standard Go · gox

js
obj?.field ?? "guest"
go
result := fallback
if v != zero {
    result = v
}
go
import "github.com/sahilkhaire/gox/cond"

cond.CoalesceFn(ptr, func(v T) R { ... }, fallback)

Example

go
import "github.com/sahilkhaire/gox/cond"

cond.CoalesceFn(ptr, func(v T) R { ... }, fallback)

Tips

Prefer explicit zero-value checks in performance-critical hot paths if the compiler cannot prove types.

Standard library alternative

Use the standard library directly:

go
result := fallback
if v != zero {
    result = v
}

Back to cond package overview

MIT Licensed · Built for Node.js developers moving to Go