Rust HashMap内部结构错误:无法移出共享引用后面的xxx

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

我有下面的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>()
        }
    }
}

我不知道少了什么。我尝试过添加
&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