Is this usage of a vector guaranteed never to re-allocate?

struct AgentCollection {
    available_ids: Vec<AgentId>,
    agents: HashMap<AgentId, Box<dyn EconomicAgent>>
impl AgentCollection {
    fn create_agent(&mut self, f: fn(AgentId) -> Box<dyn EconomicAgent>) -> Option<AgentId> {
        let id = self.available_ids.pop()?;
        let agent = f(id);
        self.agents.insert(id, agent);

    fn destroy_agent(&mut self, agent_id: AgentId) {

    fn new(size:u32) -> AgentCollection {
        AgentCollection{available_ids:(1..size).collect(), agents:HashMap::new()}

available_ids starts with a fixed list of ids. As agents are created they take an id from this list. As agents are destroyed, they return an id to this list. The list will never be bigger than when it was first created, so it is not ever necessary to re-allocate.
Assuming I never call shrink_to_fit or something similar, will this vector remain in the same memory location for the life of my application? Or are there some rules for conserving space baked into the object?

That will never reallocate. Note that you are giving out ids in reverse order, which may or may not matter for your use case.

Or well. If I remove the same ID twice, it could reallocate. You might want to check whether remove found anything.


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.