errors _ golang

本文介绍了Go语言中处理错误的独特方式,通过使用明确的返回值来传递错误信息,并对比了与其他语言如Java和Ruby中异常处理的不同。通过示例展示了如何自定义错误类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In Go it's idiomatic to communicate errors via an explicit, separate return value. this constrasts errors via an explicit, separate return value. This constrasts with the exceptions used in languages like Java and Ruby and the overloaded single result / error value sometimes used in C. Go's approach makes it easy to see which functions return errors and to handle them using the same language constructs employed for any other, non-error tasks

package main

import (
    "errors"
    "fmt"
)

func f1(arg int) (int, error) {
    if arg == 42 {
        return -1, errors.New("can't work with 42")
    }
    return arg + 3, nil
}

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 {
        return -1, &argError{arg, "can't work with it"}
    }

    return arg + 3, nil
}

func main() {

    for _, i := range []int{7, 42} {
        if r, e := f1(i); e != nil {
            fmt.Println("f1 failed : ", e)
        } else {
            fmt.Println("f2 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)
        }
    }

    _, e := f2(42)
    if ae, ok := e.(*argError); ok {
        fmt.Println(ae.arg)
        fmt.Println(ae.prob)
    }
}
f2 worked :  10
f1 failed :  can't work with 42
f2 worked :  10
f2 failed :  42 - can't work with it
42
can't work with it

总结 :

  1 : golang 的 内建函数 builtin.go 里面定义了 type error interface{ Error() string }; 实现了这个方法就是 自定义的 Error(查看源码 command + shift + 鼠标左键)

  2 : ....

转载于:https://www.cnblogs.com/jackkiexu/p/4338023.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值