有没有办法直接简化 Result<String, VarError> 中 Ok("VAL") 的匹配

Pat*_*zke 0 rust

我有这个代码:

let routes = match env::var("ENV") {
    Ok(el) => {
        if el == "PROD" {
            routes![upload_image]
        } else {
            routes![get_token, callback, form, upload_image, refresh]
        }
    },
    _ => routes![get_token, callback, form, upload_image, refresh],
};
Run Code Online (Sandbox Code Playgroud)

该函数env::var返回一个Result<String, VarError>. 我想知道我上面的代码是否可以简化如下:

let routes = match env::var("ENV") { // E: mismatched types: this expression has type `Result<std::string::String, VarError>
    Ok("PROD") => { // E: mismatched types: expected `String`, found `&str`
       routes![upload_image]
    },
    _ => routes![get_token, callback, form, upload_image, refresh],
};
Run Code Online (Sandbox Code Playgroud)

String但是,我收到有关“不匹配类型:预期,发现”的错误&str。有没有办法简化这段代码?

caf*_*e25 5

String 最简单的解决方案可能是仅使用derefsstr和 call 的事实Result::as_deref

fn main() {
    let routes = match std::env::var("ENV").as_deref() {
        Ok("PROD") => {
           "prod_routes"
        },
        _ => "fallback_routes",
    };
}
Run Code Online (Sandbox Code Playgroud)