美文网首页
11. Go极简教程 error的使用

11. Go极简教程 error的使用

作者: 超级大柱子 | 来源:发表于2018-06-03 03:37 被阅读24次

    习惯使用error类型, 并且做好判断, 能很大程度上提高程序的健壮性

    养成习惯, 不然等运行时错误不好捕获

    package main
    
    import (
        "errors"
        "log"
    )
    
    // Sqrt -
    func Sqrt(x float64) (float64, error) {
        if x < 0 {
            return 0, errors.New("x小于0了")
        }
        return x * x, nil
    }
    
    func main() {
        if v, err := Sqrt(-5); err != nil {
            log.Println(err)
        } else {
            log.Println(v)
        }
    }
    
    

    参考资料:
    http://go-tour-zh.appspot.com/

    Go极简教程 继续阅读( 目录)

    相关文章

      网友评论

          本文标题:11. Go极简教程 error的使用

          本文链接:https://www.haomeiwen.com/subject/qlidsftx.html