Don't unwrap options: There are better ways (2024)
Published on: 2025-07-12 02:58:27
I noticed that handling the None variant of Option without falling back on unwrap() is a common papercut in Rust. More specifically, the problem arises when you want to return early from a function that returns a Result if you encounter None .
It has been discussed a million times already, but, surprisingly, not even the Rust book mentions my favorite approach to handling that, and many forum posts are outdated.
With a bit of practice, robust handling of None can become as easy as unwrap() , but safer.
Jump to the end if you’re in a hurry and just need a quick recommendation.
Very commonly, people write code like this:
fn get_user ( ) -> Option < String > { None } fn get_user_name ( ) -> Result < String > { let user = get_user ( ) ? ; Ok ( user ) }
The goal here is to return early if you encounter None in an Option , so they use the ? operator to propagate errors.
Alas, this code doesn’t compile. Instead, you get a dreaded error message:
error [ E0277 ] : the ` ? ` operator can
... Read full article.