Hi all.
I was trying to make the code below to work:
fn issue() {
trait Reader {
fn read(&self, buf: &mut [u8]);
}
struct Abc {
f: Box<dyn Reader>,
buf: [u8; 32],
}
impl Reader for u8 {
fn read(&self, buf: &mut [u8]) {
buf[0] = 0;
}
}
let buf = [0u8; 32];
let abc = Rc::new(RefCell::new(Abc {
f: Box::new(100u8),
buf,
}));
let mut abc_mut_ref = abc.borrow_mut();
// can't work, compiling error:
// abc_mut_ref.f.read(&mut abc_ref.buf[..]);
// can't do it like below, runtime error:
// let abc_ref = abc.borrow();
// abc_ref.f.read(&mut abc_mut_ref.buf[..]);
}
There are 2 solutions from the commented code, which are unfortunately both wrong.
And I found that if Rc/RefCell
wasn't used (just use a mutable ref), it can work:
// it can work like below:
let abc2 = &mut Abc {
f: Box::new(100u8),
buf,
};
abc2.f.read(&mut abc2.buf[..]);
Is there any solution to this issue? Thanks.