Skip to main content

Error handling with Result and Option

Rust has no exceptions and no `null`. A function that might fail returns `Result<T, E>`, and a value that might be absent is an `Option<T>`. Both are ordinary enums, so the compiler forces you to handle the failing branch.

That sounds tedious until you meet `?`. Putting `?` after a `Result` says "if this failed, return the error from my function too"; otherwise unwrap the value and carry on. One character replaces a whole try/catch pyramid.

`match` is the other half of the story: it is exhaustive, so adding a new error variant makes every incomplete match a compile error rather than a silent bug.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust