11. Go极简教程 error的使用

习惯使用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的使用)