18 错误处理
package main
import (
"fmt"
"math"
)
func sqrt(n float64) (float64, error) {
if n < 0 {
return 0, fmt.Errorf("invalid argument '%f', must be >= 0", n)
}
return math.Sqrt(n), nil
}
func printSqrt(n float64) {
if res, err := sqrt(n); err == nil {
fmt.Printf("sqrt of %f is %f\n", n, res)
} else {
fmt.Printf("sqrt of %f returned error '%s'\n", n, err)
}
}
func main() {
printSqrt(16)
printSqrt(-16)
}
// 输出结果
// sqrt of 16.000000 is 4.000000
// sqrt of -16.000000 returned error 'invalid argument '-16.000000', must be >= 0'译者注:error源码解读
error源码解读最后更新于