4

I am trying to solve this: http://tour.golang.org/#58

Here is what I have done:

#imports omitted
type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return "Cannot Sqrt negative number: " + string(e)
}

func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, ErrNegativeSqrt(1)
    }
    # calculate z here...
    return z, nil
}
# main omitted

I have also tried e.String() and e.string() but those didn't work too.

1 Answer 1

10

Try using the fmt package

import "fmt"
...
return fmt.Sprint("Cannot Sqrt negative number ", float64(e))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. I had to use it with float64(e) as hints suggested, otherwise it made an infinite loop. I am not sure why though.
Ah, yes. Forgot about that. fmt.Print (and other fmt functions) will print the error message of the type if it implement the error interface (has a method Error() string). This will cause fmt.Sprint to call your Error() func, which will call fmt.Sprint, etc, in a loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.