gcond

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 29, 2025 License: Apache-2.0 Imports: 0 Imported by: 9

Documentation

Overview

Package gcond helps users choose values according to various conditions in one line.

Example
fmt.Println(If(true, 1, 2)) // 1
var a *struct{ A int }
getA := func() int { return a.A }
get1 := func() int { return 1 }
fmt.Println(IfLazy(a != nil, getA, get1)) // 1
fmt.Println(IfLazyL(a != nil, getA, 1))   // 1
fmt.Println(IfLazyR(a == nil, 1, getA))   // 1

fmt.Println(Switch[string](3).
	Case(1, "1").
	CaseLazy(2, func() string { return "3" }).
	When(3, 4).Then("3/4").
	When(5, 6).ThenLazy(func() string { return "5/6" }).
	Default("other")) // 3/4
Output:

1
1
1
1
3/4

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func If

func If[T any](cond bool, onTrue, onFalse T) T

If returns onTrue when cond is true, otherwise returns onFalse. It is used as a replacement of ternary conditional operator (:?) in many other programming languages.

⚠️ WARNING: onTrue and onFalse always be evaluated regardless of the truth of cond. Use IfLazy, IfLazyL, and IfLazyR if you need lazy evaluation.

🚀 EXAMPLE:

If(true, 1, 2)                       ⏩ 1
If(false, 1, 2)                      ⏩ 2
If(p != nil, p.foo, nil)             ⏩ ❌PANIC❌
If(true, 1, default())               ⏩ 1 // ⚠️ but func default is always evaluated

func IfLazy

func IfLazy[T any](cond bool, onTrue, onFalse Lazy[T]) T

IfLazy is a variant of If, accepts Lazy values.

🚀 EXAMPLE:

v1 := func() int {return 1}
v2 := func() int {return 2}
vp := func () int { panic("") }
IfLazy(true, v1, v2)   ⏩ 1
IfLazy(false, v1, v2)  ⏩ 2
IfLazy(true, v1, vp)   ⏩ 1 // won't panic
IfLazy(false, vp, v2)  ⏩ 2 // won't panic

func IfLazyL

func IfLazyL[T any](cond bool, onTrue Lazy[T], onFalse T) T

IfLazyL is a variant of If, accepts Lazy onTrue value.

func IfLazyR

func IfLazyR[T any](cond bool, onTrue T, onFalse Lazy[T]) T

IfLazyR is a variant of If, accepts Lazy onFalse value.

func Switch

func Switch[R any, T comparable](variable T) *switchBuilder[R, T]

Switch initiates a new switchBuilder with the given variable. It is used as a more flexible alternative to the built-in switch statement.

🚀 EXAMPLE:

Switch[string](1).Case(1, "One").Default("Other")	⏩ "One"
Switch[string](2).Case(1, "One").Default("Other")	⏩ "Other"

Types

type Lazy

type Lazy[T any] func() T

Lazy is a value type that evaluates only when needed.

Jump to

Keyboard shortcuts

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