Exercise: Errors

Take your Sqrt function from the earlier exercise and make it return an error when given a negative number.

Create a custom error type:

type ErrNegativeSqrt float64

Give it an Error() string method so that ErrNegativeSqrt(-2).Error() returns "cannot Sqrt negative number: -2".

Then update Sqrt to return an ErrNegativeSqrt value for negative inputs.

Watch out: calling fmt.Sprint(e) inside Error will cause infinite recursion — fmt.Sprint calls Error, which calls fmt.Sprint, and so on. Convert first: fmt.Sprint(float64(e)).

package main

import (
	"fmt"
)

func Sqrt(x float64) (float64, error) {
	return 0, nil
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(Sqrt(-2))
}