How do I match
on an enum reference? I am using a dependency that returns a reference to an enum and I need to read the value the enum contains. In the following example, the thing I care about is assigning final_val
with x
:
fn main() {
let test_string = String::from("test");
let option: std::option::Option<String> = Some(test_string);
let ref_option = &option;
let final_val = match ref_option {
Some(x) => x,
_ => String::from("not Set"),
};
println!("{:?}", final_val);
}
If I follow what the compiler suggests and add a &
to the type Some
and ref x
:
fn main() {
let test_string = String::from("test");
let option: std::option::Option<String> = Some(test_string);
let ref_option = &option;
let final_val = match ref_option {
&Some(ref x) => x,
_ => String::from("not Set"),
};
println!("{:?}", final_val);
}
I get the following error, which I don't know how to resolve:
error[E0308]: match arms have incompatible types
--> src\main.rs:6:21
|
6 | let final_val = match ref_option
| _____________________^
7 | | {
8 | | &Some(ref x) => x,
9 | | _ => String::from("not Set" ),
| | ------------------------ match arm with an incompatible type
10 | | };
| |_____^ expected reference, found struct `std::string::String`
|
= note: expected type `&std::string::String`
found type `std::string::String`