为 HashMap<_, String> 返回默认 &str

Returning a default &str for HashMap<_, String>

我有一个HashMap<_, String>,我想为其获取相应的键值或return 默认字符串。最明显的方法是只使用 unwrap_or,但这会因类型错误而失败:

error[E0308]: mismatched types
  --> src/main.rs:11:44
   |
11 |     let val = hashmap.get(key).unwrap_or("default");
   |                                            ^^^^^^^^^ expected struct `std::string::String`, found str
   |
   = note: expected type `&std::string::String`
              found type `&'static str

我可以使用像 if let Some(val) = hashmap.get(key) { val } else { "default" } 这样的表达式来解决这个问题,但我想知道是否有更简洁的方法。

看来问题是 Rust 不会自动对 Option<&String> 执行 Deref 强制转换,因此您必须使用 Option::map_or 之类的方法显式转换为 &str:

let val = hashmap.get("key").map_or("default", String::as_str);

虽然这是最直接的方法,但在此相关答案中还有其他几种 Deref 强制转换的替代方法: