简体   繁体   中英

Rust hashmap inside Struct error: cannot move out of xxx which is behind a shared reference

I have the following Rust structure which has a HashMap to children structures.

use std::collections::HashMap;
#[derive(Debug)]

struct Node {
    children: HashMap<i32, Node>,
}

impl Node {
    fn no_immediate_children(&self) -> usize {
        if self.children.is_empty() {
            0
        } else {
            1 + self.children.into_iter().map(|(_, child)| child.no_immediate_children()).sum::<usize>()
        }
    } 
}

I implement no_immediate_children(&self) to find the total number of nodes. However, under self.children , Rust highlights an error because:

cannot move out of `self.children` which is behind a shared reference

move occurs because `self.children` has type `std::collections::HashMap<i32, Node>`, which does not implement the `Copy` trait

I am not sure what is missing. I am new to Rust. I have tried adding &self.children... but still got the same error.

The issue is that .into_iter(self) needs to take ownership of the HashMap, but in your case no_immediate_children(&self) it's behind a referece -> ie &self instead of self ;

You can work around that in two ways, depending on what you want to achieve:

  1. If you want to consume the elements of the hash map and leave it empty after the method invocation:

    • Change the receiver to &mut self
    • Use .drain() instead of .into_iter() :

       self.children.drain().map(|(_, mut v)| v.no_immediate_children()).sum::<usize>() + 1
  2. If you just want to get the sum, but do not want to modify the HashMap:

    • Use .iter() instead of .into_iter() :

       self.children.iter().map(|(_k, v)| v.no_immediate_children()).sum::<usize>() + 1
  3. You want ot consume the whole Node chain:

    • Change the method signature to fn no_immediate_children(self) and use .into_iter() as it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM