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 convert the keys of a Rust HashMap to a vector?
- How to use a custom hash function with a Rust HashMap?
- How to clone a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to use an enum in a Rust HashMap?
- How to compare two Rust HashMaps?
- How to clear a Rust HashMap?
- How to get a reference to a key in a Rust HashMap?
- How to get all values from a Rust HashMap?
- How to convert a Rust HashMap to JSON?
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace all matches using Rust regex?
- How to get pointer address in Rust
- How to replace strings using Rust regex?
- How to create pointer in Rust
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
- How to parse a file with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to create a Rust regex from a string?
See more codes...