Maps in Rust
Maps are Rust’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the HashMap::new
method.
Set key/value pairs using typical name.insert(key, val)
syntax.
Printing a map with e.g. println!
will show all of its key/value pairs.
Get a value for a key with name.get(key)
.
If the key doesn’t exist, the Option::None
is returned.
The len
method returns the number of key/value pairs.
The HashMap::remove
method removes key/value pairs from a map.
Clearing all key/value pairs from a map can be done with the clear
method.
The contains_key
method can be used to check if a key is present in the map.
You can also declare and initialize a new map in the same line with this syntax.
In Rust, you can compare two maps for equality using the ==
operator.
Note that maps appear in the form {"k": v, "k": v}
when printed with println!
.