How to convert Option<&mut T> to &mut Option<T>

There is as_mut method in Option(Option in core::option - Rust) to convert from &mut Option<T> to Option<&mut T> .

How to undo the as_mut?

By calling cloned() on the Option, or mem::swap of the inner value with another owned value.

In Rust you can easily lend a value you own, but you can't just take a borrowed value and pretend you own it (that's stealing!)

The borrowed/owned relationship is not symmetrical, and by necessity it's easy one way, and not always possible the other way.

2 Likes

The problem is, to have a &mut Option<T> someone else should own the Option<T> and hold it during the lifetime. But with Some(&mut T) how can the compiler know that the &mut T actually is came from the &mut Option<T>?

1 Like

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