I’m a complete beginner in Rust. In order to learn the language I’m working on a project to convert an a-life simulation I wrote in C to Rust.
In this program, a bunch of entities move around a sparse 2-dimensional array eating smaller entities and try to avoid being eaten by larger ones. If they do well they spawn new entities. If they don’t, they die.
In the Rust version, I’ve implemented the sparse array as a vector of structs wrapped in a Option. The empty cells all point to a single None value, the rest move around the vector consuming any lower level entities they encounter. In Rust terms, all these entities have the same scope and lifetime, but in terms of the program they don’t. Only the successful ones persist.
The problem is, I can’t figure out how to delete “dead” entities. I can overwrite them by assigning a None to the same index, but what happens the original entity? I assume that it creates a memory leak. The vector element now points to a different location, but the memory allocated to the now dead entity stills holds that data. We just don’t have the pointer anymore. As the program runs, it is expected that there will be lots of dead entities that need to be cleared off, so I need a reliable way to free the memory they used.
I’ve created a gist that demonstrates a simplified version of my project. Is there a way to free the dead entities before reallocating the vector element, or is my approach to this problem flawed?