cond

package
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2025 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package cond provides generic, ternary-like conditional functions.

This package offers a concise way to express simple conditional logic in a single expression, avoiding the need for a more verbose if-else block. It provides functions for both eagerly-evaluated values (If) and lazily-evaluated functions (IfFunc).

Usage

## Eager Evaluation with `If`

The `If` function is a direct replacement for a simple ternary operation. Both the `trueVal` and `falseVal` are evaluated before the function is called.

// Determine a status message based on an error.
func GetStatusMessage(err error) string {
	return cond.If(err == nil, "Status: OK", "Status: Failed")
}

// Assign a value based on a boolean condition.
isLoggedIn := true
buttonText := cond.If(isLoggedIn, "Logout", "Login")

## Lazy Evaluation with `IfFunc`

The `IfFunc` function accepts functions that are only executed when needed. This is useful when the values to be returned involve expensive computations.

// The expensive functions are only called when the condition is met.
func calculateResult(isComplex bool) int {
	return cond.IfFunc(isComplex, doComplexCalculation, doSimpleCalculation)
}

func doComplexCalculation() int {
	// Simulate a time-consuming operation.
	time.Sleep(1 * time.Second)
	return 100
}

func doSimpleCalculation() int {
	return 1
}

Choose `If` for simple values and `IfFunc` to optimize performance when dealing with computationally intensive branches.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func If

func If[T any](condition bool, trueVal T, falseVal T) T

If returns trueVal if the condition is true, and falseVal otherwise. This is a generic, eagerly-evaluated ternary-like expression. Both trueVal and falseVal are evaluated before this function is called.

For lazy evaluation where values are expensive to compute, see IfFunc.

func IfFunc

func IfFunc[T any](condition bool, trueFn func() T, falseFn func() T) T

IfFunc returns the result of trueFn if the condition is true, and the result of falseFn otherwise. This is a generic, lazily-evaluated ternary-like expression. Only the function corresponding to the condition's outcome is executed.

func IfFuncE

func IfFuncE[T any](condition bool, trueFn func() (T, error), falseFn func() (T, error)) (T, error)

IfFuncE returns the result of trueFn if the condition is true, and the result of falseFn otherwise. It is the error-returning version of IfFunc. This is a generic, lazily-evaluated ternary-like expression. Only the function corresponding to the condition's outcome is executed.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL