feat: Support string-alias type's `ToStringE`

This commit is contained in:
Peterlits Zo 2023-12-23 11:57:37 +08:00
parent 48ddde5701
commit a3b5448d74
3 changed files with 14 additions and 2 deletions

View File

@ -233,11 +233,15 @@ func TestToStringE(t *testing.T) {
var jn json.Number var jn json.Number
_ = json.Unmarshal([]byte("8"), &jn) _ = json.Unmarshal([]byte("8"), &jn)
type Key struct { type Key struct {
k string k string
} }
key := &Key{"foo"} key := &Key{"foo"}
type StrAlias string
sa := StrAlias("bar")
tests := []struct { tests := []struct {
input interface{} input interface{}
expect string expect string
@ -266,6 +270,8 @@ func TestToStringE(t *testing.T) {
{template.JS("(1+2)"), "(1+2)", false}, {template.JS("(1+2)"), "(1+2)", false},
{template.CSS("a"), "a", false}, {template.CSS("a"), "a", false},
{template.HTMLAttr("a"), "a", false}, {template.HTMLAttr("a"), "a", false},
{sa, "bar", false},
// errors // errors
{testing.T{}, "", true}, {testing.T{}, "", true},
{key, "", true}, {key, "", true},

View File

@ -911,7 +911,7 @@ func indirect(a interface{}) interface{} {
// Copyright 2011 The Go Authors. All rights reserved. // Copyright 2011 The Go Authors. All rights reserved.
// indirectToStringerOrError returns the value, after dereferencing as many times // indirectToStringerOrError returns the value, after dereferencing as many times
// as necessary to reach the base type (or nil) or an implementation of fmt.Stringer // as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
// or error, // or error.
func indirectToStringerOrError(a interface{}) interface{} { func indirectToStringerOrError(a interface{}) interface{} {
if a == nil { if a == nil {
return nil return nil
@ -980,6 +980,12 @@ func ToStringE(i interface{}) (string, error) {
return s.String(), nil return s.String(), nil
case error: case error:
return s.Error(), nil return s.Error(), nil
}
iReflectVal := reflect.ValueOf(i)
switch iReflectVal.Kind() {
case reflect.String:
return iReflectVal.String(), nil
default: default:
return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i) return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
} }

2
go.mod
View File

@ -1,4 +1,4 @@
module github.com/spf13/cast module github.com/PeterlitsZo/cast
go 1.19 go 1.19