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.
```rust use borrowwithref_obj::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.
struct Processor
/// Processes one element in the work queue
pub fn process_one(&mut self) {
let current_work = match self.work_queue.pop() {
Some(v) => v,
None => { return; }
};
let data_source = self.data_source.borrow();
let current_result = current_work + *data_source;
println!("{}", current_result);
}
/// Processes all elements in the work queue
pub fn process_all(&mut self) {
while !self.work_queue.is_empty() {
self.process_one();
}
}
}
// Create a processor that is the sole owner of the data let mut soleowningprocessor = Processor::new(1); // Prints 2,3,4,5,6 soleowningprocessor.process_all();
// Creates a processor that borrows the data let value = 2; let mut borrowingprocessor = Processor::new(&value); // Prints 3,4,5,6,7 soleowningprocessor.processall();
// Creates a processor that shares ownership via Rc
let value = Rc::new(RefCell::new(1)); let mut rcprocessor = Processor::new(Rc::clone(&value)); // Prints 2,3,4 rcprocessor.processone(); rcprocessor.processone(); rcprocessor.processone(); // Modify the value *value.borrowmut() = 5; // Prints 9,10 rcprocessor.processone(); rcprocessor.processone();
// You can do the same as above with Arc