13

According to fortyforty's reply to this question:

fmt.Sprint(e) will call e.Error() to convert the value e to a string. If the Error() method calls fmt.Sprint(e), then the program recurses until out of memory.

You can break the recursion by converting the e to a value without a String or Error method.

This is still confusing to me. Why does fmt.Sprint(e) call e.Error() instead of String()? I tried using the Stringer interface, this is my code:

package main

import (
  "fmt"
  "math"
)

type NegativeSqrt float64

func (e NegativeSqrt) Error() string {
  fmt.Printf(".")
  return fmt.Sprint(e)
}

func (e NegativeSqrt) String() string {
  return fmt.Sprintf("%f", e)
}

func Sqrt(x float64) (float64, error) {
  if x < 0 {
    return 0, NegativeSqrt(x)
  }
  return math.Sqrt(x), nil
}

func main() {
  fmt.Println(Sqrt(2))
  fmt.Println(Sqrt(-2))
}
Community
  • 1
  • 1
Davide Guerri
  • 1,887
  • 2
  • 17
  • 25

3 Answers3

14

It seems it's explained directly is source of fmt package:

// Is it an error or Stringer?
// The duplication in the bodies is necessary:
// setting handled and deferring catchPanic
// must happen before calling the method.

And than Error() or String() is called.

What it means is that first error.Error() is called to produce string, which is than once again processed and is printed as string.

Whether error has method String is irrelevant here. The question is why NegativeSqrt is printed with one method and not the other. Type NegativeSqrt implements both fmt.Stringer and error interfaces so it's up to the implementation of fmt package which of interfaces should be used to get string from NegativeSqrt (since fmt.Sprint takes its parameters by interface{}).

To illustrate this consider this example:

package main

import (
    "fmt"
)

type NegativeSqrt float64

func (e NegativeSqrt) Error() string {
    return ""
}

func (e NegativeSqrt) String() string {
    return ""
}

func check(val interface{}) {
    switch val.(type) {
    case fmt.Stringer:
        fmt.Println("It's stringer")
    case error:
        fmt.Println("It's error")
    }
}

func check2(val interface{}) {
    switch val.(type) {
    case error:
        fmt.Println("It's error")
    case fmt.Stringer:
        fmt.Println("It's stringer")
    }
}

func main() {
    var v NegativeSqrt
    check(v)
    check2(v)
}

Executing this gives:

% go run a.go
It's stringer
It's error

This is because in Go type switch behaves just like normal switch, so order of cases matters.

Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101
tumdum
  • 1,981
  • 14
  • 19
5

Because the type is error and the interface of error is

  type error interface{
     Error() string
  }

every error must have an Error() string method but does not have to have a String() string method. That why is logic to check first the Error() method.

fabrizioM
  • 46,639
  • 15
  • 102
  • 119
1

Let me expand tumdum's finding for better clarity.

I'll jump from a call to call to show how we go into loop.

We start from the exercise's

func (e NegativeSqrt) Error() string {
  fmt.Printf(".")
  return fmt.Sprint(e)
}

Which delivers us to a line 237 of the fmt/print.go:

func Sprint(a ...interface{}) string

Inside the function, our next jump is on line 239:

p.doPrint(a, false, false)

We arrive to line 1261:

func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {

Inside that function, we'll jump, with our error argument, through line 1273:

prevString = p.printArg(arg, 'v', 0)

We arrive at a huge core monster function at line 738:

func (p *pp) printArg(arg interface{}, verb rune, depth int) (wasString bool) {

Inside that, you can see a large switch case switch. error goes in the default section as it is deemed to be a non-trivial type.

Which delivers us to line 806 with the call to handleMethods():

if handled := p.handleMethods(verb, depth); handled {

We arrive at line 688:

func (p *pp) handleMethods(verb rune, depth int) (handled bool) {

Inside of that function, on line 724, call to Error() happens, which completes the loop:

p.printArg(v.Error(), verb, depth)
Fyodor
  • 2,793
  • 4
  • 21
  • 24