Module lessons (1/2)
Collections and HashMap
Collections are data structures capable of holding multiple values. Unlike the primitive array and tuple types, the data these collections reference is stored on the heap, which means the amount of data does not need to be known at compile time and can grow or shrink dynamically during program execution.
The two most commonly used collections in Rust are vectors (Vec<T>) and key-value maps (HashMap<K, V>).
Vectors (Vec<T>)
Vectors allow you to store more than one value of the same type in a single data structure that puts all values next to each other in memory:
fn main() {
// Creating an empty mutable vector
let mut v: Vec<i32> = Vec::new();
// Or using the vec! macro
let mut v2 = vec![1, 2, 3];
// Appending elements
v.push(5);
v.push(6);
// Accessing elements by index
let third = v2[2];
println!("The third element is: {}", third);
}
HashMap (HashMap<K, V>)
The HashMap<K, V> collection stores a mapping of keys of type K to values of type V. It operates via a hashing function, which determines how these keys and values are placed in memory. It is extremely useful when you want to look up data not by a numeric index, but by a key (such as a name or an ID).
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
// Inserting key-value pair
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
// Reading a value (returns an Option<&V>)
let team_name = String::from("Blue");
let score = scores.get(&team_name);
match score {
Some(val) => println!("Score: {}", val),
None => println!("No score found."),
}
}
Try it yourself
Exercise 1: Basic Operations on Vec
Declare a mutable integer vector named v using Vec::new(). Add the elements 10, 20, and 30 in sequence using the push method. Finally, print the first element of the vector (index 0) using println!.
Show hint
Use `let mut v = Vec::new();` to initialize the vector, insert elements with `v.push(value)` and access with `v[0]`.
Solution available after 3 attempts
Exercise 2: User Scores with HashMap
Import std::collections::HashMap. In the main function, declare a mutable HashMap named scores to store String keys and i32 values. Insert a score of 50 for the user 'Alice'. Safely extract the score using the get method and unwrap() to print it.
Show hint
Do not forget `use std::collections::HashMap;`. Insert with `scores.insert(String::from("Alice"), 50);`and fetch the value with`.get("Alice").unwrap()`.
Solution available after 3 attempts
Exercise 3: Doubling Values in a Vector
Define a function named double_values that accepts a reference to a slice of integers &[i32] and returns a new Vec<i32> containing the same elements multiplied by 2.
Show hint
The function should iterate over the elements of the slice and insert them multiplied by 2 into the new vector to be returned.
Solution available after 3 attempts