β
World 9 Β· Oops! Handling Mistakes
Success or Oops (Result)
Panicking and stopping everything is a big deal. Most of the time, when something goes wrong, you donβt want to crash β you just want to say βhmm, that didnβt work, letβs handle it.β Rust has a perfect tool for that: Result. β
A Result is like a sealed box that holds one of two things: either a success or
an oops. You open it carefully to see which one you got.
The Big Idea
A Result is either
Ok(value) when things worked, or
Err(problem) when they didn't. It's used for jobs that might fail β
so your program can decide what to do instead of crashing.
Turning text into a number
Hereβs a job that might fail: turning text into a number. The text "42" can become the
number 42. But text like "abc" is not a number at all! So this job returns a Result.
We use match to peek inside the box and react to each case.