rustborrow-checker

Converting Option<String> to Option<&str> in match statement


I have a function that takes in a Option<&str>, but my var is currently a Result<String> that I have converted to Option<String> in a match statement.

let geom_source= std::fs::read_to_string(folder.join("shader.geom"));
let geom_source:Option<String> = match geom_source {
    Ok(s) => Some(s),
    Err(_) => None,
};

I have tried with

let geom_source= std::fs::read_to_string(folder.join("shader.geom"));
let geom_source:Option<String> = match geom_source {
    Ok(s) => Some(&s),
    Err(_) => None,
};

but the compiler gives an error.


Solution

  • If you want an Option<&str>, you'll need to change the type-annotation for geom_source from Option<String> to Option<&str>, and match on a reference instead of moving the value:

    let geom_source = std::io::Result::Ok(String::from("foo")); // Dummy
    
    let geom_source: Option<&str> = match &geom_source {
        Ok(s) => Some(s),
        Err(_) => None,
    };
    

    It's probably more appropriate to simply use Result::ok() instead of a match to convert the io::Result<String> to an Option<String>, and use Option::deref() to create an Option<&str> whenever needed:

    fn foo(_s: Option<&str>) {}
    
    fn main() {
        let geom_source = std::io::Result::Ok(String::from("foo")).ok();
        foo(geom_source.as_deref());
    }