三元运算符 (#101)

This commit is contained in:
jefferyjob
2025-07-23 11:15:03 +08:00
committed by GitHub
parent 334f8362f8
commit e7323b7144
4 changed files with 71 additions and 1 deletions

View File

@@ -57,5 +57,8 @@ func ToUint32(i any) (uint32, error)
func ToUint64(i any) (uint64, error)
// 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
View 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
}

View 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
View 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)
}
}
})
}
}