mirror of https://github.com/spf13/cast.git
feat: Support string-alias type's `ToStringE`
This commit is contained in:
parent
48ddde5701
commit
a3b5448d74
|
@ -233,11 +233,15 @@ func TestToStringE(t *testing.T) {
|
|||
|
||||
var jn json.Number
|
||||
_ = json.Unmarshal([]byte("8"), &jn)
|
||||
|
||||
type Key struct {
|
||||
k string
|
||||
}
|
||||
key := &Key{"foo"}
|
||||
|
||||
type StrAlias string
|
||||
sa := StrAlias("bar")
|
||||
|
||||
tests := []struct {
|
||||
input interface{}
|
||||
expect string
|
||||
|
@ -266,6 +270,8 @@ func TestToStringE(t *testing.T) {
|
|||
{template.JS("(1+2)"), "(1+2)", false},
|
||||
{template.CSS("a"), "a", false},
|
||||
{template.HTMLAttr("a"), "a", false},
|
||||
{sa, "bar", false},
|
||||
|
||||
// errors
|
||||
{testing.T{}, "", true},
|
||||
{key, "", true},
|
||||
|
|
8
caste.go
8
caste.go
|
@ -911,7 +911,7 @@ func indirect(a interface{}) interface{} {
|
|||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// indirectToStringerOrError returns the value, after dereferencing as many times
|
||||
// as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
|
||||
// or error,
|
||||
// or error.
|
||||
func indirectToStringerOrError(a interface{}) interface{} {
|
||||
if a == nil {
|
||||
return nil
|
||||
|
@ -980,6 +980,12 @@ func ToStringE(i interface{}) (string, error) {
|
|||
return s.String(), nil
|
||||
case error:
|
||||
return s.Error(), nil
|
||||
}
|
||||
|
||||
iReflectVal := reflect.ValueOf(i)
|
||||
switch iReflectVal.Kind() {
|
||||
case reflect.String:
|
||||
return iReflectVal.String(), nil
|
||||
default:
|
||||
return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue