Could someone explain the key differences between os.Exit() and panic() and how they are used in practice in Go?
The key differences are:
os.Exit skips the execution of deferred function.os.Exit, you can specify the exit code.panic is terminating while os.Exit is not. (Seems other answers do not mention this.)If you need to execute the deferred function, you have no choice but panic. (On the other hand, if you want to skip execution of deferred function, use os.Exit.)
If a non-void function is defined in such a way:
return or panicThen you cannot replace panic with os.Exit otherwise the compiler will refuse to compile the program, saying "missing return at end of function". (Go is very dumb here, even log.Panic does not terminate a function.)
Under other conditions:
panic when something really wired happens, e.g. programming logic error.os.Exit when you want an immediate exit, with specified exit code.