Option::insert (return inner reference)

I don't know if I am missing something, but I just stumbled upon a minor papercut in std::option::Option.
I have two variables opt: &'a mut Option<T> and value: T. I want to unconditionally assign Some(value) to *opt and then return a mutable reference to the value inside opt (so the return type is &'a mut T).

This should be possible without an unwrap, but I don't know how. Option::get_or_insert only inserts when the old value is None.
If there is no such method, would it be worthwhile to create an issue/PR/RFC against the standard library? There are already many convenience methods fixing similar papercuts.

You could do this:

*opt = None;
let r = opt.get_or_insert(value);

Thank you! This is still a bit awkward, but I like it much better than the unwrap. I still feel like this could be a method in std::option::Option.

You could try to get it added.

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