When to panic in Go versus Rust
error philosophy and panic boundaries.
both reserve panic for unrecoverable bugs and use values, Result or error, for expected failures; Rust's type system pushes more cases to Result.
WHAT THIS TESTS Whether you understand that panic is for unrecoverable programmer errors and that both languages favor returning error values for expected failures, with Rust's types shifting the boundary.
A GOOD ANSWER COVERS In both languages, expected, recoverable failures should be values: Go returns an error as the last result and callers check it; Rust returns Result or Option and callers handle the variants. Panic is reserved for situations that indicate a bug or a broken invariant the program cannot sensibly continue past, such as an index out of bounds or a violated precondition. Go panics unwind the stack and can be caught with recover, typically only at a boundary like an HTTP handler to convert a bug into a 500 rather than crashing the server. Rust panics unwind or abort and are not meant as routine control flow; functions like unwrap and expect panic and are appropriate in tests, prototypes, or when a None or Err truly cannot happen. Rust's type system pushes more failures into Result, so well-written Rust panics less than equivalently naive code.
COMMON WRONG ANSWERS Using panic for validation or expected user errors. Saying recover makes panic a normal error channel in Go. Claiming Rust never panics. Treating unwrap as production-quality default.
LIKELY FOLLOW-UPS When is unwrap acceptable. How does recover work and where to place it. What is unwinding versus abort. How does the question mark operator propagate Result.
ONE CONCRETE EXAMPLE Parsing user input that may be malformed: idiomatic Rust returns a Result and uses the question mark operator to propagate it, never panicking on bad input; a quick prototype might unwrap and panic, which would be a returned error in real code. In Go, the parser returns an error you check; you would not panic on bad input, but a guard against an impossible nil that signals a bug might panic and be recovered at the request boundary so one bad request does not take down the process.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.