[][src]Crate borrow_trait

This library provides traits for borrow and borrow_mut functions, most commonly found in RefCells. Therefore it is possible to accept other kinds of RefCells like an AtomicRefCell or smart pointers around RefCells like Arc, Rc or Box.


Let's say you have a library, that needs to read some data from a Reader, but doesn't want to mutate it and wants to accept any kind of RefCell, that gives a mut reference to the Reader.

use std::io::{ Read, Cursor };
use std::cell::RefCell;
use borrow_trait::{ BorrowRefMut };

fn takes_bound<C, T>(value: &T) -> Vec<u8>
    T: for<'a> BorrowRefMut<'a, Target = C>,
    C: Read,
    let mut result = vec![];
    value.borrow_mut().read_to_end(&mut result).expect("Failed to read from `value: T`");

let value = RefCell::new(Cursor::new(vec![0, 1, 2, 3]));
assert_eq!(takes_bound(&value), vec![0, 1, 2, 3]);

Only accepting RefCells, that can be cloned (for example Rc<RefCell<T>>):

use std::io::{ Read, Cursor };
use std::cell::{ RefCell };
use borrow_trait::{ BorrowRefMut };
use std::rc::{ Rc };

fn takes_bound<C, T>(value: T) -> Vec<u8>
    T: for<'a> BorrowRefMut<'a, Target = C> + Clone,
    C: Read,
    let mut result = vec![];
        .read_to_end(&mut result)
        .expect("Failed to read from `value: T`")

let value = Rc::new(RefCell::new(Cursor::new(vec![0, 1, 2, 3])));
assert_eq!(takes_bound(value.clone()), vec![0, 1, 2, 3]);


no_std support can be enabled by adding the following to the Cargo.toml:

borrow_trait = { version = "0.1", default-features = false }

By enabling the alloc feature, the library will implement the traits for Rc, Arc and Box.

borrow_trait = { version = "0.1", default-features = false, features = [ "alloc" ] }


  • This crate re-exports it's dependencies for ease of use.
  • This crate does conform to semantic versioning.
  • It contains not a single line of unsafe code.


  • Remove the lifetime requirement of BorrowRef<'a, C, T> and BorrowRefMut<'a, C, T>. This feature requires Generic Associated Lifetimes rust-lang/rust#44265


  • Parts of the documentation were copied from the std library
  • The feature flags were inspired by the serde and rand crate.
  • The name for the traits were inspired by borrow_with_ref_obj crate.


pub use atomic_refcell;
pub use cell;



A trait for immutably borrowing data.


A trait for mutably borrowing data.