Skip to content
Node: cond ? a : bgithub.com/sahilkhaire/gox/cond

If

Overview

Returns a when cond is true, otherwise b. The closest equivalent to JavaScript's ternary operator — both branches must be the same type in Go.

If you are coming from Node.js, the closest pattern is cond ? a : b.

Signature

go
func If[T any](cond bool, a, b T) T

Compare: Node.js · Standard Go · gox

js
const label = age >= 18 ? 'adult' : 'minor';
go
label := "minor"
if age >= 18 {
    label = "adult"
}
go
import "github.com/sahilkhaire/gox/cond"

adult := cond.If(age >= 18, "adult", "minor")

Example

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

adult := cond.If(age >= 18, "adult", "minor")

Tips

Both branches are evaluated eagerly. Use cond.IfLazy when one branch is expensive and should be skipped.

Standard library alternative

Use the standard library directly:

go
label := "minor"
if age >= 18 {
    label = "adult"
}

Back to cond package overview

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