Rust 闭包会改变捕获的变量

问题描述 投票:0回答:1

我正在尝试编写一个将图形转换为非循环的函数。我在 Python 中运行这段代码,它使用

dfs
函数,该函数需要两个函数:一个在访问节点之前运行,另一个在访问节点之后运行。这在 Python 中运行得很好,我希望在 rust 中也能有相同的界面。

我目前拥有的代码是:

    fn make_acyclic (
        &self,
    ) -> Graph<E> {
        let mut dag_nodes = HashMap::new();
        let mut finish_times = HashMap::new();
        let mut t = 0;

        let pre_fn = |node: &E| {
            t += 1;
            dag_nodes.insert(node, node.clone());
        };

        let post_fn = |node: &E| {
            t += 1;
            finish_times.insert(node, t);
        };

        let mut visited = HashSet::new();
        self.dfs_from(&self.root, &mut visited, Some(&pre_fn), Some(&post_fn));
        ...

借用检查器抱怨我借用

t
两次是可变的。我怎样才能让它发挥作用?

rust borrow-checker
1个回答
0
投票

所以你非常肯定正在借用

t
作为可变两次 - 你有两个东西存储对
t
的可变引用,如果我理解的话,这将以交错的方式改变它。

我认为你会想要使用

Rc<Refcell<usize>>
Arc<Mutex<usize>>
- 前者可能足以满足你的情况(听起来不像你有任何线程的东西),但我通常只是默认为
Arc<Mutex>>
.

© www.soinside.com 2019 - 2024. All rights reserved.