[英]How do I modify Rc<RefCell> from inside the closure?
我试图将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
来修改其内容,如果有,我该如何执行此任务?
修改枚举值(而Option
为枚举)内容的主要方法是模式匹配:
fn do_something(path_two: &mut Option<Vec<PathBuf>>) {
if let Some(ref mut paths) = *path_two {
paths.push(Path::new("abcde").to_path_buf());
}
}
请注意, paths
模式变量与ref mut
限定符绑定-这意味着它将为&mut Vec<PathBuf>
,即对选项内部的可变引用,正是您需要修改矢量的情况它存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.