Home > Article > Backend Development > Why Does Printing a Nested Struct Cause a Stack Overflow?
Consider the following nested struct:
<code class="go">type ConfigOne struct { Daemon daemon } type daemon struct { Loglevel int Logfile string }</code>
A String() string method converts the struct elements into a string:
<code class="go">func (c ConfigOne) String() string { return fmt.Sprintf("%+v\n", c) }</code>
When printing the nested struct with c.String(), the following error occurs:
runtime: goroutine stack exceeds 1000000000-byte limit fatal error: stack overflow
This error indicates excessive stack usage due to recursion. The recursion is caused by the % v format, which invokes String() for the nested daemon struct. This process repeats indefinitely, leading to a stack overflow.
To resolve the recursion, avoid using % v in the String() method. Instead, construct the string manually, as demonstrated below:
<code class="go">func (c ConfigOne) String() string { //return fmt.Sprintf("%+v\n", c.Daemon.Loglevel) return fmt.Sprintf("%+v\n", c.Daemon) }</code>
By explicitly formatting the daemon struct, we avoid the infinite recursion and ensure that the intended data is output.
The above is the detailed content of Why Does Printing a Nested Struct Cause a Stack Overflow?. For more information, please follow other related articles on the PHP Chinese website!