Rust Lang

Convert Option Type to Result and the Result Type to Option in Rust

When working with various aspects of a program, we may need to determine whether the operation is a success or a failure. This can allow us to capture that value and take action such as displaying the error message to the user or capturing the return value.

In Rust, two main types represent the values that may or may not be present or the operation state like success or failure. The “Option” and “Result” types allow us to store this information.

In Rust, the “Option” type allows us to store the value that may or may not exist, while the “Result” type stores an operation that may or may not succeed.

Sometimes, we may encounter a scenario where we need to convert between “Option” and “Result”. This tutorial explores how to convert the “Option” to “Result” and the “Result” to “Option” using the Rust programming language.

Convert the Option Type to Result Type

In Rust, the “Option” type stores two values: “Some(value)” and “None”. If we have an option type and we wish to convert it into a Result type, we need to specify an error message that is returned if the “Option” is “None”.

The “Option” type provides us with two methods of converting an “Option” type to a “Result” type. These methods are the “ok_or” and the “ok_or_else”.

Rust Ok_Or Method

The “ok_or” method takes an argument which is similar to the error value of the “Result” type. If the “Option” is “Some”, the function returns a result with the option’s value. Otherwise, if the “Option” is “None”, the method returns a result with the error value that is provided as the argument.

Consider the following example code:

fn option_to_result(value: Option<i32>) -> Result<i32, &'static str> {
   value.ok_or("Value not found.")
}

 

In the previous example, the value is an Option<i32> type. We then call the “ok_or” method on the value and pass in the error message as the argument. If the value is “Some(x)”, the method returns an Ok(x). Otherwise, if the value is “None”, the “ok_or” method returns an Err(“Value not found!”) message.

Rust Ok_Or_Else Method

The “ok_or_else” method works similarly to the “ok_or” method. However, it takes a closure that returns the error value. This is very useful when you need to act to generate the error value.

The following example demonstrates how to work with the “ok_or_else” method:

fn option_to_result(value: Option<i32>) -> Result<i32, &'static str> {
   value.ok_or_else(|| "Value not found.".to_string())
}

 

In this case, we call the closure || “Value not found.” to_String() if the value is “None”. The closure returns the string which is used as the error value of the “Result”.

Convert the Result Type to Option Type

Unlike the conversion of “Option” to “Result”, when you have a “Result” type, we can convert it to an option by simply extracting the value from the “Result” if it’s an Ok or return “None” if it’s an Err.

We can use the ok() method from the “Result” type to accomplish this. If the result is Ok, the method returns an option which holds the value of the result. Otherwise, if the result is Err, the method returns “None”.

Example:

fn result_to_option(result: Result<i32, &'static str>) -> Option<i32> {
   result.ok()
}

 

This should convert the “Result” to an “Option”.

NOTE: It is important to understand that although the conversions are possible and allowed by the compiler, they should be used with caution. Sometimes, it may be more efficient and safe to handle the “Option” and “Result” types directly rather than converting them.

Conclusion

You now learned about the Rust “Option” and “Result” types to represent a value that may or may not exist or an action that may or may not succeed. We also learned how to convert an “Option” type to a “Result” type and vice versa.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list