From 317856e841367bcd17b06674abf68dcb3a0bad68 Mon Sep 17 00:00:00 2001 From: "david.wong" Date: Thu, 7 Nov 2024 16:37:53 +0800 Subject: [PATCH] =?UTF-8?q?IfThenElseFunc=E5=9B=BA=E5=AE=9A=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E9=94=99=E8=AF=AF=E8=BF=94=E5=9B=9E=EF=BC=8C=E6=B3=9B?= =?UTF-8?q?=E5=9E=8BT=E4=BD=9C=E4=B8=BA=E7=94=A8=E6=88=B7=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E8=87=AA=E5=AE=9A=E4=B9=89=E8=BF=94=E5=9B=9E=E7=9A=84?= =?UTF-8?q?=E7=BB=93=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- condition.go | 2 +- condition_test.go | 19 +++++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/condition.go b/condition.go index e0181be..eb7f9f7 100644 --- a/condition.go +++ b/condition.go @@ -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() } diff --git a/condition_test.go b/condition_test.go index 7df6ab3..272c226 100644 --- a/condition_test.go +++ b/condition_test.go @@ -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 }