Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert Option<Option<String>> to Option<Option<&str>> in Rust?

I am trying to make this conversion (Option<Option<String>> to Option<Option<&str>>) possible, but I still failed after trying many methods including using .map.

I know that the conversion is possible, however, if there’s no nested Option (i.e. Option<String> to Option<&str>): just using .as_deref().
Using .map(|inner| inner.as_deref()) violates the ownership.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason using a plain map violates ownership rules is because it takes self. You’re consuming the outer Option and then trying to borrow something from inside it, which doesn’t work.

However, there’s an easy approach here, using as_ref and then as_deref inside the map. as_ref turns &Option<T> into Option<&T>, where T is Option<String>, so when you call map, you get an &Option<String>, which you can then safely pass to as_deref.

fn main() {
    let foo = Some(Some(String::from("abc")));
    let bar: Option<Option<&str>> = foo.as_ref().map(|r| r.as_deref());
    eprintln!("{:?}", bar);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading