Friday, December 04, 2015

Golang Exercise: Errors

package main

import (
 "fmt"
 "math"
)


type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
 if e < 0 {
  return fmt.Sprintf("cannot Sqrt negative number: %v ", float64(e))
 }
 return ""
}


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



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

Output:
1.4142135623730951 
-2 cannot Sqrt negative number: -2 

Program exited.

Reference:

http://tour.golang.org/methods/9

No comments: