How to Lookup a Value from a HashMap and Create One If not Present

Hi again. First of all, thank you so much for all your help. Everybody is really friendly here.

I have quite a simple question, I believe. This is a common pattern: I need to lookup a value in a HashMap and return it; if it does not exist, I will need to create one and return the created one. However, I am running into an obvious lifetime issue here:

    // Check whether there is already a HashMap for the entity's type
    let instance_map = match self.e_types.get(&entity.e_type()) {
        Some(i) => i,
        None => {
            // ...and if not, create one
            let i = HashMap::new();
            let key = entity.e_type().clone();
            self.e_types.insert(key, i);
            // &i -- Interesting; this does not compile as i gets dropped at the end of the block
            self.e_types.get(&entity.e_type()).unwrap() // -- this seems costly/silly
        }
    };

Naturally, i gets dropped at the end of the block. I could look up the value from the HashMap again, this time knowing that it does exist, but that seems costly and somewhat silly. What is the idiomatic way of doing this?

You are looking for the entry API I believe:

Looks like I do. Thank you!

    // Check whether there is already a HashMap for the entity's type...
    let instance_map = self
        .e_types
        .entry(entity.e_type().clone())
        // and create a new one if not
        .or_insert(HashMap::new());

.or_default()

...ah, yes. That is even shorter. I guess the outcome is the same.

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.