Skip to content

Dev #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions if_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
24 changes: 18 additions & 6 deletions if_expression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,22 @@ 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)
//}

func TestReturnByFunc(t *testing.T) {
r := ReturnByFunc[string](true, func() string {
return "是"
}, func() string {
return "否"
})
fmt.Println(r)
}