Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)
Explain `defer`, `panic`, and `recover`: Execution Order and Named Return Mutations.
senior LevelCode ExampleGraphQL
In Simple Words:
defer: Schedules a function call to execute immediately before the surrounding function returns.- Deferred calls execute in LIFO (Last-In, First-Out) reverse order.
- Arguments to deferred functions are evaluated immediately at declaration time.
- Can read and modify named return values.
panic: Stops ordinary flow, executes deferred calls up the stack, and crashes the program with a stack trace.recover: Catches a panicking goroutine inside a deferred function and restores normal execution. Recover ONLY catches panics in the same goroutine!
go
func safeDivide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered from panic: %v", r)
}
}()
return a / b, nil // If b == 0, panics, recovered by defer!
}