Advertisement
Guest User

Untitled

a guest
May 26th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 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(&aa.get_vec(), 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. // #[inline(always)]
  48. // pub fn get_cc<'a>( &'a self, i: usize ) -> &CC {
  49. // let a = self.bb.data.borrow();
  50. // }
  51.  
  52. pub fn get_cc<'a>(v: &'a Ref<Vec<CC>>, i: usize) -> &'a CC {
  53. &v[i]
  54. }
  55. }
  56.  
  57. struct BB{ pub data : RefCell<Vec<CC>> }
  58. impl BB{
  59. fn new()->Self{ BB{ data: RefCell::new( Vec::new() ) } }
  60. }
  61.  
  62. #[derive(Debug)]
  63. struct CC{ txt: String }
  64. impl CC{
  65. fn new( s: &str )->Self { CC{ txt: s.to_string() } }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement