Rust HashMap内部结构错误:无法移出共享引用后面的xxx
我有下面的Rust结构,它有一个到子结构的Rust HashMap内部结构错误:无法移出共享引用后面的xxx,rust,Rust,我有下面的Rust结构,它有一个到子结构的HashMap use std::collections::HashMap; #[derive(Debug)] struct Node { children: HashMap<i32, Node>, } impl Node { fn no_children(&self) -> usize { if self.children.is_empty() { 1
HashMap
use std::collections::HashMap;
#[derive(Debug)]
struct Node {
children: HashMap<i32, Node>,
}
impl Node {
fn no_children(&self) -> usize {
if self.children.is_empty() {
1
} else {
1 + self
.children
.into_iter()
.map(|(_, child)| child.no_children())
.sum::<usize>()
}
}
}
我不知道少了什么。我尝试过添加
&self.children…
,但仍然得到了相同的错误。问题是.into iter(self)
需要拥有HashMap
,但在中没有直接的子对象(&self)
HashMap位于引用->后面,即&self
而不是self
您可以通过两种方式解决这一问题,具体取决于您想要实现的目标:
- 将接收器更改为
&mut self
- 使用
而不是.drain()
:.into\u iter()
节点
链:
- 将方法签名更改为
,并按原样使用fn no_immediate_children(self)
李>.into_iter()
问题是,
.into_iter(self)
需要拥有HashMap
的所有权,但在中没有直接子对象(&self)
的HashMap
位于引用->后面,即&self
而不是self
您可以通过两种方式解决这一问题,具体取决于您想要实现的目标:
- 将接收器更改为
&mut self
- 使用
而不是.drain()
:.into\u iter()
节点
链:
- 将方法签名更改为
,并按原样使用fn no_immediate_children(self)
李>.into_iter()
作为旁注,您的
no_immediate_children
递归计算所有子项,而不仅仅是直接子项…@Jmb谢谢,我已经在代码中编辑了它。作为旁注,您的no_immediate_children
递归计算所有子项,而不仅仅是直接子项…@Jmb谢谢,我已经在代码中编辑了它。
self.children.drain().map(|(_, mut v)| v.no_immediate_children()).sum::<usize>() + 1
self.children.iter().map(|(_k, v)| v.no_immediate_children()).sum::<usize>() + 1