diff --git a/condition.go b/condition.go index 01197aa..e0181be 100644 --- a/condition.go +++ b/condition.go @@ -14,11 +14,19 @@ package ekit -// IfThenElse 根据条件返回对应的泛型结果,请注意,结果值在传入时就会访问,请务必确认其合法性 -// 例:传 trueValue 时传入了一个指针对象并调用其方法,需要先判空 +// IfThenElse 根据条件返回对应的泛型结果 +// 注意避免结果的空指针问题 func IfThenElse[T any](condition bool, trueValue, falseValue T) T { if condition { return trueValue } return falseValue } + +// IfThenElseFunc 根据条件执行对应的函数并返回泛型结果 +func IfThenElseFunc[T any](condition bool, trueFunc, falseFunc func() T) T { + if condition { + return trueFunc() + } + return falseFunc() +} diff --git a/condition_test.go b/condition_test.go index 71a4f07..7df6ab3 100644 --- a/condition_test.go +++ b/condition_test.go @@ -15,6 +15,8 @@ package ekit import ( + "errors" + "fmt" "testing" "github.com/stretchr/testify/assert" @@ -25,3 +27,36 @@ func TestIfThenElse(t *testing.T) { i = IfThenElse(false, i, 0) assert.Equal(t, i, 0) } + +func ExampleIfThenElse() { + result := IfThenElse(true, "yes", "no") + fmt.Println(result) + + // Output: + // yes +} + +func TestIfThenElseFunc(t *testing.T) { + err := IfThenElseFunc(true, func() error { + return nil + }, func() error { + return errors.New("some error") + }) + assert.NoError(t, err) +} + +func ExampleIfThenElseFunc() { + err := IfThenElseFunc(false, func() error { + // do something when condition is true + // ... + return nil + }, func() error { + // do something when condition is false + // ... + return errors.New("some error when execute func2") + }) + fmt.Println(err) + + // Output: + // some error when execute func2 +}