Skip to content

Commit c2f683c

Browse files
committed
新增IfElseAny
1 parent d55a46b commit c2f683c

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

README.md

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,11 +131,17 @@ assert.True(t, s.Equal(s2))
131131

132132
## 九、`ifop`
133133
ifop是弥补下golang没有三目运算符,使用函数模拟
134-
134+
### 9.1 if else部分类型相同
135135
```go
136136
// 如果该值不为0, 返回原来的值,否则默认值
137137
val = IfElse(len(val) != 0, val, "default")
138138
```
139+
### 9.2 if else部分类型不同
140+
```go
141+
o := map[string]any{"hello": "hello"}
142+
a := []any{"hello", "world"}
143+
fmt.Printf("%#v", IfElseAny(o != nil, o, a))
144+
```
139145
## 十、`mapex`
140146
薄薄一层包装,增加标准库map的接口
141147
* mapex.Keys()
@@ -206,4 +212,4 @@ for pair := range m.Iter() {
206212
m.Len()// 获取长度
207213
allKeys := m.Keys() //返回所有的key
208214
allValues := m.Values()// 返回所有的value
209-
```
215+
```

ifop/ifop.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,10 @@ func IfElse[T any](cond bool, ifVal T, elseVal T) T {
1414
}
1515
return elseVal
1616
}
17+
18+
func IfElseAny(cond bool, ifVal any, elseVal any) any {
19+
if cond {
20+
return ifVal
21+
}
22+
return elseVal
23+
}

ifop/ifop_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,12 @@ func TestIfElse(t *testing.T) {
1818
a = "hello"
1919
assert.Equal(t, IfElse(len(a) != 0, a, "default"), "hello")
2020
}
21+
22+
func TestIfElse2(t *testing.T) {
23+
o := map[string]any{"hello": "hello"}
24+
a := []any{"hello", "world"}
25+
26+
assert.Equal(t, IfElseAny(o != nil, o, a), o)
27+
o = nil
28+
assert.Equal(t, IfElseAny(o != nil, o, a), a)
29+
}

0 commit comments

Comments
 (0)