Skip to content

Commit 7e49a65

Browse files
committed
feat: add isComparable function to check the comparability of a type.
1 parent 48f6e2d commit 7e49a65

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

util.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,20 @@ func isEqual(x, y any) bool {
5353
}
5454
}
5555

56+
// isComparable gets the type of the value, and checks whether the type is comparable or not.
57+
func isComparable(v any) bool {
58+
switch v.(type) {
59+
case
60+
int, int8, int16, int32, int64, // Signed integer
61+
uint, uint8, uint16, uint32, uint64, uintptr, // Unsigned integer
62+
float32, float64, // Floating-point number
63+
string: // string
64+
return true
65+
default:
66+
return false
67+
}
68+
}
69+
5670
// isSameType indicates the equality of two types, and it will ignore the bit size of the same
5771
// type. For example, `int32` and `int64` will be the same type.
5872
func isSameType(t1, t2 reflect.Type) bool {

util_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,19 @@ func TestIsEqual(t *testing.T) {
7878
assert.Equal(isEqual(testStruct1{A: 0}, testStruct2{A: 0}), false)
7979
}
8080

81+
func TestIsComparable(t *testing.T) {
82+
assert := New(t)
83+
84+
assert.Equal(isComparable(1), true)
85+
assert.Equal(isComparable(int64(1)), true)
86+
assert.Equal(isComparable(uint64(1)), true)
87+
assert.Equal(isComparable(float32(1.0)), true)
88+
assert.Equal(isComparable(1.0), true)
89+
assert.Equal(isComparable("Hello"), true)
90+
assert.Equal(isComparable([]byte{'H', 'e', 'l', 'l', 'o'}), false)
91+
assert.Equal(isComparable([]int{1, 2, 3}), false)
92+
}
93+
8194
func TestIsNil(t *testing.T) {
8295
assert := New(t)
8396

0 commit comments

Comments
 (0)