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 implement PartialEq for a Rust HashMap?
- How to use a custom hash function with a Rust HashMap?
- How to use a HashBrown with a Rust HashMap?
- How to create a new Rust HashMap with values?
- 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 create a HashMap of pointers in Rust?
- How to create a nested HashMap in Rust?
- How to create a new Rust HashMap with a specific type?
More of Rust
- How to match the end of a line in a Rust regex?
- How to parse JSON string in Rust?
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to replace strings using Rust regex?
- How to get a capture group using Rust regex?
- Hashshet example in Rust
- How to convert a Rust slice of u8 to a string?
See more codes...