1

I'm working through the Go tour and in the Errors exercise it mentions that calling Sprint(f) in your Error function will result in an issue, which is an infinite loop. Why this occurs is explained here: Error, infinite loop

In my first implementation though I used Sprintf with the %f verb:

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %f", e)
}

This seems to avoid the issue and I was wondering if this is because the %f verb is expecting a float so it forces it to treat e as a float? The tour mentioned that assignment requires explicit conversion, however I assume that doesn't effect this case?

Or am I completely off the mark and something else is going on here?

Community
  • 1
  • 1
Shaun Bouckaert
  • 8,417
  • 1
  • 17
  • 20
  • Doesn't `Sprintf` return a string and thus is not affected by the issue? – masnun Apr 17 '17 at 11:55
  • Sprint also returns a string – Shaun Bouckaert Apr 17 '17 at 11:56
  • Yes, right. My bad. – masnun Apr 17 '17 at 11:57
  • Check out these questions+answers for examples when the same issue arises, and type conversion solves it (explanation is in the answers): [Call json.Unmarshal inside UnmarshalJSON function without causing stack overflow](http://stackoverflow.com/questions/43176625/call-json-unmarshal-inside-unmarshaljson-function-without-causing-stack-overflow/43178272#43178272); and [The difference between t and *t](http://stackoverflow.com/questions/43065856/the-difference-between-t-and-t/43065979#43065979). – icza Apr 17 '17 at 15:09

1 Answers1

4

That infinite loop case applies only to v, s, x, X, and q.

See here: https://github.com/golang/go/blob/6f51082da77a1d4cafd5b7af0db69293943f4066/src/fmt/print.go#L615

ordonezalex
  • 2,645
  • 1
  • 20
  • 33
mkopriva
  • 35,176
  • 4
  • 57
  • 71