Avatar ·

How to iterate over a HashMap, printing key/value, and remove elements in Rust?

Hello everyone! I'm new to Rust and trying to solve a simple problem: I have a `HashMap`, and I want to iterate over all its elements, print the key-value pairs, and then remove some of them based on a condition (e.g., all where the value is less than 10). The problem is that the borrow checker won't let me do this. Here's my code that doesn't compile: ```rust use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert("apple".to_string(), 5); map.insert("banana".to_string(), 15); map.insert("cherry".to_string(), 3); for (key, value) in &map { println!("{}: {}", key, value); if *value < 10 { map.remove(key); // Error! } } } ``` The compiler gives an error: `cannot borrow 'map`