How to Propagate Errors in a Closure Used with entry().or_insert_with_key()?

I'm working on a function that uses HashMap::entry().or_insert_with_key() , and I want to propagate errors from the closure when the function returns a Result .
Here's a simplified version of my current code:

fn get_content(&mut self, file: &Path) -> Result<String> {      
    self.map.entry(file.to_owned()).or_insert_with_key(|key| {  
        // How can I return an error from this closure?
        let file = fs::read_to_string(path)?;
        
        // More potentially fallible operations  
    })
    // ...
}

What's the recommended pattern for this scenario? I'd appreciate any insights or example solutions.

match the return value of map.entry instead of using or_insert_with_key.

2 Likes

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.