Crate borrow_owned[][src]

Expand description

Simple helper for temporary object moving.

It is useful if you need to pass your object somewhere and you cannot pass a reference to the object because you wouldn’t be able to guarantee that the object lives long enough. For example, you don’t want to use Arc<Mutex<_>> for some reason but you need to pass your object to a new thread and you need to use the object again in the original thread once the new thread does not need the object anymore.

See the examples below.

Features

  • async - asynchronous version of the helper

Example

use std::{mem, thread, time::Duration};
use borrow_owned::BorrowOwned;

struct MyStruct;

let object = MyStruct;
let (borrowed, ret) = object.borrow_owned();

thread::spawn(move || {
    println!("doing something with the object...");
    thread::sleep(Duration::from_millis(100));

    mem::drop(borrowed);

    println!("doing something else...");
    thread::sleep(Duration::from_millis(100));
});

println!("waiting until the borrow ends...");
let objects = ret.wait();
println!("the object is back again!");

Asynchronous example

use std::{mem, time::Duration};
use borrow_owned::AsyncBorrowOwned;

struct MyStruct;

#[tokio::main]
async fn main() {
    let object = MyStruct;
    let (borrowed, ret) = object.async_borrow_owned();

    tokio::spawn(async move {
        println!("doing something with the object...");
        tokio::time::sleep(Duration::from_millis(100));

        mem::drop(borrowed);

        println!("doing something else...");
        tokio::time::sleep(Duration::from_millis(100));
    });

    println!("waiting until the borrow ends...");
    let object = ret.await;
    println!("the object is back again!");
}

Structs

AsyncBorrowedasync

Borrowed object.

AsyncReturnasync

Return handle.

Borrowed

Borrowed object.

Return

Return handle.

Traits

AsyncBorrowOwnedasync

Trait allowing objects to be temporarily moved elsewhere.

BorrowOwned

Trait allowing objects to be temporarily moved elsewhere.