I'm trying to create a chain of struct instances, like this:
Struct_instance_a:
id:1
prev:None
Struct_instance_b:
id:2
prev:Struct_instance_a
etc..
But getting this error from the compiler:
error[E0382]: borrow of moved value: `a`
error[E0382]: borrow of moved value: `a`
--> src/main.rs:31:9
|
28 | let a = crate::Node::new(None, 1);
| - move occurs because `a` has type `Node`, which does not implement the `Copy` trait
29 | let b=crate::Node::new(Some(a), 2);
| - value moved here
30 |
31 | assert_eq!(a.id, b.prev.unwrap().id);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
This is my code snippet:
fn main() {
println!("hello");
}
pub struct Node {
prev: Option<Box<Node>>,
id: u64,
}
impl Node {
fn new(prev: Option<Node>, id:u64) -> Node {
Node {
prev: match prev {
None => None,
Some(prev) => Some(Box::new(prev))
},
id
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_children() {
let a = crate::Node::new(None, 1);
let b = crate::Node::new(Some(a), 2);
assert_eq!(a.id, b.prev.unwrap().id);
}
}
I'm new to Rust and trying to understand why this doesn't work. So far I've read about ownership and borrowing and lifetimes and tried a few combinations of those. It feels like I'm close to the solution but missing some fundamental piece of knowledge yet.