Search code examples
rustoption-type

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.


Solution

  • When you find yourself stringing together multiple methods and closures to work with Option, Result, or even things like hash_map::Entry, consider going back to basics and using a match:

    pub fn opt_opt_str_ref(input: &Option<Option<String>>) -> Option<Option<&str>> {
        match input {
            Some(Some(s)) => Some(Some(s.as_str())),
            Some(None) => Some(None),
            None => None,
        }
    }
    

    This has the advantage that when read, its meaning is obvious; there is no question about what it actually does. If it needs to be changed to do something slightly different, how to do so is obvious.

    It's not always better (and this particular example is particularly inelegant with all the repetition), but (in my opinion) it's always worth considering the option.