Sobes.tech
Middle+

What is a panic in Go? How does a panic differ from a deadlock?

sobes.tech AI

Answer from AI

Panic in Go is a mechanism that occurs when a critical error happens during program execution, such as accessing out-of-bounds of a slice, division by zero, or explicitly calling the panic() function. A panic causes the immediate termination of the current goroutine's normal execution and begins the "stack unwinding" process, calling deferred functions (defer). If the panic is not recovered using recover(), the program will crash.

Deadlock is a situation where one or more goroutines are permanently blocked, waiting for resources or events that will never occur. Unlike a panic, a deadlock does not cause the program to crash, but it stops making progress.

In summary:

  • Panic is an emergency state that stops the program if not handled.
  • Deadlock is a blocking state where the program hangs but does not crash.

Example of a panic:

func main() {
    var s []int
    fmt.Println(s[1]) // will cause a panic: index out of range
}