优化类型的定义

This commit is contained in:
Yun
2024-10-28 20:02:37 +08:00
parent 832e70ba48
commit 1e41151c1d
6 changed files with 232 additions and 102 deletions
+24 -19
View File
@@ -8,40 +8,45 @@ import (
// interface 转 float64
func ToFloat64(val interface{}) (f float64, err error) {
if v, ok := val.(string); ok {
f, err = strconv.ParseFloat(v, 64)
} else if v, ok := val.(float64); ok {
switch v := val.(type) {
case nil:
return 0, errors.New("val is nil")
case float32:
return float64(v), nil
case float64:
return v, nil
} else if v, ok := val.(float32); ok {
case int:
return float64(v), nil
} else if v, ok := val.(int); ok {
case int8:
return float64(v), nil
} else if v, ok := val.(int8); ok {
case int16:
return float64(v), nil
} else if v, ok := val.(int16); ok {
case int32:
return float64(v), nil
} else if v, ok := val.(int32); ok {
case int64:
return float64(v), nil
} else if v, ok := val.(int64); ok {
case uint:
return float64(v), nil
} else if v, ok := val.(uint); ok {
case uint8:
return float64(v), nil
} else if v, ok := val.(uint8); ok {
case uint16:
return float64(v), nil
} else if v, ok := val.(uint16); ok {
case uint32:
return float64(v), nil
} else if v, ok := val.(uint32); ok {
case uint64:
return float64(v), nil
} else if v, ok := val.(uint64); ok {
return float64(v), nil
} else if v, ok := val.(bool); ok {
case string:
return strconv.ParseFloat(v, 64)
case bool:
if v {
return 1, nil
} else {
return 0, nil
}
} else {
return 0, errors.New("类型转换失败")
case []byte:
return strconv.ParseFloat(string(v), 64)
}
return
return 0, errors.New("convx.ToFloat64: unknown type")
}