Skip to content

Instantly share code, notes, and snippets.

@henryobiaraije
Last active February 13, 2023 20:11
Show Gist options
  • Save henryobiaraije/6cc397614e20e0d4f3702b9ce125bc79 to your computer and use it in GitHub Desktop.
Save henryobiaraije/6cc397614e20e0d4f3702b9ce125bc79 to your computer and use it in GitHub Desktop.
Practical example on Using HashMaps in Rust programming language
// Video Tutorial https://youtu.be/nOeOMHtAa2o
// Youtube Channel: Daily Dose of Rust language
use std::collections::HashMap;
fn main() {
// How to create Hashmap in Rust.
let mut student_scores: HashMap<String, f64> = HashMap::new();
// How to assign values to Hashmaps in Rust.
student_scores.insert(String::from("Henry"), 100.0);
student_scores.insert(String::from("John"), 90.0);
// How to insert a value to Hashmaps in Rust (Only when that value does not exist).
student_scores.entry(String::from("John")).or_insert(43.0);
// How to get a value from a hashmap in Rust.
let henry_score = student_scores
.get(&String::from("Henry"))
.copied()
.unwrap_or(0.0);
// How to loop through a Hashmap in Rust language.
for (key, value) in &student_scores {
println!("key = {}, value = {}", key, value);
}
println!("scores = {:?}", student_scores);
println!("Henry's scores = {:?}", henry_score);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment