gpt4 book ai didi

rust - 结构错误 : cannot borrow data in a "&" reference as mutable 中的 HashMap

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

我有以下代码:

struct Node{
node_map: HashMap<char, Node>,
value: Option<i32>,
}

struct Trie {
root: Node,
}

impl Trie {
fn new() -> Trie {
Trie {
root: Node{
node_map: HashMap::new(),
value: None,
},
}
}

fn find(&self, key: &String) -> Option<&Node> {
// Returning some Option<&Node>
}

fn delete(&mut self, key: &String) -> Option<i32> {
// extract code snippet
let mut search_node = self.find(key);
if search_node.is_some() {
search_node.unwrap().node_map.remove(& 'x');
}
None
}
}

Rust 在 search_node.unwrap().chs 下报错部分:不能将“&”引用中的数据借用为可变

所以我明白 find函数返回 Option<&Node>所以当在上面一行展开时,我得到了对 Node 的引用.

尝试:

  • 我试图通过以下方式解除对节点的引用:*search_node.unwrap().node_map.remove(& 'x');*(search_node.unwrap()).node_map.remove(& 'x');但它仍然会抛出错误。
  • 我关注了另一个答案 here并尝试制作node_map可变的,如:
 struct Node<'a> {
node_map: &'a mut HashMap<char, Node<'a>>,
value: Option<i32>,
}

但后来我在几个地方提示缺乏生命周期。我不知道如何添加的一个特定位置在 new 中功能。

请让我知道如何解决原始问题或如何添加适当的生命周期。

最佳答案

问题是 find 返回一个(可选的)不可变引用,但是您稍后尝试改变它。出于这个原因,您可能想要添加一个带有签名的方法 find_mut

fn find_mut(&mut self, key: &str) -> Option<&mut Node>

(我将 key 参数更改为 &str 因为 it's discouraged to take &String as an argument )

另一个风格上的东西:你应该使用 if let 而不是检查 search_node 是一些然后展开。

if let Some(search_node) = self.find_mut(key) {
search_node.node_map.remove(&'x');
}

关于rust - 结构错误 : cannot borrow data in a "&" reference as mutable 中的 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424116/

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