Is it possible to switch options to the value of a mutable link
As Mattiu M. said , the general answer is no. The reason is that this will cause the enumeration to be in an undefined state, which will allow access to undefined memory, which will violate Rust's security guarantees. As an example, let's assume that this code compiled without errors:
impl<T> E<T> { fn promote_to_b(&mut self) { if let E::VariantA(val) = *self { // Things happen *self = E::VariantB(val); } } }
The problem is that you moved the value from self to val , what should happen to the memory representing T inside self ?
If we copied the bits and then there was a panic in βThings happenβ, the destructor for val and T inside self will execute, but since they point to the same data, this will lead to double free.
If we did not copy the bits, then you could not safely access the val inside the "Things happen", which would be utmost useful.
The cost solution works because the compiler can keep track of who should call the destructor: the function itself. When you are inside a function, the compiler knows what specific lines may be needed to free the value and properly names them in case of panic.
The Clone or Default solution works because you never move a value from the original enumeration. Instead, you can replace the original enumeration with a dummy value and take ownership of the original (using Default ) or duplicate the entire original value (using Clone ).
replace_with RFC (# 1736) suggested adding a method that would allow this to work, ensuring that the correct memory semantics were confirmed, but the RFC was not accepted.
Shepmaster
source share