101 lines
2.2 KiB
Go
101 lines
2.2 KiB
Go
// Package op_any ...
|
|
//
|
|
// Description : wrapper ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2023-06-01 18:18
|
|
package op_any
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
|
|
"git.zhangdeman.cn/zhangdeman/consts"
|
|
"git.zhangdeman.cn/zhangdeman/serialize"
|
|
)
|
|
|
|
// AnyDataType ...
|
|
func AnyDataType(data any) *AnyType {
|
|
at := &AnyType{
|
|
data: data,
|
|
}
|
|
at.dataType = at.Type()
|
|
return at
|
|
}
|
|
|
|
// AnyType ...
|
|
type AnyType struct {
|
|
data any
|
|
dataType consts.DataType
|
|
}
|
|
|
|
// IsNil 是否为 nil
|
|
func (at *AnyType) IsNil() bool {
|
|
if at.data == nil {
|
|
return true
|
|
}
|
|
reflectValue := reflect.ValueOf(at.data)
|
|
switch reflectValue.Kind() {
|
|
case reflect.Chan, reflect.Func, reflect.Map,
|
|
reflect.Pointer, reflect.UnsafePointer,
|
|
reflect.Interface, reflect.Slice:
|
|
return reflectValue.IsNil()
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// Type 获取类型
|
|
func (at *AnyType) Type() consts.DataType {
|
|
if len(at.dataType) > 0 {
|
|
// 已经处理过的,无需在处理
|
|
return at.dataType
|
|
}
|
|
if at.IsNil() {
|
|
return consts.DataTypeNil
|
|
}
|
|
reflectType := reflect.TypeOf(at.data)
|
|
switch reflectType.Kind() {
|
|
case reflect.String:
|
|
return consts.DataTypeString
|
|
case reflect.Slice, reflect.Array:
|
|
return consts.DataTypeSliceAny
|
|
case reflect.Map, reflect.Struct:
|
|
return consts.DataTypeMapAnyAny
|
|
case reflect.Pointer:
|
|
return consts.DataTypePtr
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
return consts.DataTypeInt
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
return consts.DataTypeUint
|
|
case reflect.Bool:
|
|
return consts.DataTypeBool
|
|
case reflect.Float32, reflect.Float64:
|
|
return consts.DataTypeFloat64
|
|
default:
|
|
return consts.DataTypeUnknown
|
|
}
|
|
}
|
|
|
|
// ToString 转为字符串
|
|
func (at *AnyType) ToString() string {
|
|
dataType := at.Type()
|
|
switch dataType {
|
|
case consts.DataTypeUnknown, consts.DataTypeNil:
|
|
return ""
|
|
case consts.DataTypeString:
|
|
return fmt.Sprintf("%v", at.data)
|
|
case consts.DataTypeInt:
|
|
fallthrough
|
|
case consts.DataTypeUint:
|
|
fallthrough
|
|
case consts.DataTypeFloat64:
|
|
fallthrough
|
|
case consts.DataTypeBool:
|
|
return fmt.Sprintf("%v", at.data)
|
|
default:
|
|
return serialize.JSON.MarshalForStringIgnoreError(at.data)
|
|
}
|
|
}
|