此问题已经在这里有了答案:
我具有以下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
} else {
1 + self
.children
.into_iter()
.map(|(_, child)| child.no_children())
.sum::<usize>()
}
}
}
我实施了no_children(&self)
以查找节点总数。但是,在self.children
下,Rust突出显示了一个错误,因为:
error[E0507]: cannot move out of `self.children` which is behind a shared reference
--> src/lib.rs:13:17
|
13 | 1 + self
| _________________^
14 | | .children
| |_________________________^ move occurs because `self.children` has type `std::collections::HashMap<i32, Node>`, which does not implement the `Copy` trait
我不确定缺少什么。我尝试添加&self.children...
,但仍然遇到相同的错误。
[问题是.into_iter(self)
需要拥有HashMap
的所有权,但在no_immediate_children(&self)
中,HashMap
后面是引用->即&self
而不是self
;]]
您可以通过两种方式解决此问题,具体取决于要实现的目标:
如果要使用哈希映射的元素,并在方法调用后将其保留为空: