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 theHashMap
type from thestd::collections
module. -
let mut scores = HashMap::new();
: This creates a new emptyHashMap
calledscores
. -
scores.insert(String::from("Blue"), 10);
: This inserts a key-value pair into theHashMap
, with the key being aString
with the value"Blue"
and the value being ani32
with the value10
. -
let blue_score = scores.remove("Blue");
: This removes the key-value pair with the key"Blue"
from theHashMap
and stores the associated value in the variableblue_score
. -
println!("Blue score: {:?}", blue_score);
: This prints the value stored inblue_score
to the console.
Helpful links
Related
- How to use a tuple as a key in a Rust HashMap?
- How to implement PartialEq for a Rust HashMap?
- How to get the length of a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to sort the keys in a Rust HashMap?
- How to use a custom hash function with a Rust HashMap?
- How to create a HashMap of structs in Rust?
- How to create a HashMap of traits in Rust?
- How to create a HashMap of HashMaps in Rust?
More of Rust
- Hashshet example in Rust
- How to convert Rust bytes to hex?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to get the last element of a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
- How to match the end of a line in a Rust regex?
- How to escape dots with regex in Rust?
- How to use regex to match a group in Rust?
See more codes...