I'm new to Rust and facing the steep learning curve. I am trying to learn how to code certain design patterns using Rust structs that I would normally code as a class in Java or Swift. I am struggling with the correct way to code these. I need help fixing the struct as well as how to call it. I would then like to create a function to traverse the tree and log each node.
Below is one example where I am trying to code a tree/node struct. The Node has a string value, an optional reference to a parent Node, and a vector/list of child nodes. I was unsure as to whether the children should also be references or owned.
struct Node<'a> {
parent: Option<&'a Node<'a>>,
value: String,
children: Vec<&'a Node<'a>>,
}
impl Node<'_> {
pub fn addNode(&self, child: &Node) {
self.children.push(child);
}
}
fn main() {
println!("Tree nodes");
let root = Node {
parent: None,
value: String::from(""),
children: Vec<&Node>::new(),
};
let n1 = Node {
parent: Some(&root),
value: String::from("a"),
};
let n2 = Node {
parent: Some(&n1),
value: String::from("p"),
};
let n3 = Node {
parent: Some(&n2),
value: String::from("ple"),
};
println!("n value is {}", root.value);
println!("n1 value is {}", n1.value);
println!("n2 value is {}", n2.value);
println!("n3 value is {}", n3.value);
}