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]

[src]

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:

  1. If the closure took ownership of the inner value, None, otherwise Some(inner).

  2. The value returned by the closure.

See the module level documentation for details and examples.

impl<'a, T> RentToOwn<'a, T>
[src]

[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>.

This code doesn't compile so be extra careful!
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]

[src]

Formats the value using the given formatter.

impl<'a, T: Hash + 'a> Hash for RentToOwn<'a, T>
[src]

[src]

Feeds this value into the given [Hasher]. Read more

1.3.0
[src]

Feeds a slice of this type into the given [Hasher]. Read more

impl<'a, T> Deref for RentToOwn<'a, T>
[src]

The resulting type after dereferencing.

[src]

Dereferences the value.

impl<'a, T> DerefMut for RentToOwn<'a, T>
[src]

[src]

Mutably dereferences the value.