rustRust HashMap example
Rust's HashMap
is a data structure that stores key-value pairs. It is a hash table implementation of the Map
trait.
Example code
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let team_name = String::from("Blue");
let score = scores.get(&team_name);
println!("{:?}", score);
Output example
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
containing the value "Blue" and the value being ani32
containing the value 10. -
let team_name = String::from("Blue");
- This creates aString
containing the value "Blue". -
let score = scores.get(&team_name);
- This retrieves the value associated with the keyteam_name
from theHashMap
. -
println!("{:?}", score);
- This prints the value associated with the keyteam_name
from theHashMap
.
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 use an enum in a Rust HashMap?
- 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 sort a Rust HashMap?
- How to create a HashMap of pointers in Rust?
- How to create a HashMap of structs in Rust?
- How to create a HashMap of traits in Rust?
- How to convert a Rust HashMap to a JSON string?
More of Rust
- How to split a string with Rust regex?
- How to get a capture group using Rust regex?
- How to use regex to match a group in Rust?
- How to replace a capture group using Rust regex?
- How to use captures_iter with regex in Rust?
- How to use regex to match a double quote in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to match the end of a line in a Rust regex?
- How to replace all using regex in Rust?
- How to split a string by regex in Rust?
See more codes...