sanity-io / litter

Litter is a pretty printer library for Go data structures to aid in debugging and testing.
MIT License
1.54k stars 54 forks source link

Not support String() implement function? #48

Open rsgok opened 2 years ago

rsgok commented 2 years ago

Seems like litter not accept costumed String() implement func

Example comparing go-spew

package main

import (
    "github.com/davecgh/go-spew/spew"
    "github.com/sanity-io/litter"
)

func main() {
    TT()
}

type A struct {
    Tag string
    Num int
    InA InA
}

type InA struct {
    Id   int
    Type string
}

func (t InA) String() string {
    return t.Type
}

func TT() {
    a := A{
        Tag: "tag-A",
        Num: 1,
        InA: InA{
            Id:   100,
            Type: "test",
        },
    }
    spew.Dump(a)
    litter.Dump(a)
}

Output compare

(main.A) {
 Tag: (string) (len=5) "tag-A",
 Num: (int) 1,
 InA: (main.InA) test
}
main.A{
  Tag: "tag-A",
  Num: 1,
  InA: main.InA{
    Id: 100,
    Type: "test",
  },
}
atombender commented 2 years ago

Litter doesn't use fmt.Stringer because Litter is meant to produce a format that corresponds to the data structure. If you want to modify the output, you can plug in a custom formatter. You should easily be able to add something that dumps fmt.Stringer types as strings instead.

rsgok commented 2 years ago

Litter doesn't use fmt.Stringer because Litter is meant to produce a format that corresponds to the data structure. If you want to modify the output, you can plug in a custom formatter. You should easily be able to add something that dumps fmt.Stringer types as strings instead.

Have tried custom formatter, seems good.

However, when i use anonymous struct member, output is unexpected. Like I mention in https://github.com/davecgh/go-spew/issues/142

Here is my demo code

package main

import (
    "io"

    "github.com/sanity-io/litter"
)

func main() {
    TT()
}

type A struct {
    Tag string
    Num int
    InA
}

type InA struct {
    Id   int
    Type string
}

func (t InA) String() string {
    return t.Type
}

func (t InA) LitterDump(w io.Writer) {
    w.Write([]byte(t.Type))
}

func TT() {
    a := A{
        Tag: "tag-A",
        Num: 1,
        InA: InA{
            Id:   100,
            Type: "test",
        },
    }
    litter.Dump(a)
}

output is

main.Atest

struct A is missing