0

I am trying to formalize my use of Rc<RefCell<T>>. This works fine:

use std::cell::{Ref, RefCell};
use std::rc::Rc;

struct SP<T> {
    object: Rc<RefCell<T>>,
}

impl<T> SP<T> {
    pub fn new(value: T) -> SP<T> {
        SP {
            object: Rc::new(RefCell::new(value)),
        }
    }
    pub fn get(&self) -> Ref<T> {
        self.object.borrow()
    }
}
// impl<T> Deref for SP<T> {
//     type Target = T;
//     fn deref(&self) -> &Self::Target {
//         &self.object.borrow()
//     }
// }
struct Test {
    i: i32,
}
fn main() {
    let t = Test { i: 42 };
    let sp = SP::new(t);

    let tt = sp.get().i;

    println!("{}", tt)
}

I would like to sugar the use of SP so that I can do this:

fn main() {
    let t = Test { i: 42 };
    let sp = SP::new(t);

    let tt = sp.i; // implicit 'dereference'

    println!("{}", tt)
}

I tried to implement this in the commented out code. The problem is that the rvalue generated by borrow() refuses to live long enough to be consumed by the rest of the statement. Is there any magic spell I can cast over this code to persuade it to work?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
pm100
  • 48,078
  • 23
  • 82
  • 145
  • 1
    TL;DR — you can't. That's kind of the point of runtime/dynamic borrow checking, as opposed to compile-time/static borrow checking. Presumably if you could do this, then `RefCell` would already allow you to do it and you wouldn't need the wrapper. – Shepmaster Sep 01 '20 at 18:41
  • dont really see that including the word get() in a statement fundamentally changes the dynamic / static borrow mutability etc. Its just typing 6 less chars. I supposed I could call it g and get it down to 4 chars. Not asking to store the result or anything, just want the rvalue to last for the whole statement. – pm100 Sep 01 '20 at 20:37

0 Answers0