0
我想將RefCell傳遞給閉包中的函數,然後從閉包中修改相同的變量。這裏是我的代碼:如何從閉合內部修改Rc <RefCell>?
let path: Rc<RefCell<Option<Vec<PathBuf>>>> = Rc::new(RefCell::new(None));
...
//valid value assigned to path
...
let cloned_path = path.clone();
button_run.connect_clicked(move |_| {
let to_remove: usize = open_dir(&mut cloned_path.borrow_mut().deref_mut());
//Here I need to remove "to_remove" index from cloned_path
});
//Choose a random directory from Vec and open it. Returns opened index.
fn open_dir(path_two: &mut Option<Vec<PathBuf>>) -> usize {
let vec = path_two.clone();
let vec_length = vec.unwrap().len();
let mut rng = thread_rng();
let rand_number = rng.gen_range(0, vec_length);
let p: &str = &*path_two.clone().expect("8")[rand_number].to_str().unwrap().to_string();
Command::new("explorer.exe").arg(p).output();
rand_number.clone()
}
首先,我想,既然我open_dir()
函數接受&mut
,我可以修改函數內部的載體。但不管我嘗試了什麼,我總是收到cannot move out of borrowed content
錯誤。 然後我想 - 好的,我可以從函數返回索引並從閉包本身訪問cloned_path
。但是,我能得到編譯的唯一代碼
button_run.connect_clicked(move |_| {
let to_remove: usize = open_dir(&mut cloned_path.borrow_mut().deref_mut());
let x = &*cloned_path.borrow_mut().clone().unwrap().remove(to_remove);
});
它的工作原理,但它的cloned_path
克隆版本中刪除,離開原來的影響。有沒有辦法直接訪問cloned_path
來修改它的內容,如果有,我該如何處理這個任務?