rustHow to delete an entry from a Rust HashMap?
To delete an entry from a Rust HashMap, the remove method can be used. The remove method takes a key as an argument and returns the value associated with the key if it exists.
Example code
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let blue_score = scores.remove("Blue");
println!("Blue score: {:?}", blue_score);
Output example
Blue score: Some(10)
Code explanation
-
use std::collections::HashMap;: This imports theHashMaptype from thestd::collectionsmodule. -
let mut scores = HashMap::new();: This creates a new emptyHashMapcalledscores. -
scores.insert(String::from("Blue"), 10);: This inserts a key-value pair into theHashMap, with the key being aStringwith the value"Blue"and the value being ani32with the value10. -
let blue_score = scores.remove("Blue");: This removes the key-value pair with the key"Blue"from theHashMapand stores the associated value in the variableblue_score. -
println!("Blue score: {:?}", blue_score);: This prints the value stored inblue_scoreto the console.
Helpful links
Related
- How to remove an element from a Rust HashMap if a condition is met?
- How to print a Rust HashMap?
- How to convert a Rust HashMap to JSON?
- How to create a HashMap of pointers in Rust?
- How to create a HashMap of structs in Rust?
- How to sort a Rust HashMap?
- How to lock a Rust HashMap?
- How to add an entry to a Rust HashMap?
- How to sort the keys in a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
More of Rust
- How to use binary regex in Rust?
- How to map a Rust slice?
- How to compare two Rust HashMaps?
- How to yield a thread in Rust?
- How to make regex case insensitive in Rust?
- How to use regex to match a group in Rust?
- How to match whitespace with a regex in Rust?
- How to use regex lookbehind in Rust?
- How to match digits with regex in Rust?
- How to use regex to match a double quote in Rust?
See more codes...