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 print a Rust HashMap?
- How to compare two Rust HashMaps?
- How to sort the keys in a Rust HashMap?
- How to use a custom hash function with a Rust HashMap?
- How to clear a Rust HashMap?
- How to check if a Rust HashMap contains a key?
- How to build a Rust HashMap from an iterator?
- How to remove an element from a Rust HashMap if a condition is met?
- How to print the keys of a Rust HashMap?
- How to pop an element from a Rust HashMap?
More of Rust
- Yield example in Rust
- How to match whitespace with a regex in Rust?
- Enum as u16 in Rust
- How to replace strings using Rust regex?
- How to use regex lookbehind in Rust?
- Regex example to match multiline string in Rust?
- How to use regex lookahead in Rust?
- How to use captures_iter with regex in Rust?
- How to sort a Rust HashMap?
- How do I add a variable to a string in Rust?
See more codes...