Skip to content

Commit

Permalink
up: update some for reflects.BKind, add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 8, 2022
1 parent c680246 commit 1f2107f
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 22 deletions.
33 changes: 11 additions & 22 deletions reflects/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,19 @@ type BKind uint

// base kinds
const (
Invalid BKind = iota
Bool
Int
Uint
Float
String
Array
Map
Struct
Complex
Unsupported
// Int for all intX types
Int = BKind(reflect.Int)
// Uint for all uintX types
Uint = BKind(reflect.Uint)
Float = BKind(reflect.Float32)
Array = BKind(reflect.Array)
// Complex for all complexX types
Complex = BKind(reflect.Complex64)
)

// ToBaseKind convert reflect.Kind to base kind
func ToBaseKind(kind reflect.Kind) BKind {
switch kind {
case reflect.Bool:
return Bool
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return Int
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
Expand All @@ -33,18 +28,12 @@ func ToBaseKind(kind reflect.Kind) BKind {
return Float
case reflect.Complex64, reflect.Complex128:
return Complex
case reflect.String:
return String
case reflect.Array, reflect.Slice:
return Array
case reflect.Map:
return Map
case reflect.Struct:
return Struct
default:
// like: string, map, struct, ptr, func, interface ...
return BKind(kind)
}

// like: ptr, func, interface ...
return Unsupported
}

// Type struct
Expand Down
25 changes: 25 additions & 0 deletions reflects/type_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package reflects_test

import (
"reflect"
"testing"

"github.com/gookit/goutil/reflects"
"github.com/stretchr/testify/assert"
)

func TestToBaseKind(t *testing.T) {
assert.Equal(t, reflects.ToBaseKind(reflect.Int16), reflects.Int)
assert.Equal(t, reflects.ToBaseKind(reflect.Uint16), reflects.Uint)
assert.Equal(t, reflects.ToBaseKind(reflect.Float32), reflects.Float)
assert.Equal(t, reflects.ToBaseKind(reflect.Slice), reflects.Array)
assert.Equal(t, reflects.ToBaseKind(reflect.Complex64), reflects.Complex)
assert.Equal(t, reflects.ToBaseKind(reflect.String), reflects.BKind(reflect.String))
}

func TestTypeOf(t *testing.T) {
rt := reflects.TypeOf(int64(23))

assert.Equal(t, reflect.Int64, rt.Kind())
assert.Equal(t, reflects.Int, rt.BaseKind())
}
16 changes: 16 additions & 0 deletions reflects/value_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package reflects_test

import (
"reflect"
"testing"

"github.com/gookit/goutil/reflects"
"github.com/stretchr/testify/assert"
)

func TestValueOf(t *testing.T) {
rv := reflects.ValueOf(int64(23))

assert.Equal(t, reflect.Int64, rv.Kind())
assert.Equal(t, reflects.Int, rv.BaseKind())
}

0 comments on commit 1f2107f

Please sign in to comment.