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 implement PartialEq for a Rust HashMap?
- How to use an enum in a Rust HashMap?
- How to create a HashMap of traits in Rust?
- How to get the length of a Rust HashMap?
- How to remove an element from a Rust HashMap if a condition is met?
- How to create a HashMap of pointers in Rust?
- How to create a HashMap of structs in Rust?
- How to create a HashMap of HashMaps in Rust?
- How to sort a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
More of Rust
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to use regex with bytes in Rust?
- How to use regex lookahead in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to match whitespace with a regex in Rust?
See more codes...