From HashMap<String, Option<String>> into Option<String>


I am having an HashMap<String, Option<String>> and I want to get the value as typed Option<String>. But I end to have an &Option<String>.

Rust Playground

Please advise

If you want an owned value, you need to take ownership from the HashMap by using remove.

What do you want to happen to the value stored in the hashmap?

If you want Option<String> you need to move it from the hashmap and use HashMap::remove(). Or clone() the value if you want to keep it in the hashmap.

Alternatively you can get the value as &Option<String> and convert it to Option<&String> using Option::as_ref() like

let optional_name : Option<&String> = name.unwrap().as_ref();

It's not exactly what you want but you can use it pretty much the same way without having to remove the item from the hashmap or cloning it.

1 Like

Here's an annotated version of your code that results in an Option<String> without panicking.

The reason you get a &Option<String> instead of Option<String> is because the get method just gives you a pointer to the item.

If you want an owned value, your choices are to either create a copy (clone()) or move the value out of the HashMap (remove()).

1 Like

You could also use map.get_mut("key").and_then(Option::take), which will leave the key in the map with value None.

Thank you all for your helps.

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.