I created a type Space
that has an optional fields lef_neighbor
and right_neighbor
of the same type Space
. Rust needs to know the size of the type at compile time so I wrapped the types in a Box<>
. I now want to create a method that I can call on a Space
that creates the right_neighbor
of this Space
object and assigns it as such. It also needs to set the left_neighbor
field of the new Space
to the old Space
so they can both find each other.
pub struct Space {
left_neighbor: Option<Box<Space>>,
right_neighbor: Option<Box<Space>>,
}
impl Space {
pub fn new() -> Self {
Self {
left_neighbor: None,
right_neighbor: None,
}
}
pub fn create_neigbor(&mut self) {
let neighbor_space = Space::new();
neighbor_space.left_neighbor = Some(Box::new(self));
self.right_neighbor = Some(Box::new(neighbor_space));
}
}
This gives the compile error:
|
16 | neighbor_space.left_neighbor = Some(Box::new(self));
| ^^^^ expected struct `Space`, found `&mut Space`
How do I fix this problem?