Files
convx/to_string.go
T
2024-10-28 20:33:26 +08:00

47 lines
1.0 KiB
Go

package convx
import (
"errors"
"fmt"
"strconv"
)
// interface 转 string
func ToString(val interface{}) (str string, err error) {
switch v := val.(type) {
case nil:
return "", fmt.Errorf("can not convert to string")
case string:
return v, nil
case int:
return strconv.Itoa(v), nil
case int8:
return strconv.FormatInt(int64(v), 10), nil
case int16:
return strconv.FormatInt(int64(v), 10), nil
case int32:
return strconv.FormatInt(int64(v), 10), nil
case int64:
return strconv.FormatInt(v, 10), nil
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32), nil
case float64:
return strconv.FormatFloat(v, 'f', -1, 64), nil
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
case uint32:
return strconv.FormatUint(uint64(v), 10), nil
case uint64:
return strconv.FormatUint(v, 10), nil
}
return "", errors.New("can not convert to string")
}