dtnd30892 2015-06-04 09:44
浏览 83
已采纳

Go中有什么与finally()相反的init()吗?

Is there something in Go which do just opposite to what init() do inside a package?

  • 写回答

1条回答 默认 最新

  • drcmue4619 2015-06-04 10:03
    关注

    This was discussed before by the Go team, and the conclusion was not to add support for it. Quoting minux:

    Personally, I prefer the style where program exit is handled exactly same as program crash. I believe no matter how hard you try, your program can still crash under some unforeseen situations; for example, memory shortage can bring any well-behave Go program to a crash, and there is nothing you can do about it; so it's better to design for them. If you follow this, you won't feel the need for atexit to clean up (because when your program crash, atexit won't work, so you simply can't depend on it).

    But you still have some options:

    Handling <kbd>CTRL+C</kbd>

    If you want to do something when your program is terminated by <kbd>CTRL+C</kbd> (SIGINT), you can do so, see:

    Golang: Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

    Object Finalizer

    Also note that you can register a finalizer function for a pointer value. When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and runs f(x) in a separate goroutine.

    You can register such finalizer with runtime.SetFinalizer() which might be enough for you, but note:

    There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program.

    See this example:

    type Person struct {
        Name string
        Age  int
    }
    
    func main() {
        go func() {
            p := &Person{"Bob", 20}
            runtime.SetFinalizer(p, func(p2 *Person) {
                log.Println("Finalizing", p2)
            })
            runtime.GC()
        }()
    
        time.Sleep(time.Second * 1)
        log.Println("Done")
    }
    

    Output (Go Playground):

    2009/11/10 23:00:00 Finalizing &{Bob 20}
    2009/11/10 23:00:01 Done
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?