79191448

Date: 2024-11-15 07:43:34
Score: 1.5
Natty:
Report link

While the accepted answer using or_insert_with() ( https://stackoverflow.com/a/73801683/8535397 ) is more idiomatic in most cases, the answer using match map.entry() and into_mut() ( https://stackoverflow.com/a/73805068/8535397 ) was what helped me, and I wanted to write this as an answer because I think there is a specific case where the match is more useful, and I want this to be easily found in the future.

Specifically, using a match allows you to do an early return (or break) within the match statement, useful for example if insertion can fail, and you want to pass the error to the caller, and also allows you to use the question mark ? operator ( https://doc.rust-lang.org/rust-by-example/std/result/question_mark.html ). Inverting the example:

use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::num::ParseIntError;

fn get_parsed(
    number_text: String,
    cache: &mut HashMap<String, u32>
) -> Result<&mut u32, ParseIntError> {
    let parsed = match cache.entry(number_text) {
        Entry::Occupied(entry) => entry.into_mut(),
        Entry::Vacant(entry) => {
            // imagine this is an expensive operation that can fail
            let parsed: u32 = entry.key().parse()?;
            entry.insert(parsed)
        }
    };
    Ok(parsed)
}
Reasons:
  • Blacklisted phrase (1): stackoverflow
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: Tigregalis