去:从延期返回 [英] Go: returning from defer

查看:165
本文介绍了去:从延期返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  func getReport(文件名字符串)

我想从函数返回一个错误, (rep报告,错误错误){
rep.data = make(map [string] float64)

推迟func(){
如果r:= recover(); r!= nil {
fmt.Println(在f中恢复,r)
err,_ = r。(错误)
返回nil,err
}
}()
panic(Report format not recognized。)
// getReport函数的其余部分,它可以尝试超出边界访问切片
...
}

我似乎误解了恐慌和延期的概念。任何人都可以启发我吗?

解决方案

在延迟函数中,您可以更改返回的参数,但不能返回新集。因此,对您所拥有的产品进​​行简单的更改将会使其发挥作用。



您写的内容还存在另一个问题,即您使用 string ,但在你的类型断言中需要一个错误



Play

 推迟func(){
如果r:= recover(); r!= nil {
fmt.Println(在f中恢复,r)
//找出错误是什么,并设置err
switch x:= r。(type) {
大小写字符串:
err = errors.New(x)
大小写错误:
err = x
默认值:
err = errors.New 未知恐慌)
}
//无效rep
rep = nil
//返回已修改的错误和
}
}()


I want to return an error from a function if it panics (in Go):

func getReport(filename string) (rep report, err error) {
    rep.data = make(map[string]float64)

    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
            err, _ = r.(error)
            return nil, err
        }
    }()
    panic("Report format not recognized.")
    // rest of the getReport function, which can try to out-of-bound-access a slice
    ...
} 

I appear to have misunderstood the very concept of panic and defer. Can anybody enlighten me?

解决方案

In a deferred function you can alter the returned parameters, but you can't return a new set. So a simple change to what you have will make it work.

There is another problem with what you wrote, namely that the you've paniced with a string but are expecting an error in your type assertion.

Here is a fix for both of those (Play)

defer func() {
    if r := recover(); r != nil {
        fmt.Println("Recovered in f", r)
        // find out exactly what the error was and set err
        switch x := r.(type) {
        case string:
            err = errors.New(x)
        case error:
            err = x
        default:
            err = errors.New("Unknown panic")
        }
        // invalidate rep
        rep = nil
        // return the modified err and rep
    }
}()

这篇关于去:从延期返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆