rustExample of Box Rust HashMap
A HashMap
in Rust is a data structure that stores key-value pairs. It is similar to a Dictionary
in other languages. The HashMap
is implemented using a hash table
, which allows for efficient lookups.
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 newHashMap
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 looks up the value associated with the keyteam_name
in theHashMap
. -
println!("{:?}", score);
- This prints the value associated with the keyteam_name
in 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 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
- How to replace a capture group using Rust regex?
- How to calculate the sum of a Rust slice?
- How do I create an array of strings in Rust?
- How to replace all matches using Rust regex?
- How to use regex to match a double quote in Rust?
- Hashshet example in Rust
- How to use regex captures in Rust?
- How to convert JSON to a struct in Rust?
- How to pop an element from a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
See more codes...