简体   繁体   中英

Do I need to use os.Exit(0) when succefully terminanting an application in Go?

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) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM