Consider the below code, where I have a struct that contains an Option<String> and has a method for returning either the value within the option or a default value, both as &str. I've implemented this using a match statement, but I feel that it must be possible to rewrite this into a single line using Option methods. Unfortunately, all my attempts so far — the most complicated of which has been (&self.sopt).as_ref().unwrap_or_else(|| "<unknown>".into()) — fail to compile, usually because the &String is not being implicitly converted to a &str.
How can I rewrite this with Option methods? Please explain your answer.
That's because in this case you already have an Option<&String> to begin with (Vec::get() returns Option<&T>), and the Deref impl for references is the identity function. So just map the deref call explicitly over the option: