diff --git a/cast_test.go b/cast_test.go index 6bea164..fb1712c 100644 --- a/cast_test.go +++ b/cast_test.go @@ -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}, diff --git a/caste.go b/caste.go index d49bbf8..e2db454 100644 --- a/caste.go +++ b/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) } diff --git a/go.mod b/go.mod index 96d32f2..d5c49b2 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/spf13/cast +module github.com/PeterlitsZo/cast go 1.19