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?