A simple Go package that provides a generic ternary operator function.
go get github.com/4n4k1n/ternaryimport "github.com/4n4k1n/ternary"
// Basic usage
result := ternary.If(4 > 5, "yes", "no") // returns "no"
// With numbers
max := ternary.If(a > b, a, b) // Get maximum of two values
// With strings
status := ternary.If(isActive, "active", "inactive")
// Complex conditions
msg := ternary.If(age >= 18 && hasLicense, "can drive", "cannot drive")func If[T any](condition bool, trueVal, falseVal T) T- condition: Any boolean expression
- trueVal: Value to return if condition is true
- falseVal: Value to return if condition is false
- Returns: Either trueVal or falseVal depending on the condition
The function uses Go generics, so it works with any type as long as both return values are the same type.
Go doesn't have a built-in ternary operator like condition ? trueVal : falseVal in other languages. This package provides a clean, reusable way to write simple conditional expressions without verbose if-else blocks.
MIT