diff --git a/dump/dump.go b/dump/dump.go index 4e9320cf9..2c74462e6 100644 --- a/dump/dump.go +++ b/dump/dump.go @@ -3,6 +3,7 @@ package dump import ( "bytes" + "fmt" "io" "os" "reflect" @@ -43,6 +44,9 @@ var ( opts.Output = os.Stdout opts.ShowFlag = Fnopos }) + + // some type init + stringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() ) // Theme color code/tag map for dump diff --git a/dump/dumper.go b/dump/dumper.go index 262dd727a..b0eb66a6e 100644 --- a/dump/dumper.go +++ b/dump/dumper.go @@ -236,11 +236,11 @@ func (d *Dumper) printRValue(t reflect.Type, v reflect.Value) { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: intStr := strconv.FormatInt(v.Int(), 10) intStr = d.ColorTheme.integer(intStr) - d.printf("%s(%s),%s\n", t.String(), intStr, d.rvStringer(v)) + d.printf("%s(%s),%s\n", t.String(), intStr, d.rvStringer(t, v)) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: intStr := strconv.FormatUint(v.Uint(), 10) intStr = d.ColorTheme.integer(intStr) - d.printf("%s(%s),%s\n", t.String(), intStr, d.rvStringer(v)) + d.printf("%s(%s),%s\n", t.String(), intStr, d.rvStringer(t, v)) case reflect.String: strVal := d.ColorTheme.string(v.String()) lenTip := d.ColorTheme.valTip("#len=" + strconv.Itoa(v.Len())) @@ -395,10 +395,10 @@ func (d *Dumper) checkCyclicRef(t reflect.Type, v reflect.Value) (goon bool) { return true } -func (d *Dumper) rvStringer(rv reflect.Value) string { - val := rv.Interface() - if s, ok := val.(fmt.Stringer); ok { - return d.ColorTheme.valTip(` #str: "` + s.String() + `"`) +func (d *Dumper) rvStringer(rt reflect.Type, rv reflect.Value) string { + // fmt.Println("Implements fmt.Stringer:", t.Implements(stringerType)) + if rv.CanInterface() && rt.Implements(stringerType) { + return d.ColorTheme.valTip(` #str: "` + rv.Interface().(fmt.Stringer).String() + `"`) } return "" } diff --git a/dump/dumper_test.go b/dump/dumper_test.go index 283b9311d..2d917d451 100644 --- a/dump/dumper_test.go +++ b/dump/dumper_test.go @@ -3,6 +3,7 @@ package dump import ( "bytes" "fmt" + "io/fs" "os" "reflect" "testing" @@ -419,3 +420,26 @@ func TestStruct_WithNested(t *testing.T) { // Github: string("https://github.com/inhere"), // } } + +func TestDumper_Dump_userType(t *testing.T) { + type testSt struct { + name string + mod fs.FileMode + Mod2 fs.FileMode + Age int + } + + st := testSt{ + name: "inhere", + mod: 0777, + Mod2: 0775, + Age: 23, + } + + fmt.Println("------ use dumper ------") + P(st) + fmt.Println("------ use fmt.Println ------") + fmt.Println(st) + fmt.Println("------ use fmt.Printf ------") + fmt.Printf("%+v\n", st) +}