This post shows Rust HashMap basic examples, particularly for beginners. A map is a type of data structure that allows us to store key-value pair data. We may have learned it from other programming languages like Java. In Rust, the HashMap struct represents and implements the concept of a map.
Declare a Rust HashMap Example
Creating a map in Rust is easy using HashMap. Consider the following line of codes.
1 | let mut course_student_map: HashMap<String, String> = HashMap::new(); |
Like other Rust collections, HashMap allows us to use generics to define the key and value types. The Rust codes create a HashMap with String key-value pair data in our example. Then, we can use the following codes to put data into the map.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | course_student_map.insert( "CS-214".to_string(), "Karl".to_string(), ); course_student_map.insert( "CS-215".to_string(), "Keane".to_string(), ); course_student_map.insert( "CS-216".to_string(), "Kyler".to_string(), ); |
The Rust codes insert the course name as a key and the student name enrolled in that course. Meanwhile, if we want to store numeric course IDs instead of course names, we can do so as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | let mut course_student_map: HashMap<i32, String> = HashMap::new(); course_student_map.insert( 214, "Karl".to_string(), ); course_student_map.insert( 215, "Keane".to_string(), ); course_student_map.insert( 216, "Kyler".to_string(), ); |
Notice we adjusted the Rust HashMap declaration in our example and used the i32 type for the key but kept the String type for the student name. To retrieve a value from a Rust HashMap, we can use either one of the following functions.
1 2 3 | // Option1: Get an immutable value from Rust HashMap let option1:Option<&String> = course_student_map.get(&216); println!("{}", option.unwrap()); // Displays "kyler" |
1 2 3 | // Option 2: Get a mutable value from Rust HashMap let option:Option<&mut String> = course_student_map.get_mut(&216); println!("{}", option.unwrap()); // Displays "kyler" |
1 2 3 4 | // Option 3: Get a mutable value from Rust HashMap let option:Option<(&i32, &String)> = course_student_map.get_key_value(&216); let (key, val) = option.unwrap(); println!("{} {}", key, val); // Displays "216 Kyler" |
Custom Key For Rust Map Using Struct
In some situations, we may want a custom key for our Rust Map instead of using i32, String, or other Rust’s default data types. We can do so by creating structs. Let’s suppose that now we identify any course by its ID and country code. Instead of just the ID alone, we throw in a country code and name the key as “course identity.”
Consider the following struct definition. Notice we use the #[derive] to implement those Rust traits – Eq, Hash, PartialEq.
1 2 3 4 5 | #[derive(Eq, Hash, PartialEq)] struct course_identity { id: i32, country_code: String, } |
Then, we need to modify our codes as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | let mut course_student_map: HashMap<course_identity, String> = HashMap::new(); course_student_map.insert( course_identity {id: 200, country_code: String::from("PH")}, "Karl".to_string(), ); course_student_map.insert( course_identity {id: 200, country_code: String::from("MY")}, "Keane".to_string(), ); course_student_map.insert( course_identity {id: 200, country_code: String::from("ID")}, "Kyler".to_string(), ); let option:Option<&String> = course_student_map.get(&course_identity {id: 200, country_code: String::from("ID")}); println!("{}",option.unwrap()); |
Loop Through Rust Map
To loop through the Rust HashMap key-value pairs, we need the map’s iterator, and we can get that using either one of these functions – iter(), iter_mut(), and into_iter().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // course_student_map.iter(); for (id, name) in course_student_map.iter() { println!("{} {} {}", id.id, id.country_code, name) } // course_student_map.iter_mut(); for (id, name) in course_student_map.iter_mut() { println!("{} {} {}", id.id, id.country_code, name) } // course_student_map.into_iter for (id, name) in course_student_map.into_iter() { println!("{} {} {}", id.id, id.country_code, name) } |
We can also retrieve just the keys instead of the key-value pairs.
1 2 3 4 5 6 7 8 | for key in course_student_map.keys() { println!("{} {}", key.id, key.country_code) } // Displays the following: // 200 MY // 200 PH // 200 ID |
Or just the values!
1 2 3 4 5 6 7 | for val in course_student_map.values() { println!("{}", val); } // Displays the following: // Keane // Karl // Kyler |
There you go! By the way, we tested the Rust HashMap example codes using Rust 1.59.0.