gometalinter / errcheck返回有关推迟返回变量的func的警告 [英] gometalinter / errcheck returns a warning on deferring a func which returns a variable

查看:87
本文介绍了gometalinter / errcheck返回有关推迟返回变量的func的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gometalinter errcheck 给我一个关于推迟返回变量的函数的警告。

gometalinter and errcheck return me a warning about deferring a function which returns a variable.

网络请求中的示例:

defer r.Body.Close()

在这种情况下, Close 返回一个错误变量,并且

In this case, Close returns an error variable and it's not checked.

最好的方法/惯用法是将其推迟到另一个函数中吗?

Is the best method / idiomatic to defer it inside another function?

defer func() {
    err := r.Body.Close()
    if err != nil {
        // fmt, panic or whatever
    }
}()


推荐答案

如果推迟函数具有任何返回值,函数完成后将被丢弃(有关更多详细信息,请检查规范:延迟语句)。

If a deferred function has any return values, they are discarded when the function completes (for more details check Spec: Defer statements).

因此检查返回值的唯一方法是存储返回值,并且只有在不延迟函数本身的情况下才有可能,但是另一个调用它的函数。

So the only way to check the return value is to store it, and it is only possible if not the function itself is deferred, but another function that calls it.

一种实现方法是像您一样使用匿名函数,

One way to do it is using an anonymous function as you did, which may be slightly simplified:

defer func() {
    if err := r.Body.Close(); err != nil {
        fmt.Println("Error when closing:", err)
    }
}()

或者您可以为其创建一个辅助函数:

Or you may create a helper function for it:

func Check(f func() error) {
    if err := f(); err != nil {
        fmt.Println("Received error:", err)
    }
}

并使用它:

defer Check(r.Body.Close)

当然可以多次使用辅助功能,例如:

The helper function of course can be used multiple times, e.g.:

defer Check(r.Body.Close)
defer Check(SomeOtherFunc)

您还可以为其创建一个修改后的帮助程序功能,该功能可以接受多个功能:

For which you may also create a modified helper function, which may accept multiple functions:

func Checks(fs ...func() error) {
    for i := len(fs) - 1; i >= 0; i-- {
        if err := fs[i](); err != nil {
            fmt.Println("Received error:", err)
        }
    }
}

并使用它:

defer Checks(r.Body.Close, SomeOtherFunc)

请注意,我故意在 Checks中使用了向下循环)来模仿延后函数执行的先进先出性质,因为最后一个推迟将首先执行,因此使用向下循环,将首先执行传递给 Checks()的最后一个函数值。

Note that I intentionally used a downward loop in Checks() to mimic the first-in-last-out nature of the execution of deferred functions, because the last defer will be executed first, and so using a downward loop the last function value passed to Checks() will be executed first.

这篇关于gometalinter / errcheck返回有关推迟返回变量的func的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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