英文:
Do I need to use os.Exit(0) when succefully terminanting an application in Go?
问题
我最近发现了Go标准库中的os.Exit函数,并且在一些教程中也见过它。
由于Go的func main()
函数不返回任何值,所以在main()
函数中使用return
而不是os.Exit(0)
是否有关系呢?
我知道os.Exit
还会忽略Go代码中的defer
语句,但在这种情况下,我只想知道对于操作系统来说,return
和os.Exit(0)
之间是否没有区别。
英文:
I`ve recently discovered the os.Exit function on Go standard library, and I`ve seen it in some tutorials as well.
Since the Go`s func main()
does not return any value, does it matter if I simply use return
in the main()
function isteand of os.Exit(0)
?
I know os.Exit
also ignores defers
in Go code, but in this case I just want to know if there`s no difference for the OS between return
and os.Exit(0)
.
答案1
得分: 4
你描述的区别是正确的,os.Exit(0)
会立即结束程序,忽略任何延迟执行的操作。使用return
语句,程序将以默认的代码0结束。
在defer语句之外,基本上没有区别。
英文:
the difference you described is correct, os.Exit(0)
finishes the program immediately, ignoring any defers. With return
your program will finish with default code 0.
test-exit$ cat main.go
> package main
>
> func main() {
> return
> }
test-exit$ go run main.go
test-exit$ echo $? // shows status code of last executed command
> 0
So outside the defer case there is basically no difference.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论