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

其他函数可以共享单个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?

图片转代码服务由CSDN问答提供 功能建议

我看到了很多在函数内部使用defer func()的示例。 有没有办法避免在各个地方重复它并像普通函数一样调用它?

在此示例(以及许多其他示例)中,defer函数嵌套在另一个函数内:< / p>

 包main 
 
import(
“ fmt” 
“ os” 
)
 
func main(){
延迟func(){
 如果err:= recovery();  err!= nil {
 fmt.Fprintf(os.Stderr,“ Exception:%v 
”,err)
 os.Exit(1)
} 
}()
 
文件,err:  = os.Open(os.Args [1])
,如果出错!= nil {
 fmt.Println(“无法打开文件”)
} 
 
 fmt.Printf(“%v”,文件 )
} 
   
 
 

是否可以将defer func()移动到main()之外,以便其他功能也可以使用它?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题