Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![allow(dead_code)]
- #![allow(unused_variables)]
- #[allow(unused_imports)]
- use std::cell::{ Ref, RefMut, RefCell };
- fn main() {
- let aa = AA::new();
- // Add can mut borrow BB's Vec and Add things.
- aa.add( "w00t" );
- aa.add( "c00l");
- aa.add( "l00p");
- /* Get Vec, Then CC Ref works just fine
- let cvec = aa.get_vec();
- let ref cc = cvec[0];
- */
- //Trying to get CC without getting BB's Vector in this context
- //But this causes life-time issues.
- let c = aa.get_cc( 0 );
- //println!("{:?}", c );
- }
- struct AA{ bb :BB, }
- impl AA{
- pub fn new()->Self{ AA{ bb: BB::new() } }
- pub fn add( &self, txt: &str ){
- let mut hash = self.bb.data.borrow_mut();
- hash.push( CC{ txt: txt.to_string() } );
- }
- pub fn get_vec( &self ) -> Ref< Vec<CC> >{ self.bb.data.borrow() }
- /* Does N't because of reference pwm by function errors.
- pub fn get_cc( &self, i: usize ) -> &CC{
- let v = self.bb.data.borrow();
- &v[ i ]
- }
- */
- // Life Time Issues... Meh
- /* */
- pub fn get_cc( &self, i: usize ) -> Ref<&CC>{
- let vec = self.bb.data.borrow();
- Ref::map( vec, |v|{
- &&v[ i ]
- })
- }
- }
- struct BB{ data : RefCell< Vec< CC > > }
- impl BB{
- fn new()->Self{ BB{ data: RefCell::new( Vec::new() ) } }
- }
- #[derive(Debug)]
- struct CC{ txt: String }
- impl CC{
- fn new( s: &str )->Self { CC{ txt: s.to_string() } }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement