Skip to content

Commit e3b4693

Browse files
authored
Merge pull request #7 from golang-infrastructure/dev
Dev
2 parents 226ba33 + 4869afa commit e3b4693

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

if_expression.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,18 @@ func Return[T any](boolExpression bool, trueReturnValue, falseReturnValue T) T {
1414
return falseReturnValue
1515
}
1616
}
17+
18+
// ReturnByFunc
19+
//
20+
// @Description: if实现的三元表达式
21+
// @param boolExpression: 布尔表达式,最终返回一个布尔值
22+
// @param trueReturnValue: 当boolExpression返回值为true的时候执行此函数并返回值
23+
// @param falseReturnValue: 当boolExpression返回值为false的时候执行此函数并返回值
24+
// @return bool: 三元表达式的结果,为trueReturnValue或者falseReturnValue中的一个
25+
func ReturnByFunc[T any](boolExpression bool, trueFuncForReturnValue, falseFuncForReturnValue func() T) T {
26+
if boolExpression {
27+
return trueFuncForReturnValue()
28+
} else {
29+
return falseFuncForReturnValue()
30+
}
31+
}

if_expression_test.go

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,22 @@ func ExampleReturn() {
1717
// 是
1818
}
1919

20-
func TestMap(t *testing.T) {
21-
m := map[string]interface{}{
22-
"foo": "bar",
23-
}
24-
//t.Log(m["bad"]) // nil
25-
t.Log(Return(m["bad"] != nil, m["bad"], "aaa")) // ⚠️ 范型传nil进来就panic了.
20+
//func TestMap(t *testing.T) {
21+
// m := map[string]interface{}{
22+
// "foo": "bar",
23+
// }
24+
// m["bar"] = "aaa"
25+
// //t.Log(m["bad"]) // nil
26+
// var v string
27+
// v = Return[string](m["bad"] == nil, m["bar"], "aaa") // m["bar"]的类型不对
28+
// t.Log(v)
29+
//}
30+
31+
func TestReturnByFunc(t *testing.T) {
32+
r := ReturnByFunc[string](true, func() string {
33+
return "是"
34+
}, func() string {
35+
return "否"
36+
})
37+
fmt.Println(r)
2638
}

0 commit comments

Comments
 (0)