mirror of
https://github.com/jefferyjob/go-easy-utils.git
synced 2025-09-27 03:15:55 +08:00
三元运算符 (#101)
This commit is contained in:
@@ -57,5 +57,8 @@ func ToUint32(i any) (uint32, error)
|
|||||||
func ToUint64(i any) (uint64, error)
|
func ToUint64(i any) (uint64, error)
|
||||||
|
|
||||||
// ToBool 将给定的值转换为bool
|
// ToBool 将给定的值转换为bool
|
||||||
func ToBool(i any) bool
|
func ToBool(i any) bool
|
||||||
|
|
||||||
|
// Ternary 三元运算符
|
||||||
|
func Ternary[T any](expr bool, a, b T) T
|
||||||
```
|
```
|
11
anyx/ternary.go
Normal file
11
anyx/ternary.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package anyx
|
||||||
|
|
||||||
|
// Ternary 三元运算符
|
||||||
|
// 根据表达式 expr 的布尔值,返回 a 或 b 中的一个
|
||||||
|
// 如果 expr 为 true,则返回 a;否则返回 b
|
||||||
|
func Ternary[T any](expr bool, a, b T) T {
|
||||||
|
if expr {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
13
anyx/ternary_example_test.go
Normal file
13
anyx/ternary_example_test.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package anyx
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func ExampleTernary() {
|
||||||
|
age := 15
|
||||||
|
res := Ternary(age < 18, "未成年", "成年")
|
||||||
|
|
||||||
|
fmt.Println(res)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// 未成年
|
||||||
|
}
|
43
anyx/ternary_test.go
Normal file
43
anyx/ternary_test.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
package anyx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTernary(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
expr bool
|
||||||
|
a any
|
||||||
|
b any
|
||||||
|
expected any
|
||||||
|
}{
|
||||||
|
{"TrueCase_String", true, "yes", "no", "yes"},
|
||||||
|
{"FalseCase_String", false, "yes", "no", "no"},
|
||||||
|
{"TrueCase_Int", true, 1, 2, 1},
|
||||||
|
{"FalseCase_Int", false, 1, 2, 2},
|
||||||
|
{"TrueCase_Struct", true, struct{ X int }{1}, struct{ X int }{2}, struct{ X int }{1}},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
switch tt.a.(type) {
|
||||||
|
case string:
|
||||||
|
result := Ternary(tt.expr, tt.a.(string), tt.b.(string))
|
||||||
|
if result != tt.expected.(string) {
|
||||||
|
t.Errorf("expected %v, got %v", tt.expected, result)
|
||||||
|
}
|
||||||
|
case int:
|
||||||
|
result := Ternary(tt.expr, tt.a.(int), tt.b.(int))
|
||||||
|
if result != tt.expected.(int) {
|
||||||
|
t.Errorf("expected %v, got %v", tt.expected, result)
|
||||||
|
}
|
||||||
|
case struct{ X int }:
|
||||||
|
result := Ternary(tt.expr, tt.a.(struct{ X int }), tt.b.(struct{ X int }))
|
||||||
|
if result != tt.expected.(struct{ X int }) {
|
||||||
|
t.Errorf("expected %+v, got %+v", tt.expected, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user