I am learining rust and as an exercise i wanted to implement simple graph dfs and bfs. However i completly stucked with "cannot move out of borrowed content"
error.
This is what i already have, it failes inside Iterator implementation
struct Node<T> {
value: T,
neighbors: Vec<Node<T>>,
}
impl <T> Node<T> {
fn new(value: T) -> Node<T> {
Node { value, neighbors: Vec::new() }
}
fn add_neighbor(&mut self, node: Node<T>) {
self.neighbors.push(node)
}
}
struct Dfs<T> {
root: Node<T>,
queue: Vec<Node<T>>
}
impl <T> Dfs<T> {
fn new(root: Node<T>) -> Dfs<T> {
Dfs { root, queue: Vec::new() }
}
}
impl <T> Iterator for Dfs<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
let current = &mut self.root;
match current.neighbors.split_first_mut() {
Some((head, _tail)) => {
self.root = *head;
Some(current.value)
}
_ => None
}
}
}
fn main() {
let mut a = Node::new(1);
let mut b = Node::new(2);
let mut c = Node::new(3);
let d = Node::new(4);
let e = Node::new(5);
let f = Node::new(6);
b.add_neighbor(d);
a.add_neighbor(b);
c.add_neighbor(e);
c.add_neighbor(f);
a.add_neighbor(c);
let mut dfs = Dfs::new(a);
while let Some(value) = dfs.next() {
println!("{}", value);
}
}