remove a key-value pair from a map in rust

To remove a key-value pair from a map in Rust, you can use the remove() method of the HashMap data structure. Here's an example:

main.rs
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();

    map.insert("key1", "value1");
    map.insert("key2", "value2");
    map.insert("key3", "value3");

    println!("Before: {:?}", map); // Before: {"key1": "value1", "key2": "value2", "key3": "value3"}

    map.remove("key2");

    println!("After: {:?}", map); // After: {"key1": "value1", "key3": "value3"}
}
392 chars
16 lines

In this example, we first create a new HashMap and insert three key-value pairs into it. Then, we print the map to the console to see its contents.

Next, we call the remove() method on the map with the key "key2". This removes the key-value pair with that key from the map.

Finally, we print the map again to see that the key-value pair has been successfully removed.

gistlibby LogSnag