File tree Expand file tree Collapse file tree 1 file changed +25
-2
lines changed
Expand file tree Collapse file tree 1 file changed +25
-2
lines changed Original file line number Diff line number Diff line change 33# 一、开发初衷
44
55Golang中缺少三元表达式,就导致某些情况三元表达式一行就能搞定的事情到Golang里面就得写得很啰嗦,
6- 这是无法忍受的,这个库就是借助大量自定义的if函数来实现类似三元表达式的功能。
6+ 这是无法忍受的,~~ 这个库就是借助大量自定义的if函数来实现类似三元表达式的功能~~ ,最新版本是基于泛型实现的 。
77
88## 二、引入依赖
99
10+ go get安装:
11+
1012``` text
1113go get -u github.com/golang-infrastructure/go-if-expression
1214```
1315
16+ 如果你不想增加新的依赖,直接拷贝下面这段代码到你的utils中,泛型的实现版本非常简洁:
17+
18+ ``` go
19+ package if_expression
20+
21+ // Return
22+ //
23+ // @Description: if实现的三元表达式
24+ // @param boolExpression: 布尔表达式,最终返回一个布尔值
25+ // @param trueReturnValue: 当boolExpression返回值为true的时候返回的值
26+ // @param falseReturnValue: 当boolExpression返回值为false的时候返回的值
27+ // @return bool: 三元表达式的结果,为trueReturnValue或者falseReturnValue中的一个
28+ func Return [T any](boolExpression bool , trueReturnValue, falseReturnValue T ) T {
29+ if boolExpression {
30+ return trueReturnValue
31+ } else {
32+ return falseReturnValue
33+ }
34+ }
35+ ```
36+
1437# 三、 Example
1538
1639比如最常见的默认值场景:
1740
1841``` go
1942threadNum := 0
20- fmt.Printf (" 线程数: %d " , if_expression.ReturnInt (threadNum == 0 , 1 , threadNum))
43+ fmt.Printf (" 线程数: %d " , if_expression.Return (threadNum == 0 , 1 , threadNum))
2144```
2245
2346使用的例子:
You can’t perform that action at this time.
0 commit comments