Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fmt: value implementing Stringer (GoString) cause infinite recursion with %s (%v) #12285

Closed
vladimirvivien opened this issue Aug 23, 2015 · 3 comments

Comments

@vladimirvivien
Copy link

The fmt.Print{f, ln} function generates a stackoverflow when the format flag is %v to output the value of a type that implements the Stringer interface. This is true when the implementation of the String() method also uses fmt with flag %v or %s flag to output the string as shown in the example below.

1)What version of Go are you using (go version)?
go version go1.4.2 linux/amd64

2) What operating system and processor architecture are you using?
Ubuntu 14 trusty
Linux Kernel 3.14

3)What did you do ?
The following simple program.

package main

import (
    "fmt"
)

type mytype string

func (m mytype) String() string {
    return fmt.Sprintf("%s", m)
}

func main() {
    s := mytype("hello")
    fmt.Printf("%v", s)
}
  1. What did you expect to see?
    Expects the value of s to be printed.

5) What did you see instead?

runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
@bradfitz bradfitz changed the title GoStringer value cause Stack Overflow when %V or %S used in implementation x/tools/cmd/stringer: value cause stack overflow with %V or %S Aug 23, 2015
@minux minux changed the title x/tools/cmd/stringer: value cause stack overflow with %V or %S fmt: value implementing Stringer (GoString) cause infinite recursion with %s (%v) Aug 24, 2015
@minux
Copy link
Member

minux commented Aug 24, 2015

This is working as intended. You need to change the String method to
convert m into a real string before passing it to fmt.Sprintf, otherwise
the fmt.Sprintf will just call the String method again, which will lead to
infinite recursion.

http://play.golang.org/p/uURu3VA02V

@minux minux closed this as completed Aug 24, 2015
@ianlancetaylor
Copy link
Contributor

See "To avoid recursion" in the fmt package docs.

@vladimirvivien
Copy link
Author

@ianlancetaylor thanks for pointing that out.

@golang golang locked and limited conversation to collaborators Aug 24, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants