Memorising Rust Patterns


When learning Rust, it’s tempting to memorise snippets of code the way you might memorise incantations: copy, paste, hope it works. That approach fails quickly in Rust. What does work is memorising patterns of thought, and one of the most useful early patterns is the dance between Result, Option, .ok() and .ok_or().

A good example is this small function:

fn parse_positive(s: &str) -> Result<i32, &'static str> {
    s.parse::<i32>()
        .ok()
        .filter(|n| *n > 0)
        .ok_or("not a positive number")
}

You should memorise this — but not as a string of symbols.

What you’re really memorising is a story:

Try something that might fail.
Decide the reason for failure doesn’t matter (if it indeed does fail).
Apply validation (e.g. filter or map).
Turn “nothing” back into a proper error.

That’s the important part.

The call to .ok() is you explicitly saying: “I don’t care why this failed.”
The error is discarded on purpose. No panic, no logging, no ceremony — just absence.

ok-or

Option

Once you’re in Option land, methods like filter, map, and and_then become available. This is where validation shines. You keep what you want, silently drop what you don’t, and move on.

Then .ok_or(...) flips the switch back. Now absence does matter again. By supplying an error ("not a positive number" in this case), you turn None into something that can be returned and handled upstream.

A key detail is how ok_or works with ?. Once you call .ok_or(...), you have a Result again, so it is common to immediately follow it with ?. This says: if the result is Ok, keep going; if it is Err, return the error immediately. That makes your code clean and idiomatic, and it keeps the error handling consistent without wrapping results in nested Result<Result<...>> types.

This pattern — Result → Option → Result — is everywhere in real Rust code. You’ll use it for parsing user input, environment variables, config files, CLI arguments, and any situation where you want to be forgiving at first and strict later.

The key point is this:
don’t memorise syntax, memorise intent.

If you understand that .ok() opts out of error handling, and .ok_or() opts back in, the code almost writes itself. If you ever find yourself thinking “I’ll just wrap this in Ok(...)”, that’s a warning sign you’ve lost the flow.

Avoid match

These methods let you avoid match most of the time and keep your code clean and expressive.

The pattern you’re learning (Result → Option → Result) often uses:

  • .ok()
  • .filter()
  • .map()
  • .and_then()
  • .ok_or()

So yes — memorise this example : as a pattern of control flow, not a magic spell.