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

问题描述 投票:-1回答: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>()
        }
    }
}

我实施了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...,但仍然遇到相同的错误。

rust
1个回答
2
投票

[问题是.into_iter(self)需要拥有HashMap的所有权,但在no_immediate_children(&self)中,HashMap后面是引用->即&self而不是self;]]

您可以通过两种方式解决此问题,具体取决于要实现的目标:

  1. 如果要使用哈希映射的元素,并在方法调用后将其保留为空:

© www.soinside.com 2019 - 2024. All rights reserved.