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 Option
inside 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?