Easiest, most ergonomic string-lookup-with-default in Map collection

I'm wondering what is the simplest way to look up a value in a map-collection Map<_, String> and use a string-literal (possibly the empty string) as a default. (For the purpose of this question, it doesn't matter whether the collection is HashMap, BTreeMap, or something else.)

The fundamental problem is that the value type, &String, doesn't automatically deref to &str in most attempts that I've tried.

The simplest working version I've found so far is:

h.get("baz").map_or("", |s| &s)

This looks weird to me, because .get() already returns a reference, so the only purpose of the |s| &s lambda is to trigger the Deref trait.

I am a bit surprised I couldn't find any existing threads (here or anywhere else on the internet) about this; it seems like it would be a fairly common use case (e.g. when implementing environment variables in a shell).

How about

h.get("baz").map_or("", String::as_str)


1 Like

I do like that that's more explicit!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.