0

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.

dcoles
  • 3,785
  • 2
  • 28
  • 26
  • I don't understand your question is already perfectly answered with a canonical question. Why not juste close as duplicate ? Your answer look useless. – Stargateur Apr 28 '19 at 09:14
  • @Stargateur In my question it's an `Option<&String>` to `Option<&str>`. I didn't personally know enough Rust to say they're equivalent. Happy to close as a duplicate if that's the case. Secondly working with a `HashMap<_, String>` is reasonably common, but the canonical answer for getting default values (https://stackoverflow.com/questions/41417660/how-does-one-create-a-hashmap-with-a-default-value-in-rust) doesn't work for `String`. Thus there's value in asking "How do I get a default for a String map". – dcoles Apr 28 '19 at 12:24

1 Answers1

4

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

dcoles
  • 3,785
  • 2
  • 28
  • 26