First of all, whenever you have a question โhow is it used in practiceโ, a good way to start is to search the Go source code (or any sufficiently large base code), and docs for the answers.
Now os.Exit and panic very different. panic used when a program or part of it has reached a state that cannot be restored.
When panic is called, including implicitly at runtime errors, such as indexing a slice out of bounds or rejecting a type assertion, it immediately stops the execution of the current function and starts expanding the goroutine stack, launching any pending functions along the way. If this unwind reaches the top of the goroutine stack, the program dies.
os.Exit used when you need to immediately stop executing a program, without the possibility of restoring or executing a pending cleanup statement, and also return an error code (which other programs can use to report what happened). This is useful in tests, when you already know that after this one test will fail, the other will also fail, so you can just exit. It can also be used when your program has done everything you need, and now you just need to exit, i.e. After printing a help message.
In most cases, you will not use panic (you should return error instead), and you almost never need os.Exit outside of some cases in tests and to quickly os.Exit the program.
Ainar-G Feb 12 '15 at 9:08 2015-02-12 09:08
source share