'returns a value referencing data owned by the current function' on match with `&str`

I have this code

enum Enum {
    V1,
    V2
}

fn decoded() -> Result<Enum, String> {
    // found from external function
    let string = Some(String::from("v1")); // Return type Option<String>
    
    // how to match String with &str
    match string.map(|s| s.as_str()) {
        Some("v1") => Ok(Enum::V1),
        Some("v2") => Ok(Enum::V1),
        Some(v) => Err(format!("Unrecognized {:?}", v).into()),
        None => Err("Unexpected null".into())
    }
}

fn main() {
    decoded();
}

The thing is, although I am matching on &str, I am returning completely different type. I guess rust is not able to deduce that.

Playground link: Rust Playground

The error is not about your decoded function. It's about the map callback function.

You need to change string.map(|s| s.as_str()) to string.as_ref().map(|s| s.as_str()), which can be abbreviated as string.as_deref().

That's because map() on Option<String> is expected to destroy the String in the process (it maps one type to another, and after map the old type ceases to exist).

By adding as_ref() you make it Option<&String> and destroying of &String doesn't do anything, so the string data keeps existing.

1 Like

Perfect. Thank you, @kornel. It works now!

That's because map() on Option<String> is expected to destroy the String in the process (it maps one type to another, and after map the old type ceases to exist).

This being the key phrase.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.