rent_to_own
RentToOwn<T>
: A wrapper type for optionally giving up ownership of the
underlying value.
RentToOwn<T>
is useful in situations where
-
a function might want to conditionally take ownership of some
T
value, and -
that function cannot take the
T
by value and return anOption<T>
to maybe give theT
value back if it doesn't want ownership.
RentToOwn<T>
dereferences (immutably and mutably) to its inner T
value, and
additionally provides a take
method that gives up ownership of the inner value
to the caller.
Under the covers, RentToOwn<T>
is essentially an Option<T>
that gets
unwrapped when dereferenced and calls Option::take
if we need to take
ownership of the inner value. The key advantage over using Option<T>
directly,
other than the Deref
sugar, is some lifetime trickery to statically prevent
all unwrapping panics that would arise from using the RentToOwn<T>
wrapper
again after the inner value has been taken. Once the inner value is taken, the
borrow checker will ensure that the original RentToOwn<T>
cannot be used
anymore. See the take
method's documentation for details.
Example
In this example, if the configure
function encounters any errors, we do not
wish to drop the BigExpensiveResource
, but instead allow the caller to handle
the error and then reuse the resource. In effect, the configure
function is
conditionally taking ownership of the BigExpensiveResource
depending on if
there are IO errors or not.
use RentToOwn;
use ;
use fs;
/// This is a big, expensive to create (or maybe even unique) resource, and we
/// want to reuse it even if `configure` returns an error.
/// A big, expensive resource that has been properly configured.
What does configure
's caller look like? It calls RentToOwn::with
to
construct the RentToOwn<BigExpensiveResource>
and invoke a closure with
it. Then it inspects the results of the closure and whether the
BigExpensiveResource
was taken or not.
In this example, the caller can recover from any IO error when reading or
parsing the configuration file and use a default configuration with the
BigExpensiveResource
instead.
License: Apache-2.0/MIT