Rust corresponding to option (String)

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?

+4
source share
2 answers

This is a known limitation of rust patterns.

( ==) .as_ref() , String &str .

OTOH , String &str .

:

  • Option<String> Option<&str> : Some(a).as_ref().map(|s| s.as_str()). as_ref() Option<&String> ( ), as_str() &str.

  • : match Some(a) { Some(ref s) if s == "hello" => … }. Some(ref s) String s: &String, if, , .

+3

: https://play.rust-lang.org/?gist=7a1d609ec43797e3fe7591feb5f8c0f9&version=stable

std::String, , &str. , , &str, Option<&str>, Option<String>.

std::String &str, &a[..]. , Option<String>, .

- :

match a {
  Some(ref s) => match &s[..] {
    "hello" => ...,
    _ => ...
  },
  _ => ...
}

" ", , .

Option<String> Option<&str> map. map , , . , , , . Option<String> Option<&String> .

, a.as_ref().map(|s| /* s is type &String */ &s[..]). .

  match os.as_ref().map(|s| &s[..]) {
    Some("hello") => println!("It 'hello'"),
    // Leave out this branch if you want to treat other strings and None the same.
    Some(_) => println!("It some other string"),
    _ => println!("It nothing"),
  }
+2

Source: https://habr.com/ru/post/1691540/


All Articles