I can match String in rust straightforwardly, as we can see in this example.
let a = "hello".to_string();
match &a[..] {
"hello" =>{
println!("Matches hello");
},
_ => panic!()
}
But, if I have an option type, it probably won't work.
match Some(a){
Some("hello") => {
println!("Matches some hello");
}
_=> panic!()
}
because the types do not match.
19 | Some("hello") => {
| ^^^^^^^ expected struct `std::string::String`, found reference
|
= note: expected type `std::string::String`
found type `&'static str`
I can’t do the trick [..]
because we have it Option
. The best I've come up with so far:
match Some(a) {
Some(b) => {
match(&b[..]) {
"hello" => {
println!("Matches some, some hello");
},
_=> panic!()
}
},
None =>{
panic!()
}
}
which works, but terrible for this verbosity.
In this case, my code is just an example. I do not control the creation of either String or Some (String), so I cannot change this type in reality, as I could do in my example.
Any other options?
source
share