尝试:不能一次多次借用可变的"_"



我想为Trie实现一些基本方法。

use std::collections::HashMap;
#[derive(Debug)]
struct TrieNode {
chs: HashMap<char, TrieNode>,
value: Option<i32>,
}
#[derive(Debug)]
struct Trie {
root: TrieNode,
}
impl Trie {
fn new() -> Trie {
Trie {
root: TrieNode {
chs: HashMap::new(),
value: None,
},
}
}
fn add_string(&mut self, string: String, value: i32) {
let mut current_node = &mut self.root;
for c in string.chars() {
current_node = current_node.chs.entry(c).or_insert(TrieNode {
chs: HashMap::new(),
value: None,
});
}
current_node.value = Some(value);
}
fn delete(&mut self, key: &String) -> Option<i32> {
if key.is_empty() {
// if key is empty, no need to delete
return None;
}
let mut current_node = &mut self.root;
for (ind, ch) in key.chars().enumerate() {
match current_node.chs.get_mut(&ch) {
Some(node) => {
if ind < key.len() - 1 {
current_node = node;
}
}
None => return None,
}
}
// here current_node is actually the previous node of the deleted node
let temp = current_node.chs.remove(&key.chars().last().unwrap());
match temp {
Some(node) => node.value,
None => None,
}
}
}

方法delete是从Trie中移除一个键,并返回与该键对应的值。然而,我出现了以下错误。

error[E0499]: cannot borrow `current_node.chs` as mutable more than once at a time
--> src/main.rs:118:19
|
118 |             match current_node.chs.get_mut(&ch) {
|                   ^^^^^^^^^^^^^^^^ mutable borrow starts here in previous iteration of loop

我不确定借款检查器在哪里被绊倒,但你可以通过提升if检查来修复它:

let mut current_node = &mut self.root;
for (ind, ch) in key.chars().enumerate() {
if ind < key.len() - 1 {
match current_node.chs.get_mut(&ch) {
Some(node) => {
current_node = node;
}
None => return None,
}
}
}

它甚至跳过检查叶节点是否存在,但您的remove(匹配已经涵盖了这种情况。


此外,ind < key.len() - 1检查假定最后一个字符是ascii。对于您的用例来说,这可能是正确的,但如果不是,您可以使用这个答案来迭代,直到倒数第二个字符。

正如错误消息所解释的,不能一次多次借用可变值(current_node.chs(。

一种解决方案是导出TrieNodeClone特性。Clone是显式复制对象的能力的一个常见特征:

#[derive(Debug, Clone)]
struct TrieNode {
chs: HashMap<char, TrieNode>,
value: Option<i32>,
}

现在不用借用self.root,您可以克隆它:

fn delete(&mut self, key: &String) -> Option<i32> {
if key.is_empty() { 
return None
}
// clone `self.root`
let mut current_node = self.root.clone();
for (ind, ch) in key.chars().enumerate() {
match current_node.chs.get_mut(&ch) {
Some(node) => {
if ind < key.len() - 1 {
// clone `node`
current_node = node.clone();
}
// ...

如果性能是个问题,那么克隆可能不是最好的主意。然而,它仍然是一个选项,可能适合也可能不适合您的用例。

最新更新