Exercise: Errors

题目:

Copy your Sqrt function from the earlier exercise and modify it to return an error value.
Sqrt should return a non-nil error value when given a negative number, as it doesn't support complex numbers.
Create a new type type ErrNegativeSqrt float64
and make it an error by giving it a
func (e ErrNegativeSqrt) Error() string
method such that ErrNegativeSqrt(-2).Error() returns "cannot Sqrt negative number: -2".</br>
Note: a call to fmt.Sprint(e) inside the Error method will send the program into an infinite loop. You can avoid this by converting e first: fmt.Sprint(float64(e)) . Why?</br>
Change your Sqrt function to return an ErrNegativeSqrtvalue when given a negative number.

exercise-errors.go

package main

import (
    "fmt"
)

type ErrNegativeSqrt float64

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

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

    z := 1.0
    for i := 0; i < 10; i++ {
        z = z - (z*z - x)/(2*z);
    }

    return z, nil
}

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

Note:
上述代码如果直接运行的话会导致infinite loop,因为 fmt.Sprintf("cannot Sqrt negative number: %v", e)会不断调用e.Error()转换成string
所以fmt.Sprintf("cannot Sqrt negative number: %v", e)应改为fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))orfmt.Sprintf("cannot Sqrt negative number: %f", e)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容