[英]How can I update a mutable reference in a rust loop?
I'm trying to implement a Trie/Prefix Tree in Rust and I'm having trouble with the borrow checker.我正在尝试在 Rust 中实现 Trie/前缀树,但借用检查器遇到问题。 Here is my implementation so far and I'm getting an error when I call children.insert.
到目前为止,这是我的实现,当我调用 children.insert 时出现错误。
cannot borrow
*children
as mutable because it is also borrowed as immutable不能将
*children
借用为可变的,因为它也被借用为不可变的
use std::collections::HashMap;
#[derive(Clone, Debug)]
struct PrefixTree {
value: String,
children: HashMap<char, PrefixTree>
}
fn insert(mut tree: &mut PrefixTree, key: &str, value: String) {
let mut children = &mut tree.children;
for c in key.chars() {
if !children.contains_key(&c) {
children.insert(c, PrefixTree {
value: String::from(&value),
children: HashMap::new()
});
}
let subtree = children.get(&c);
match subtree {
Some(s) => {
children = &mut s.children;
},
_ => {}
}
}
tree.value = value;
}
fn main() {
let mut trie = PrefixTree {
value: String::new(),
children: HashMap::new()
};
let words = vec!["Abc", "Abca"];
for word in words.iter() {
insert(&mut trie, word, String::from("TEST"));
}
println!("{:#?}", trie);
}
I think this problem is related to Retrieve a mutable reference to a tree value but in my case I need to update the mutable reference and continue looping.我认为这个问题与检索对树值的可变引用有关,但在我的情况下,我需要更新可变引用并继续循环。 I understand why I'm getting the error since I'm borrowing a mutable reference twice, but I'm stumped about how to rewrite this so I'm not doing it that way.
我理解为什么会出现错误,因为我两次借用了可变引用,但我对如何重写它感到困惑,所以我没有那样做。
When you're doing multiple things with a single key (like find or insert and get) and run into borrow trouble, try using the Entry
API (via .entry()
):当您使用单个键(如查找或插入和获取)执行多项操作并遇到借用问题时,请尝试使用
Entry
API(通过 .entry .entry()
):
fn insert(mut tree: &mut PrefixTree, key: &str, value: String) {
let mut children = &mut tree.children;
for c in key.chars() {
let tree = children.entry(c).or_insert_with(|| PrefixTree {
value: String::from(&value),
children: HashMap::new(),
});
children = &mut tree.children;
}
tree.value = value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.