Skip to content

Commit

Permalink
IfThenElseFunc固定增加错误返回,泛型T作为用户可以自定义返回的结果
Browse files Browse the repository at this point in the history
  • Loading branch information
bigdavidwong committed Nov 7, 2024
1 parent 16e4422 commit 10e0547
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
2 changes: 1 addition & 1 deletion condition.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func IfThenElse[T any](condition bool, trueValue, falseValue T) T {
}

// IfThenElseFunc 根据条件执行对应的函数并返回泛型结果
func IfThenElseFunc[T any](condition bool, trueFunc, falseFunc func() T) T {
func IfThenElseFunc[T any](condition bool, trueFunc, falseFunc func() (T, error)) (T, error) {
if condition {
return trueFunc()
}
Expand Down
19 changes: 11 additions & 8 deletions condition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,26 +37,29 @@ func ExampleIfThenElse() {
}

func TestIfThenElseFunc(t *testing.T) {
err := IfThenElseFunc(true, func() error {
return nil
}, func() error {
return errors.New("some error")
resp, err := IfThenElseFunc(true, func() (int, error) {
return 0, nil
}, func() (int, error) {
return 1, errors.New("some error")
})
assert.NoError(t, err)
assert.Equal(t, resp, 0)
}

func ExampleIfThenElseFunc() {
err := IfThenElseFunc(false, func() error {
code, err := IfThenElseFunc(false, func() (code int, err error) {
// do something when condition is true
// ...
return nil
}, func() error {
return 0, nil
}, func() (code int, err error) {
// do something when condition is false
// ...
return errors.New("some error when execute func2")
return 1, errors.New("some error when execute func2")
})
fmt.Println(code)
fmt.Println(err)

// Output:
// 1
// some error when execute func2
}

0 comments on commit 10e0547

Please sign in to comment.