Advertisement
Guest User

Untitled

a guest
May 26th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. #![allow(dead_code)]
  2. #![allow(unused_variables)]
  3. #[allow(unused_imports)]
  4. use std::cell::{ Ref, RefMut, RefCell };
  5.  
  6.  
  7. fn main() {
  8. let aa = AA::new();
  9.  
  10. // Add can mut borrow BB's Vec and Add things.
  11. aa.add( "w00t" );
  12. aa.add( "c00l");
  13. aa.add( "l00p");
  14.  
  15. /* Get Vec, Then CC Ref works just fine
  16. let cvec = aa.get_vec();
  17. let ref cc = cvec[0];
  18. */
  19.  
  20. //Trying to get CC without getting BB's Vector in this context
  21. //But this causes life-time issues.
  22. let c = aa.get_cc( 0 );
  23.  
  24. //println!("{:?}", c );
  25. }
  26.  
  27. struct AA{ bb :BB, }
  28. impl AA{
  29. pub fn new()->Self{ AA{ bb: BB::new() } }
  30.  
  31. pub fn add( &self, txt: &str ){
  32. let mut hash = self.bb.data.borrow_mut();
  33. hash.push( CC{ txt: txt.to_string() } );
  34. }
  35.  
  36. pub fn get_vec( &self ) -> Ref< Vec<CC> >{ self.bb.data.borrow() }
  37.  
  38. /* Does N't because of reference pwm by function errors.
  39. pub fn get_cc( &self, i: usize ) -> &CC{
  40. let v = self.bb.data.borrow();
  41. &v[ i ]
  42. }
  43. */
  44.  
  45. // Life Time Issues... Meh
  46. /* */
  47. pub fn get_cc( &self, i: usize ) -> Ref<&CC>{
  48. let vec = self.bb.data.borrow();
  49. Ref::map( vec, |v|{
  50. &&v[ i ]
  51. })
  52. }
  53. }
  54.  
  55. struct BB{ data : RefCell< Vec< CC > > }
  56. impl BB{
  57. fn new()->Self{ BB{ data: RefCell::new( Vec::new() ) } }
  58. }
  59.  
  60. #[derive(Debug)]
  61. struct CC{ txt: String }
  62. impl CC{
  63. fn new( s: &str )->Self { CC{ txt: s.to_string() } }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement