Option could have a function that returns &mut

Hi Kornel,

Thank you.

They are not mutually-exclusive. See again please from my previous reply all the projects that use as_mut().unwrap()

Maybe it's not so common, but use cases exist.
Example: you have a list of options where you know for sure that the first and last elements can't be None.

I use .as_mut().unwrap() all the time, that doesn't mean I want to replace it with something else. Don't try to cite other people's code as an example of suboptimal code just because it exists. That's not a compelling argument.

5 Likes

Having another option doesn't mean that everybody have to or will use the new option.

Also, it's just your opinion that it's suboptimal. :slight_smile:
It's not like a quoted any code, those people know what they're doing.

You just said that you use all the time. So do you like to write suboptimal code?

You already have that option. You're not proposing to add an option, you're proposing to add the option to std (where everyone will have to learn to understand it.)

If you really feel like you are using this all the time, you can make an extension trait

trait OptionExt {
    type Item;
    
    fn unwrap_mut(&mut self) -> &mut Self::Item;
}

impl<T> OptionExt for Option<T> {
    type Item = T;
    
    fn unwrap_mut(&mut self) -> &mut Self::Item { self.as_mut().unwrap() }
}

Then you can use it like:

use some::path::OptionExt;
let inner = some_option.unwrap_mut();

However, I don't agree with adding it to std. I already see people stumbling over Option's 42 methods, and dozens of trait implementations. Option is stuffed to the brim with "helpful" features (sure many of these are useful, but do we really need all 42 of them?). We don't need to add more.

6 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.