modify function ToStringE to support type redefinition

This commit is contained in:
dablelv 2020-12-30 16:21:42 +08:00
parent 8d17101741
commit 4b4f3c28f6
3 changed files with 51 additions and 2 deletions

View File

@ -15,6 +15,23 @@ import (
"github.com/stretchr/testify/assert"
)
type (
intAlias int
int8Alias int8
int16Alias int16
int32Alias int32
int64Alias int64
uintAlias uint
uint8Alias uint8
uint16Alias uint16
uint32Alias uint32
uint64Alias uint64
float32Alias float32
float64Alias float64
boolAlias bool
stringAlias string
)
func TestToUintE(t *testing.T) {
tests := []struct {
input interface{}
@ -605,22 +622,37 @@ func TestToStringE(t *testing.T) {
iserr bool
}{
{int(8), "8", false},
{intAlias(8), "8", false},
{int8(8), "8", false},
{int8Alias(8), "8", false},
{int16(8), "8", false},
{int16Alias(8), "8", false},
{int32(8), "8", false},
{int32Alias(8), "8", false},
{int64(8), "8", false},
{int64Alias(8), "8", false},
{uint(8), "8", false},
{uintAlias(8), "8", false},
{uint8(8), "8", false},
{uint8Alias(8), "8", false},
{uint16(8), "8", false},
{uint16Alias(8), "8", false},
{uint32(8), "8", false},
{uint32Alias(8), "8", false},
{uint64(8), "8", false},
{uint64Alias(8), "8", false},
{float32(8.31), "8.31", false},
{float32Alias(8.31), "8.31", false},
{float64(8.31), "8.31", false},
{float64Alias(8.31), "8.31", false},
{true, "true", false},
{boolAlias(true), "true", false},
{false, "false", false},
{boolAlias(false), "false", false},
{nil, "", false},
{[]byte("one time"), "one time", false},
{"one more time", "one more time", false},
{stringAlias("one more time"), "one more time", false},
{template.HTML("one time"), "one time", false},
{template.URL("http://somehost.foo"), "http://somehost.foo", false},
{template.JS("(1+2)"), "(1+2)", false},

View File

@ -846,9 +846,24 @@ func ToStringE(i interface{}) (string, error) {
return s.String(), nil
case error:
return s.Error(), nil
default:
return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
}
// support type redefinition
switch reflect.TypeOf(i).Kind() {
case reflect.String:
return reflect.ValueOf(i).String(), nil
case reflect.Bool:
return strconv.FormatBool(reflect.ValueOf(i).Bool()), nil
case reflect.Float32:
return strconv.FormatFloat(reflect.ValueOf(i).Float(), 'f', -1, 32), nil
case reflect.Float64:
return strconv.FormatFloat(reflect.ValueOf(i).Float(), 'f', -1, 64), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(reflect.ValueOf(i).Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(reflect.ValueOf(i).Uint(), 10), nil
}
return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
}
// ToStringMapStringE casts an interface to a map[string]string type.

2
go.mod
View File

@ -5,3 +5,5 @@ require (
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2
)
go 1.13