Versions of the Borrow
and BorrowMut
traits that can return
reference objects (such as std::cell::Ref
) instead of references directly.
This allows you to accept T
, &T
, Rc<RefCell<T>>
, Arc<Mutex<T>>
, and
Arc<RwLock<T>>
by requiring a single trait.
See the crate documentation for more information.
Example
use BorrowWithRefObj;
/// Example structure that can possibly share ownership of a u32.
///
/// Modeled after a work queue getting data from a central source (ex. a
/// database) that may or may not be shared with others.
///
/// Note: Need to use higher-ranked trait bound here (for<'refr>), to tell
/// rust that the object that `borrow` returns about its lifetime.
// Create a processor that is the sole owner of the data
let mut sole_owning_processor = new;
// Prints 2,3,4,5,6
sole_owning_processor.process_all;
// Creates a processor that borrows the data
let value = 2;
let mut borrowing_processor = new;
// Prints 3,4,5,6,7
sole_owning_processor.process_all;
// Creates a processor that shares ownership via Rc<RefCell<u32>>
use Rc;
use RefCell;
let value = new;
let mut rc_processor = new;
// Prints 2,3,4
rc_processor.process_one;
rc_processor.process_one;
rc_processor.process_one;
// Modify the value
*value.borrow_mut = 5;
// Prints 9,10
rc_processor.process_one;
rc_processor.process_one;
// You can do the same as above with Arc<Mutex<T>> or Arc<RwLock<T>>, if you
// need thread-safe access.