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 ¶
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 ¶
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 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 ¶
Click to show internal directories.
Click to hide internal directories.