dongzhi9032 2016-11-03 09:22
浏览 33
已采纳

gometalinter / errcheck返回有关推迟返回变量的func的警告

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

Example in a web request:

defer r.Body.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
    }
}()
  • 写回答

1条回答 默认 最新

  • dshdb64088 2016-11-03 09:37
    关注

    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)
        }
    }
    

    And using it:

    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)
            }
        }
    }
    

    And using it:

    defer Checks(r.Body.Close, SomeOtherFunc)
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置