Struct rent_to_own::RentToOwn
[−]
[src]
pub struct RentToOwn<'a, T: 'a> { /* fields omitted */ }
A wrapper around a T
that allows users to conditionally take ownership of
the inner T
value, or simply use it like a &mut T
reference.
See the module documentation for details and examples.
Methods
impl<'a, T: 'a> RentToOwn<'a, T>
[src]
fn with<F, U>(inner: T, f: F) -> (Option<T>, U) where
F: for<'b> FnOnce(&'b mut RentToOwn<'b, T>) -> U,
[src]
F: for<'b> FnOnce(&'b mut RentToOwn<'b, T>) -> U,
Give the function f
the option to take ownership of inner
.
That is, create a RentToOwn
from the given inner
value and then
invoke the function f
with it.
The return value is a pair of:
If the closure took ownership of the inner value,
None
, otherwiseSome(inner)
.The value returned by the closure.
See the module level documentation for details and examples.
impl<'a, T> RentToOwn<'a, T>
[src]
fn take(&'a mut self) -> T
[src]
Take ownership of the inner T
value.
Note that the lifetime on the self
reference forces the mutable borrow
to last for the rest of the RentToOwn
's existence. This "tricks" the
borrow checker into statically disallowing use-after-take, which would
otherwise result in a panic if you were using Option<T>
instead of
RentToOwn<T>
.
use rent_to_own::RentToOwn; struct Thing(usize); fn use_after_take<'a>(outer: &'a mut RentToOwn<'a, Thing>) { // Take ownership of the inner value, moving it out of the // `RentToOwn`. let inner = outer.take(); let inner_val = inner.0; println!("inner's value is {}", inner_val); // An attempt to use the `RentToOwn` again (via deref) after its // value has already been taken! let outer_val = outer.0; println!("outer's value is {}", outer_val); }
Attempting to compile that example results in a compilation error:
error[E0502]: cannot borrow `*outer` as immutable because it is also borrowed as mutable
--> src/lib.rs:18:21
|
11 | let inner = outer.take();
| ----- mutable borrow occurs here
...
18 | let outer_val = outer.0;
| ^^^^^ immutable borrow occurs here
19 | println!("outer's value is {}", outer_val);
20 | }
| - mutable borrow ends here
Trait Implementations
impl<'a, T: Debug + 'a> Debug for RentToOwn<'a, T>
[src]
impl<'a, T: Hash + 'a> Hash for RentToOwn<'a, T>
[src]
fn hash<__HT: Hasher>(&self, __arg_0: &mut __HT)
[src]
Feeds this value into the given [Hasher
]. Read more
fn hash_slice<H>(data: &[Self], state: &mut H) where
H: Hasher,
1.3.0[src]
H: Hasher,
Feeds a slice of this type into the given [Hasher
]. Read more
impl<'a, T> Deref for RentToOwn<'a, T>
[src]
type Target = T
The resulting type after dereferencing.
fn deref(&self) -> &T
[src]
Dereferences the value.