How to convert &str to &string?

I have written these codes ever:

let data: HashMap<String, String> = HashMap::new();
let item = data.get("one").unwrap_or(&"empty".to_owned()).to_owned();

But (&"empty".to_owned()).to_owned() looks like not good. Is there more elegant way to implement this?

Converting an &str to &String requires copying the data. How about doing the opposite conversion instead?

let item = data.get("one").as_deref().unwrap_or("empty");

This uses Option::as_deref, which will convert an Option<&String> into an Option<&str>.

1 Like

compile error :frowning:

28 |     let item = data.get("one").as_deref().unwrap_or("empty").to_owned();
   |                                                     ^^^^^^^ expected struct `String`, found `str`
   = note: expected reference `&String`
              found reference `&'static str`
1 Like

Right, .as_deref() doesn't do anything if the Option already contains a reference. Try .map(String::as_str) instead.


It works! thanks very much. Also thanks @alice


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.