【发布时间】:2018-09-19 09:32:35
【问题描述】:
我正在用 Rust 编写一个 Trie 数据结构来实现 Aho-Corasick 算法。 TrieNode 结构体代表一个节点,如下所示:
use std::collections::{HashMap, HashSet, VecDeque};
struct TrieNode {
next_ids: HashMap<char, usize>,
kw_indices: HashSet<usize>,
fail_id: Option<usize>,
}
我使用与世代竞技场相同的策略来实现 trie,其中所有节点都存储在一个 Vec 中,并使用它们的索引相互引用。在创建所有节点后构建自动机时,我试图在不使用 clone() 方法的情况下使以下代码工作:
fn build_ac_automaton(nodes: &mut Vec<TrieNode>) {
let mut q = VecDeque::new();
for &i in nodes[0].next_ids.values() {
q.push_back(i);
nodes[i].fail_id = Some(0);
}
// ...
}
但是借用检查员对此并不满意:
error[E0502]: cannot borrow `*nodes` as mutable because it is also borrowed as immutable
|
| for &i in nodes[0].next_ids.values() {
| ----- - immutable borrow ends here
| |
| immutable borrow occurs here
| q.push_back(i);
| nodes[i].fail_id = Some(0);
| ^^^^^ mutable borrow occurs here
在不使用昂贵的clone() 方法的情况下,还有什么方法(如果有的话)可以实现上述目标?
【问题讨论】:
-
现有的aho-corasick crate。
-
相信Efficiently mutate a vector while also iterating over the same vector的答案已经回答了你的问题; Is there an elegant solution to modifying a structure while iterating?; How do I modify a container while iterating over it? 和更多。如果您不同意,请edit您的问题解释差异。否则,我们可以将此问题标记为已回答。
标签: rust borrow-checker