drj14664 2019-08-17 06:51
浏览 93
已采纳

其他函数可以共享单个defer func()吗?

I see a lot of examples using defer func() inside of a function. Is there a way to keep from repeating it in various places and call it like a normal function?

In this example (and many others) the defer function is nested inside of another function:

package main

import (
    "fmt"
    "os"
)

func main() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Fprintf(os.Stderr, "Exception: %v
", err)
            os.Exit(1)
        }
    }()

    file, err := os.Open(os.Args[1])
    if err != nil {
        fmt.Println("Could not open file")
    }

    fmt.Printf("%v", file)
}

Is there a way to move the defer func() outside of main() so it can be used by other functions as well?

  • 写回答

1条回答 默认 最新

  • douxuqiao6394 2019-08-17 06:57
    关注

    You can defer any function. Where that function is defined isn't important.

    This is perfectly valid:

    func foo() {
        // Do foo
    }
    
    
    func bar() {
        defer foo()
        // Do something before foo
    }
    
    func baz() {
        defer foo()
        // Do something else before foo
    }
    

    But in this case foo() will be called once for each invocation of bar() and baz(). It's not "shared", except in the sense that you don't have to re-write an anonymous function multiple times.

    Probably the most common example of this is calling Close() in a defer statement:

    func foo() error {
        f, err := os.Open(...)
        if err != nil {
            return err
        }
        defer f.Close() // "Close()" is obviously not defined here
        // do something with f
    }
    

    TL;DR;

    You cannot share a defer statement across functions. But as with any other function, the function invoked by defer, can be called from multiple places.

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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?