For a real-world example of panic and recover, see the json package from the Go standard library. It encodes an interface with a set of recursive functions. If an error occurs when traversing the value, panic is called to unwind the stack to the top-level function call, which recovers from the panic and returns an appropriate error value
That's panic and recover used for control flow, just like might use exceptions in other languages.
Looks like panic has at least two purposes, depending on whether you recover or not?
However, this is a poor example and a misuse of panic and recover as exceptions.
See https://golang.org/doc/effective_go.html#panic
The example will be invalid soon with the release of go 1.11 as well. The
panic/recover was removed from the unmarshal code. See master's
So no, panic and recover are not meant to be used as control flow. Yes, they CAN be used that way. I also CAN use pythons `eval` a lot, use a scripting language as my command line interpreter, or make an apple-pie with onions and garlic.
As for why `recover` exists in the first place: Packages should have the ability to stop internal panics. There are various reasons for that, some worse than other. For example it is probably okay if a package doing sensor readouts recovers from a division by zero and replaces it with an error saying that the sensor value makes no sense.
A quick google turns up https://go.dev/blog/defer-panic-and-recover, which says:
For a real-world example of panic and recover, see the json package from the Go standard library. It encodes an interface with a set of recursive functions. If an error occurs when traversing the value, panic is called to unwind the stack to the top-level function call, which recovers from the panic and returns an appropriate error value
That's panic and recover used for control flow, just like might use exceptions in other languages.
Looks like panic has at least two purposes, depending on whether you recover or not?