0

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);
}

Playground

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Looks like it'd be better if `cur_num` were just an index for the `nums` array, no? – kmdreko Apr 06 '21 at 19:01
  • 3
    Your `nums` property must be `Rc>` and your `cur_num` must be `Option>>`. Then you can update value by mutable reference at once. – Dmitry Apr 06 '21 at 19:02
  • @Dmitry I see your point, but how would I be able to update that value if nums is an array, while cur_num is an element? I am stuck at how to assign curr_num. Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e1bf479ed3a5bf54979ae7769024689f –  Apr 06 '21 at 19:57
  • 1
    Dmitry's suggestion was to do something more like [this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3df5190597b4ae96a223b1c2cec40e13). – kmdreko Apr 06 '21 at 22:10
  • @kmdreko thank you! that explains a lot. –  Apr 06 '21 at 22:29
  • 1
    Sorry, my mistake was that your `nums` must be `[Rc>; 8]`. See this RPG: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=fbac44d14059f6075f25806fef36b573 – Dmitry Apr 07 '21 at 05:22

0 Answers0