Closed jerome-laforge closed 8 years ago
That causes infinite recursion in the exact same way as the following would:
type Example struct {
foo string
}
func (e Example) String() string {
return fmt.Sprintf("%v", e)
}
I'd recommend not using spew
in a stringer like this. The elegant way to handle it is to simply move the call to spew
outside of the stringer to the caller like so:
package main
import "github.com/davecgh/go-spew/spew"
type Example struct {
foo string
}
func main() {
e := Example{"foostring"}
spew.Printf("%+v\n", e)
}
Output:
{foo:foostring}
ok, thx again for this confirmation
I know this is a user error and should not be supported by spew, but I wonder if it's possible and a good idea for spew to detect when it's indirectly calling itself a second time, and print a more helpful error message?
Or is the overhead of doing that too much (in terms of code to maintain and run-time performance) to outweigh the benefit?
@shurcooL: That's not a bad idea, but I'm really not sure if that could be done without having undesirable side effects.
spew does detect recursion within in a single call by keeping track of the pointers in a local map that is part of the instance, but the issue here is it's effectively calling the upper-level print routine over and over.
Adding some type of global tracking to detect this would mean that code such as the following wouldn't work:
e := &Example{"foostring"}
spew.Println(foo)
e.foo = "Something new"
spew.Println(foo) // <--- spew would now filter this because it would be in the global already printed map
I don't have it completely figured out, it was just a thought.
I was imagining something that would look at the stack trace whenever a top-level spew function is called, to check that it's not being called a second time (from spew).
It may very well not be feasible; I just wanted us to consider it.
I wonder if it's possible and a good idea for spew to detect when it's indirectly calling itself a second time, and print a more helpful error message?
If this modification is possible, is it applicable to print directly the structure as spew usually rather than to display this helpful error message? Or let to user by configuration the choice to display helpful error or print the structure directly without error.
Hello, I want to use go-spew into String() string. For example:
Unfortunately, that generates:
Do you know a elegant manner to do this ?
Thx