From fa2d0e253e9bed575678aee4b9e87bdfa40a2d8c Mon Sep 17 00:00:00 2001 From: CC11001100 Date: Thu, 24 Nov 2022 15:11:49 +0800 Subject: [PATCH 1/2] add some test case --- if_expression_test.go | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/if_expression_test.go b/if_expression_test.go index d308609..2a75cbc 100644 --- a/if_expression_test.go +++ b/if_expression_test.go @@ -17,10 +17,13 @@ func ExampleReturn() { // 是 } -func TestMap(t *testing.T) { - m := map[string]interface{}{ - "foo": "bar", - } - //t.Log(m["bad"]) // nil - t.Log(Return(m["bad"] != nil, m["bad"], "aaa")) // ⚠️ 范型传nil进来就panic了. -} +//func TestMap(t *testing.T) { +// m := map[string]interface{}{ +// "foo": "bar", +// } +// m["bar"] = "aaa" +// //t.Log(m["bad"]) // nil +// var v string +// v = Return[string](m["bad"] == nil, m["bar"], "aaa") // m["bar"]的类型不对 +// t.Log(v) +//} From 4869afa84314f9ceb2749f0d00ccd59e4398a028 Mon Sep 17 00:00:00 2001 From: CC11001100 Date: Fri, 2 Dec 2022 14:00:08 +0800 Subject: [PATCH 2/2] add ReturnByFunc --- if_expression.go | 15 +++++++++++++++ if_expression_test.go | 9 +++++++++ 2 files changed, 24 insertions(+) diff --git a/if_expression.go b/if_expression.go index c4fe352..8fac861 100644 --- a/if_expression.go +++ b/if_expression.go @@ -14,3 +14,18 @@ func Return[T any](boolExpression bool, trueReturnValue, falseReturnValue T) T { return falseReturnValue } } + +// ReturnByFunc +// +// @Description: if实现的三元表达式 +// @param boolExpression: 布尔表达式,最终返回一个布尔值 +// @param trueReturnValue: 当boolExpression返回值为true的时候执行此函数并返回值 +// @param falseReturnValue: 当boolExpression返回值为false的时候执行此函数并返回值 +// @return bool: 三元表达式的结果,为trueReturnValue或者falseReturnValue中的一个 +func ReturnByFunc[T any](boolExpression bool, trueFuncForReturnValue, falseFuncForReturnValue func() T) T { + if boolExpression { + return trueFuncForReturnValue() + } else { + return falseFuncForReturnValue() + } +} diff --git a/if_expression_test.go b/if_expression_test.go index 2a75cbc..ffb5248 100644 --- a/if_expression_test.go +++ b/if_expression_test.go @@ -27,3 +27,12 @@ func ExampleReturn() { // v = Return[string](m["bad"] == nil, m["bar"], "aaa") // m["bar"]的类型不对 // t.Log(v) //} + +func TestReturnByFunc(t *testing.T) { + r := ReturnByFunc[string](true, func() string { + return "是" + }, func() string { + return "否" + }) + fmt.Println(r) +}