Coalesce
Overview
Coalesce returns the first value that is not the zero value (Node: a ?? b ?? c).
If you are coming from Node.js, the closest pattern is a ?? b ?? c.
Signature
go
func Coalesce[T comparable](vals ...T) TCompare: Node.js · Standard Go · gox
js
const name = maybeName ?? 'guest';go
name := maybeName
if name == "" {
name = "guest"
}go
import "github.com/sahilkhaire/gox/cond"
tests := []struct {
in []int
want int
}{
{[]int{0, 0, 3}, 3},
{[]int{1, 2}, 1},
{[]int{}, 0},
}Example
go
import "github.com/sahilkhaire/gox/cond"
tests := []struct {
in []int
want int
}{
{[]int{0, 0, 3}, 3},
{[]int{1, 2}, 1},
{[]int{}, 0},
}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
name := maybeName
if name == "" {
name = "guest"
}