Go中有什么与finally()相反的init()吗? [英] Is there something like finally() in Go just opposite to what init()?

查看:193
本文介绍了Go中有什么与finally()相反的init()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go中是否有某些东西与包内的init()正好相反?

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

推荐答案

Go团队之前对此进行了讨论,结论是不增加对此的支持. 引用Minux :

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

就个人而言,我更喜欢这样的样式:程序退出的处理方式与程序崩溃完全相同. 我相信,无论您多么努力,程序在某些无法预料的情况下仍然会崩溃 情况例如,内存不足会导致任何运行良好的Go程序崩溃, 你对此无能为力.因此最好为他们设计. 如果您遵循此步骤,则不会感到需要清理atexit(因为当您的程序 崩溃,atexit无法正常工作,因此您根本无法依赖它.

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:

如果您想在 CTRL + C 终止程序时执行某些操作(

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

Golang:是否有可能在"defer"窗口中捕获Ctrl + C信号并运行清除功能.时尚吗?

还要注意,您可以为指针值注册一个终结器函数.当垃圾收集器找到带有关联的终结器的无法访问的块时,它将清除该关联并在单独的goroutine中运行f(x).

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.

您可以使用 runtime.SetFinalizer() 注册这样的终结器,这对您来说可能就足够了,但请注意:

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.

请参见以下示例:

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

输出(进入操场):

2009/11/10 23:00:00 Finalizing &{Bob 20}
2009/11/10 23:00:01 Done

这篇关于Go中有什么与finally()相反的init()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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