Search code examples
stringrustdefault

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


I have a HashMap<_, String>for which I would like to either get the corresponding value of a key or return a default string. The most obvious approach would be to just use unwrap_or, but this fails with an type error:

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

I can work around this using an expression like if let Some(val) = hashmap.get(key) { val } else { "default" }, but I was wondering if there is a cleaner approach.


Solution

  • It appears that the issue is that Rust does not automatically perform Deref coercion on the Option<&String>, thus you must explictly convert to a &str using something like Option::map_or:

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

    While this is the most direct method, there are several other alternatives for Deref coercion in this related answer: https://stackoverflow.com/a/31234028/1172350