How do we know when to use unwrap and when not to?

Are there any rules or best practices to understand where the unwrap() method is required or should be used?


To understand the usage of unwrap(), let’s take the example of the following code snippet:

fn divide(numerator: u64, denominator: u64) -> Option<u64> {
    if denominator == 0 {
    } else {
        Option::Some(numerator / denominator)

fn main() {
    let result = divide(6, 2);
    match result {
        // The division was valid
        Option::Some(x) => std::logging::log(x),
         // The division was invalid
        Option::None => std::logging::log("Cannot divide by 0"),

The divide() functions returns an Option type. Typically, to store the result of the divide(6, 2) operation, you would have to unwrap the result using result.unwrap(). However, it would result in a stock revert in the case of a None value. In some cases, this should suffice. In the case that you would like to choose how to handle the None case yourself, you would use match.

As opposed to unwrap(), the match keyword, as used in the example above, lets you throw an error of your choice in the case of a None value.


To further what @VeeEm wrote above, I will add that using match on an Option primarily gives you more flexibility in handling the variants. You may want to return a Result::Err with an error more appropriate for the current context, or you might want to take some other action based on the None variant such as substituting an appropriate default value.

In general, this falls under the umbrella of “Error Handing”. As Sway is largely based on Rust, we can take advantage of excellent Rust documentation on the topic; the Rust book is a great starting point: Error Handling - The Rust Programming Language


This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.