βœ…
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.

</div> Because `"42"` really is a number, we got `Ok(42)` and printed the happy message. If we had used `"abc"`, the box would hold `Err` instead, and we'd print the "oops" line. No crash β€” just a calm choice! 😊
Think of it like this… A Result is like a wrapped present. Ok means there's a gift inside 🎁, and Err means there's a note saying "sorry, this didn't work." Either way, you open it and find out β€” you don't get surprised by an explosion.
## A handy shortcut: the ? mark Sometimes you get a Result and you think: "if this failed, just pass the problem up to whoever called me." Rust has a tiny shortcut for that β€” the question mark `?`.
Ferris says: Writing ? after something means "give me the value if it worked, but if it failed, send the error back up and stop here." It saves you from writing a big match every time. πŸ¦€
Try this! Change let text = "42"; to a number you like, such as "7". Press β–Ά Run and watch the happy message change!
## Quick quiz

What does a Result hold?

Exactly! A Result is one box with two possible insides: success or a problem. βœ…

You learned… A Result is Ok(value) for success or Err(problem) for an oops, you can peek inside with match, and ? passes errors up the chain. But when should you use Result, and when should you panic? Find out next in Should I Panic? πŸ€”