Rust, Software Development

The Into and Unwrap Methods In Rust

Developers new to Rust probably have encountered the into and unwrap method calls several times in sample codes. At first sight, these calls may appear puzzling to them. So, where do we use these methods? Chances are these methods that are invoked from Option enums and structs that implement the Into (or From) trait.

Into Trait, Into Method

The Into trait is generally for data conversions. For instance, convert a struct instance into an object of a different struct definition. Consider the following sample codes.

Rust Option and Unwrap Method

When we deal with the enum Option, we use the unwrap() method to get the value of the optional value. Consider the following codes.

The codes generate the following output.

The panic is caused by the unwrap() method when the Option has no value. To resolve this, we could use either of the following alternatives.

Modifying the main function, we get the following codes.

Then, the result will be a little different.

If we look at the option.rs, we have these codes.

The unwrap() method simply returns the Option value, if there is any. Otherwise, it returns panics for None. What if we want our Option enum that works the same way?

First, we need to create our enum type.

Second, implement the Default trait for dealing with an empty value.

Third, modify the get_even_numbers and use the new enum.

Using the original main function, it generates the following output.

In case the enums are in a separate module and are using the #[non_exhaustive], please consider reading Using #[non_exhaustive] for Non-exhaustive Enums.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like