error--

第一次看这个,觉的比较难懂,后续需要继续看

package main

 
import "errors"
import "fmt"
 
//By convention, errors are the last return value and have type error, a built-in interface.
 
func f1(arg int) (int, error) {
    if arg == 42 {
        //errors.New constructs a basic error value with the given error message.
        return -1, errors.New("can't work with 42")
    }
    //A nil value in the error position indicates that there was no error.
    return arg + 3, nil
}
 
//It’s possible to use custom types as errors by implementing the Error() method on them. Here’s a variant on the example above that uses a custom type to explicitly represent an argument error.
 
type argError struct {
    arg  int
    prob string
}
 
func (e *argError) Error() string {
    return fmt.Sprintf("%d - %s", e.arg, e.prob)
}
func f2(arg int) (int, error) {
    if arg == 42 {
        //In this case we use &argError syntax to build a new struct, supplying values for the two fields arg and prob.
 
        return -1, &argError{arg, "can't work with it"}
    }
    return arg + 3, nil
}
func main() {
    //The two loops below test out each of our error-returning functions. Note that the use of an inline error check on the if line is a common idiom in Go code.
 
    for _, i := range []int{7, 42} {
        if r, e := f1(i); e != nil {
            fmt.Println("f1 failed:", e)
        } else {
            fmt.Println("f1 worked:", r)
        }
    }
    for _, i := range []int{7, 42} {
        if r, e := f2(i); e != nil {
            fmt.Println("f2 failed:", e)
        } else {
            fmt.Println("f2 worked:", r)
        }
    }
    //If you want to programmatically use the data in a custom error, you’ll need to get the error as an instance of the custom error type via type assertion.
 
    _, e := f2(42)
    if ae, ok := e.(*argError); ok {
        fmt.Println(ae.arg)
        fmt.Println(ae.prob)
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值