【发布时间】:2020-02-12 18:37:37
【问题描述】:
我有以下 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...,但仍然出现同样的错误。
【问题讨论】:
-
附带说明,您的
no_immediate_children递归计算所有子项,而不仅仅是直接子项…… -
@Jmb 谢谢,我已经在我的代码中编辑了它。
标签: rust