How to reference parent in child

I'm working on transferring a voxel game to Webassembly with Rust. I started using Rust last week so I'm very new to it. I'm not sure how to solve this issue. I have a "Chunk manager" which contains a hash map of all the loaded chunks. But I need to be able to access the other chunks from any of the chunks. So I figure I'd add a get_chunk function to the manager which returns a reference to a chunk.

If I try to pass the chunk manager reference to the newly created chunk I get an error that it expects a lifetime. But if I add a lifetime I get an error saying it isn't supported by wasm_bindgen.

I tried various solutions I found online with Rc and Refcell but I'm not sure if what would be applicable in this scenario and I'm still running into the same issue regarding lifetime.

If someone could point me in the right direction it would be greatly appreciated!

#[wasm_bindgen]
struct ChunkManager {
    chunks: HashMap<Vector3<i32>, Chunk>
    
}
#[wasm_bindgen]
impl ChunkManager {
    #[wasm_bindgen(constructor)]
    pub fn new() -> ChunkManager {
        ChunkManager {
            chunks: HashMap::new(),
        }
    }
    pub fn add_chunk(&mut self, x: i32, y: i32, z: i32) {
        self.chunks.insert(Vector3::new(x, y, z), Chunk::new(self));
    }
    fn get_chunk(&self, coords:Vector3<i32>) -> Option<&Chunk> {
        self.chunks.get(&coords)
    }

pub struct Chunk {
    chunkManager: &ChunkManager
}

impl Chunk {
    pub fn new(chunkManager:  &mut ChunkManager) -> Chunk {
    Chunk {chunkManager}
    }
}

I would be best to not do that. Rust very strongly prefers data structures without cycles. You can do it with Rc and Weak, but it's cumbersome and error-prone.

Generally, I would strongly recommend trying to rethink your design to be acyclic. Why do you need a reference to the chunk manager? Could the methods that use it be on the chunk manager instead?

Thank you for the advice, I'll give that a shot!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.