Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::sync::Arc;
- use std::cell::RefCell;
- struct Test {
- pub cache: RefCell<Option<Arc<String>>>,
- }
- impl Test {
- pub fn new() -> Self {
- Test {
- cache: RefCell::new(None)
- }
- }
- pub fn test(&self) -> Arc<String> {
- let mut cache = self.cache.borrow_mut();
- let s = cache.get_or_insert_with(|| {
- Arc::new("a".to_string())
- });
- Arc::make_mut(s).push_str(".");
- s.clone()
- }
- }
- fn main() {
- let t = Test::new();
- for _ in 1..3 {
- println!("{}", t.test());
- }
- // It is possible to keep old value around, but it means that
- // Arc::make_mut will have to make a copy.
- let a = t.test();
- let b = t.test();
- println!("{} {}", a, b);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement