Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use self in a for loop in Rust

I am pretty new to Rust and just starting doing a little "compiler" and after having used the pointer system I encountered a problem with the move system:

for constraint in constraints {
    self.get_or_create_node(constraint.0.to_string(), 0, &constraint.1);
}

This system uses a recursive function which create a tree for a path that I call a constraint but I use Strings to name my nodes so my struct cannot be copied. So the self in the loop throws a move error, how could I prevent it?

Edit here’s the get_or_create_node method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fn get_or_create_node(mut self, node_name: String, current_level: i32, value: &String) {
    let path: Vec<&str> = node_name.split('.').collect();
    if current_level + 1 == path.len().try_into().unwrap() {
        self.value = value.to_string();
    } else {
        for node in self.nodes {
            if path.get(current_level as usize).expect("Path in if statement is false") == &node.value.as_str() {
                node.get_or_create_node(node_name.clone(), current_level + 1, value);
            }
        }
    }
}

>Solution :

As I mentioned in the comments, you’re taking self by value (hence taking ownership) when you really don’t need it. Take a &mut self argument instead.

fn get_or_create_node(&mut self, node_name: String, current_level: i32, value: &String)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading