Complete these tasks to reinforce what you learned in this module.
Create a Vec<i32> with values 10, 20, 30 (use vec![]). Compute the sum of the elements using a for loop and print it.
vec![] macro to create the vector. Iterate by reference so you don’t move the vector; the theory shows how to loop over a collection.// Task 1: Vec and sum. See tasks/TASKS.md.
fn main() {
todo!("Create vec![10,20,30], sum, print sum = 60");
}
Create a HashMap<&str, i32> and insert keys "a" -> 1, "b" -> 2, "c" -> 3. Look up the value for "b" and print it (handle the Option with unwrap or expect for this task).
HashMap is in std::collections. Use .insert() for each pair; .get() returns an Option, so you need to handle that (e.g. unwrap for this task).// Task 2: HashMap. See tasks/TASKS.md.
fn main() {
todo!("Create HashMap, insert a,b,c, get b and print");
}
Implement fn word_count(text: &str) -> HashMap<String, usize> that returns how many times each whitespace-separated word appears. This task is graded by hidden tests (counts, the number of distinct keys, and the empty-input case).
text.split_whitespace() and use the entry upsert idiom: *counts.entry(word.to_string()).or_insert(0) += 1;.// Task 3: implement word_count, graded by HIDDEN tests. See tasks/TASKS.md.
use std::collections::HashMap;
fn word_count(text: &str) -> HashMap<String, usize> {
todo!("count each whitespace-separated word with the entry() upsert idiom");
}
fn main() {
let counts = word_count("a b a");
println!("a = {}", counts.get("a").copied().unwrap_or(0));
}