rust option get value
To get the value of an option in Rust, you can use the Option::unwrap
method. This method returns the value inside the Some
variant of the Option
if it exists, and panics if the Option
is None
. Here's an example:
fn main() {
let option_value: Option<i32> = Some(42);
let unwrapped_value = option_value.unwrap();
println!("The unwrapped value is: {}", unwrapped_value);
}
In this example, option_value
is an Option
that contains the value 42
. By calling unwrap
on option_value
, we extract the value 42
from the Some
variant and assign it to unwrapped_value
. Finally, we print the unwrapped value, which will output The unwrapped value is: 42
.
It's important to note that using unwrap
can lead to a panic if the Option
is None
. If you want to handle the case where the Option
is None
without panicking, you can use methods like Option::expect
or Option::map
to provide custom error handling or perform operations on the value.