Go 中是否有类似 finally() 的东西与 init() 正好相反?
Is there something like finally() in Go just opposite to what init()?
Go 中是否有某些东西与 init()
在包中所做的正好相反?
之前Go团队讨论过这个,结论是不加支持。 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).
但您还有一些选择:
处理CTRL+C
如果你想在你的程序被CTRL+C(SIGINT)终止时做一些事情,你可以这样做,见:
Golang: Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?
对象终结器
另请注意,您可以为指针值注册终结器函数。当垃圾收集器发现一个无法访问的块与关联的终结器时,它会清除关联并在单独的 goroutine 中运行 f(x)
。
您可以使用 runtime.SetFinalizer()
注册此类终结器,这对您来说可能就足够了,但请注意:
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")
}
输出(Go Playground):
2009/11/10 23:00:00 Finalizing &{Bob 20}
2009/11/10 23:00:01 Done
Go 中是否有某些东西与 init()
在包中所做的正好相反?
之前Go团队讨论过这个,结论是不加支持。 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).
但您还有一些选择:
处理CTRL+C
如果你想在你的程序被CTRL+C(SIGINT)终止时做一些事情,你可以这样做,见:
Golang: Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?
对象终结器
另请注意,您可以为指针值注册终结器函数。当垃圾收集器发现一个无法访问的块与关联的终结器时,它会清除关联并在单独的 goroutine 中运行 f(x)
。
您可以使用 runtime.SetFinalizer()
注册此类终结器,这对您来说可能就足够了,但请注意:
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")
}
输出(Go Playground):
2009/11/10 23:00:00 Finalizing &{Bob 20}
2009/11/10 23:00:01 Done