Advertisement
Guest User

Untitled

a guest
Sep 12th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. use std::sync::Arc;
  2. use std::cell::RefCell;
  3.  
  4. struct Test {
  5. pub cache: RefCell<Option<Arc<String>>>,
  6. }
  7.  
  8. impl Test {
  9. pub fn new() -> Self {
  10. Test {
  11. cache: RefCell::new(None)
  12. }
  13. }
  14.  
  15. pub fn test(&self) -> Arc<String> {
  16. let mut cache = self.cache.borrow_mut();
  17. let s = cache.get_or_insert_with(|| {
  18. Arc::new("a".to_string())
  19. });
  20.  
  21. Arc::make_mut(s).push_str(".");
  22.  
  23. s.clone()
  24. }
  25. }
  26.  
  27.  
  28. fn main() {
  29. let t = Test::new();
  30. for _ in 1..3 {
  31. println!("{}", t.test());
  32. }
  33.  
  34. // It is possible to keep old value around, but it means that
  35. // Arc::make_mut will have to make a copy.
  36. let a = t.test();
  37. let b = t.test();
  38. println!("{} {}", a, b);
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement