1

I want to change a struct member value inside a method that is of type Rc<RefCell<Option<_>>. Lets say I have this struct:

struct TestStruct {
    pub vecfield: Rc<RefCell<Vec<i32>>>,
}

impl TestStruct {
    fn set_vec(&self) {
       self.vecfield.as_ref().borrow_mut().append(&mut vec![2,3]);
    }
}


fn main() {
    let x = TestStruct { vecfield: Rc::new(RefCell::new(vec![1])) };
    x.set_vec();
    println!("{:?}", x.vecfield);
}

RefCell { value: [1, 2, 3] }

So far, so good. Now I want to wrap the Vector in an Option (or the RefCell, doesn't matter) and the method always tries to move the Option.

impl TestStruct {
    fn set_vec(&self) {
       //will not compile
       self.vecfield.as_ref().borrow_mut().unwrap().append(&mut vec![2,3]);
    }
}
fn main() {
    let x = TestStruct { vecfield: Rc::new(RefCell::new(Some(vec![1]))) };
    x.set_vec();
    println!("{:?}", x.vecfield);
}

How do I mutably access the Vector inside the method now? I tried calling into_inner() and as_ref() but this gives still my errors saying I can't move the Option inside the method. It also doesn't help if I wrap the Optioninside another Rc and clone it. From my understanding the Option inside the Rc is still behind a pointer so why is it moved in the first place? Does unwrap() need ownership?

trent
  • 25,033
  • 7
  • 51
  • 90
sh1nnen
  • 11
  • 1
  • I think this question is answered by [Cannot move out of value which is behind a shared reference when unwrapping](/q/32338659/3650362). In this case you just need to insert `.as_mut()` before `.unwrap()`. (Incidentally you don't need the `as_ref()` on `vecfield` because `Rc` is automatically dereferenced to `T` when you use `.`) – trent Aug 22 '20 at 13:29

0 Answers0