A simple wrapper type that holds values that need to be moved out from only a mutable reference.
Sometimes it's useful to be able to move out of a mutable reference temporarily or permanently. This often occurs for instance when dealing with state machines implemented using an enum. For instance let's say you have the following state machine:
Let's say that you want to implement a function that changes state from
Finished. The naive approach would be:
However, this would fail with a "cannot move out of borrowed content" error.
There are a few solutions to this problem:
Option<State>. Temporarily set it to
Noneto move out the state.
Introduce a new, invalid state for the same purpose.
Restructure your code to avoid the problem.
Depending on your scenario, any of these options might be preferable. This crate
provides a wrapper around an
Option<T> with an API that forces correct usage
Option. This approach also has the advantage that it allows the
performance-optimization of not actually checking the enum-tag outside of
Using this library, the code could have been written like this:
It can also sometimes be useful to permanently move a value out while only
having a mutable reference. One such use case is when implementing
needing to call a method of a field that consumes the field. This can be done
using this crate as follows:
The above code would also work by using an
Option directly instead of a
Takeable. However, the latter has the advantage that it is clear by its
type that it must always have a value, and also that
None variants do not
have to be handled when accessing the
Resource elsewhere. Rather, the
Takeable will panic if this is attempted after the value has been moved