Beginner - How Do I handle an Option?

I have a function that returns an Option and I'm not sure how to handle it. In another language I would do something like:

let result = functionThatReturnsOption();
if (result.is_error) {
  do_something;
}
else if (anotherFunction(result.value)) {
}
else {
}

If there's a better place for beginner questions, please let me know.
Thanks,

Asking beginner questions here is totally fine.

The most basic approach to work with an Option is by using a match statement. You can find some examples in the book (chapter 6). Reading the book is a good idea to get familiar with the basic features of Rust in general.

So your code would go something like

match function_that_returns_option() {
    None => {
        // do_something
    }
    Some(value) => {
        if another_function(value) {
            
        } else {
            
        }
    }
}

Note that there is also if let.

if let Some(value) = function_that_returns_option() {
    if another_function(value) {
        
    } else {
        
    }
} else {
     // do something
}

In general, with enum types such as Option and Result, I might advise to think pattern match to start. It’s a powerful construct that avoids a series of “narly” if/then statements. Match statements are the “yang” to the constructor’s “ying”; they provide access to the components used to construct the enum value in the first place.

Once you get the idea of matching, where there are only two value types in your enum, the statements that include an if clause “reemerge” as an appealing ergonomic approach. This is true in the if let statement because it unwraps and assigns the inner value etc... when possible, many steps in one.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.