rustRust map example
A map
in Rust is a collection of key-value pairs, where each key is unique. It is implemented as a HashMap
, which is a hash table where the keys are hashed and stored in buckets.
Example code
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("key1", "value1");
map.insert("key2", "value2");
println!("{:?}", map);
Output example
{"key1": "value1", "key2": "value2"}
Code explanation
use std::collections::HashMap;
: imports theHashMap
type from thestd::collections
module.let mut map = HashMap::new();
: creates a new emptyHashMap
and stores it in themap
variable.map.insert("key1", "value1");
: inserts a key-value pair into themap
.println!("{:?}", map);
: prints the contents of themap
to the console.
Helpful links
Related
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...