Bladeren bron

添加反射函数

yjp 6 maanden geleden
bovenliggende
commit
56474795a9
2 gewijzigde bestanden met toevoegingen van 86 en 3 verwijderingen
  1. 65 0
      reflectutils/type.go
  2. 21 3
      reflectutils/value.go

+ 65 - 0
reflectutils/type.go

@@ -0,0 +1,65 @@
+package reflectutils
+
+import "reflect"
+
+// GroupTypeKind 将反射的Kind值进行聚集
+func GroupTypeKind(t reflect.Type) reflect.Kind {
+	kind := t.Kind()
+
+	switch {
+	case kind >= reflect.Int && kind <= reflect.Int64:
+		return reflect.Int64
+	case kind >= reflect.Uint && kind <= reflect.Uint64:
+		return reflect.Uint64
+	case kind >= reflect.Float32 && kind <= reflect.Float64:
+		return reflect.Float64
+	default:
+		return kind
+	}
+}
+
+func PointerTypeElem(t reflect.Type) reflect.Type {
+	elem := t
+	if t.Kind() == reflect.Ptr {
+		elem = t.Elem()
+	}
+
+	return elem
+}
+
+func SliceTypeElem(t reflect.Type) reflect.Type {
+	elem := t
+	if t.Kind() == reflect.Slice {
+		elem = t.Elem()
+	}
+
+	return elem
+}
+
+func IsTypeInteger(t reflect.Type) bool {
+	return t.Kind() >= reflect.Int && t.Kind() <= reflect.Int64
+}
+
+func IsTypeUnsignedInteger(t reflect.Type) bool {
+	return t.Kind() >= reflect.Uint && t.Kind() <= reflect.Uint64
+}
+
+func IsTypeFloat(t reflect.Type) bool {
+	return t.Kind() >= reflect.Float32 && t.Kind() <= reflect.Float64
+}
+
+func IsTypeStructPointer(t reflect.Type) bool {
+	return t.Kind() == reflect.Pointer && t.Kind() == reflect.Struct
+}
+
+func IsTypeStructOrStructPointer(t reflect.Type) bool {
+	return t.Kind() == reflect.Struct || IsTypeStructPointer(t)
+}
+
+func IsTypeTime(t reflect.Type) bool {
+	return t.Kind() == reflect.Struct && t.String() == "time.Time"
+}
+
+func IsTypeTimePointer(t reflect.Type) bool {
+	return t.Kind() == reflect.Pointer && IsTypeTime(t.Elem())
+}

+ 21 - 3
reflectutils/value.go

@@ -22,15 +22,33 @@ func GroupValueKind(v reflect.Value) reflect.Kind {
 	}
 }
 
-func IsInteger(v reflect.Value) bool {
+func PointerValueElem(v reflect.Value) reflect.Value {
+	elem := v
+	if v.Kind() == reflect.Ptr {
+		elem = v.Elem()
+	}
+
+	return elem
+}
+
+func SliceValueElem(v reflect.Value) reflect.Value {
+	elem := v
+	if v.Kind() == reflect.Slice {
+		elem = v.Elem()
+	}
+
+	return elem
+}
+
+func IsValueInteger(v reflect.Value) bool {
 	return v.Kind() >= reflect.Int && v.Kind() <= reflect.Int64
 }
 
-func IsUnsignedInteger(v reflect.Value) bool {
+func IsValueUnsignedInteger(v reflect.Value) bool {
 	return v.Kind() >= reflect.Uint && v.Kind() <= reflect.Uint64
 }
 
-func IsFloat(v reflect.Value) bool {
+func IsValueFloat(v reflect.Value) bool {
 	return v.Kind() >= reflect.Float32 && v.Kind() <= reflect.Float64
 }