Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4869afa

Browse files
add ReturnByFunc
1 parent fa2d0e2 commit 4869afa

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
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: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,12 @@ func ExampleReturn() {
2727
// v = Return[string](m["bad"] == nil, m["bar"], "aaa") // m["bar"]的类型不对
2828
// t.Log(v)
2929
//}
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)
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /