Puzzles with `match`

I've found some interesting thing:

fn main() {
    let a = String::new();
    match a/*Guessing what to add here (1 function call)*/ {
        "" => (),
        _ => ()
    }
    let b = Some(String::new());
    match b/*Guessing what to add here (1 function call)*/ {
        Some("") => (),
        _ => ()
    }
    let c = Err::<String, String>(String::new());
    match c/*Guessing what to add here (1 function call may not sufficient)*/ {
        Ok("") => (),
        Err("") => (),
        _=>()
    }
}

All the three guessing are different, and it seems that there is no general answer for all the 3 guessings.

Maybe we should provide better ways for match T<String> with T<&str>, but for now I could only provide puzzles like this.

Answer:
fn main() {
    let a = String::new();
    match a.as_ref() {
        "" => (),
        _ => ()
    }
    let b = Some(String::new());
    match b.as_deref() {
        Some("") => (),
        _ => ()
    }
    let c = Err::(String::new());
    match c // Result
        .as_deref() // Result<&str, String>
        .map_err(core::ops::Deref::deref) // Result<&str, &str>
    {
        Ok("") => (),
        Err("") => (),
        _=>()
    }
}
3 Likes

I find this variation slightly more intuitive:

Alternative to #3
        match c.as_deref().map_err(String::as_ref) {
1 Like