Files
convx/to_string.go
T

47 lines
1.0 KiB
Go
Raw Normal View History

2024-08-15 02:43:22 +00:00
package convx
import (
2024-10-28 20:33:26 +08:00
"errors"
2024-10-27 22:19:20 +08:00
"fmt"
2024-08-15 02:43:22 +00:00
"strconv"
)
// interface 转 string
2024-10-28 20:33:26 +08:00
func ToString(val interface{}) (str string, err error) {
2024-08-15 02:43:22 +00:00
switch v := val.(type) {
2024-10-28 20:33:26 +08:00
case nil:
return "", fmt.Errorf("can not convert to string")
case string:
return v, nil
2024-08-15 02:43:22 +00:00
case int:
return strconv.Itoa(v), nil
2024-10-28 20:33:26 +08:00
case int8:
return strconv.FormatInt(int64(v), 10), nil
case int16:
return strconv.FormatInt(int64(v), 10), nil
2024-08-15 02:43:22 +00:00
case int32:
2024-10-28 20:33:26 +08:00
return strconv.FormatInt(int64(v), 10), nil
2024-08-15 02:43:22 +00:00
case int64:
return strconv.FormatInt(v, 10), nil
2024-10-28 20:33:26 +08:00
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32), nil
case float64:
return strconv.FormatFloat(v, 'f', -1, 64), nil
2024-08-15 02:43:22 +00:00
case bool:
return strconv.FormatBool(v), nil
case uint:
return strconv.FormatUint(uint64(v), 10), nil
case uint8:
return strconv.FormatUint(uint64(v), 10), nil
case uint16:
return strconv.FormatUint(uint64(v), 10), nil
2024-10-28 20:33:26 +08:00
case uint32:
return strconv.FormatUint(uint64(v), 10), nil
case uint64:
return strconv.FormatUint(v, 10), nil
2024-08-15 02:43:22 +00:00
}
2024-10-28 20:33:26 +08:00
return "", errors.New("can not convert to string")
2024-08-15 02:43:22 +00:00
}