gpt4 book ai didi

rust - 如何从闭包内部修改 Rc

转载 作者:行者123 更新时间:2023-11-29 08:30:08 26 4
gpt4 key购买 nike

我试图将 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_pa​​th。但是我唯一可以编译的代码是

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_pa​​th 的克隆版本中删除,而不会影响原始版本。有没有一种方法可以直接访问 cloned_pa​​th 以修改其内容?如果有,我该如何处理此任务?

最佳答案

修改枚举值(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 绑定(bind)限定符 - 这意味着它将是 &mut Vec<PathBuf> 类型,也就是说,对选项内部的可变引用,正是您需要修改向量的内容,以防它存在。

关于rust - 如何从闭包内部修改 Rc<RefCell>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710447/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com