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:
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)