完善数据类型转换
This commit is contained in:
+23
-7
@@ -3,6 +3,7 @@ package structx
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ValueSetter 值设置器接口
|
||||
@@ -35,6 +36,13 @@ func (ds *defaultValueSetter) SetFieldValue(field reflect.Value, value string) (
|
||||
return setPointerFieldValue(field, value)
|
||||
}
|
||||
|
||||
if isBasicStructType(fieldType) {
|
||||
if err := setBasicStructValue(field, value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return field.Interface(), nil
|
||||
}
|
||||
|
||||
if isTypeAlias(fieldType) {
|
||||
return setTypeAliasValue(field, value)
|
||||
}
|
||||
@@ -73,28 +81,36 @@ func (ds *defaultValueSetter) SetSliceElementValue(elemValue reflect.Value, item
|
||||
case reflect.String:
|
||||
elemValue.SetString(convertToString(item))
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
num, err := convertToFloat64(item)
|
||||
itemStr := convertToString(item)
|
||||
intVal, err := strconv.ParseInt(itemStr, 10, elemType.Bits())
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法转换为整型: %w", err)
|
||||
}
|
||||
elemValue.SetInt(int64(num))
|
||||
elemValue.SetInt(intVal)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
num, err := convertToFloat64(item)
|
||||
itemStr := convertToString(item)
|
||||
uintVal, err := strconv.ParseUint(itemStr, 10, elemType.Bits())
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法转换为无符号整型: %w", err)
|
||||
}
|
||||
elemValue.SetUint(uint64(num))
|
||||
elemValue.SetUint(uintVal)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
num, err := convertToFloat64(item)
|
||||
itemStr := convertToString(item)
|
||||
floatVal, err := strconv.ParseFloat(itemStr, elemType.Bits())
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法转换为浮点型: %w", err)
|
||||
}
|
||||
elemValue.SetFloat(num)
|
||||
elemValue.SetFloat(floatVal)
|
||||
case reflect.Bool:
|
||||
if b, ok := item.(bool); ok {
|
||||
elemValue.SetBool(b)
|
||||
} else {
|
||||
return fmt.Errorf("无法转换为布尔型")
|
||||
itemStr := convertToString(item)
|
||||
b, err := strconv.ParseBool(itemStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法转换为布尔型: %w", err)
|
||||
}
|
||||
elemValue.SetBool(b)
|
||||
}
|
||||
case reflect.Struct:
|
||||
if isBasicStructType(elemType) {
|
||||
|
||||
Reference in New Issue
Block a user