I have a struct with a field that references the current element on an array in the same struct using Rc
. I can now have a reference to any element from then nums
field:
use std::{cell::RefCell, rc::Rc};
struct ArrayTest {
nums: [u32; 8],
cur_num: Rc<RefCell<Option<u32>>>,
}
fn main() {
let mut slice = ArrayTest {
nums: [1, 2, 3, 4, 5, 6, 7, 8],
cur_num: Rc::new(RefCell::new(None)),
};
slice.cur_num = Rc::new(RefCell::new(Some(1)));
let ref mut t = slice.nums[3];
slice.cur_num = Rc::new(RefCell::new(Some(*t)));
println!("{:?}", slice.cur_num);
if let Some(ref mut t) = *slice.cur_num.borrow_mut() {
*t += 1;
};
println!("{:?}", slice.cur_num);
println!("{:?}", slice.nums);
}
The problem comes when I try to modify cur_num
, because I want it to reflect its value on the nums
array. Whenever I try to do so by dereferencing it, it seems like it only changes cur_num
.
RefCell { value: Some(4) }
RefCell { value: Some(5) }
[1, 2, 3, 4, 5, 6, 7, 8]
Why can't I store a value and a reference to that value in the same struct? is another topic about storing the value in the same struct, but the answer doesn't show the cases where the value can be moved, or the usage of RefCell
.
Is there a way to modify that RefCell
so that I can modify the reference?