go-learning/exercises/errors.go

32 lines
478 B
Go

package main
import (
"fmt"
"time"
)
type ErrInfo struct {
errTime time.Time
errLine int
}
func (e ErrInfo) Error() string {
return fmt.Sprintf("there was an error at %q, at line %d", e.errTime, e.errLine)
}
func Sqrt(x float64) (float64, error) {
var z float64 = 1.0
if x < 0 {
return 0, ErrInfo{time.Now(), 20}
} else {
for i := 15; i > 0; i-- {
z -= (z*z - x) / (2 * z)
}
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}