Maps and Sets
Lesson 23 of 48 in Coddy's Rust for C Developers course.
Rust provides maps and sets in std::collections. A map associates a unique key with a value; inserting an existing key replaces its value. A set keeps unique values and reports whether insertion was new. HashMap and HashSet provide hash-based lookup without a stable iteration order. BTreeMap and BTreeSet keep keys in sorted order, useful when producing deterministic reports. A map's entry(key).or_insert(default) returns a mutable reference to the stored value, allowing counters without a separate lookup and insertion. Unlike a C string pointer table, owned String keys keep their text alive; borrowed keys require the source strings to outlive the collection.
C
#include <stdio.h>
#include <string.h>
struct Entry { const char *key; int value; };
int main(void) {
struct Entry map[] = {{"port", 80}, {"mode", 1}};
for (int i = 0; i < 2; ++i)
if (strcmp(map[i].key, "port") == 0) map[i].value = 443;
const char *set[2] = {"green", "green"};
int distinct = strcmp(set[0], set[1]) == 0 ? 1 : 2;
printf("%d %d\n", map[0].value, distinct);
return 0;
}Rust
use std::collections::{BTreeMap, BTreeSet};
fn main() {
let mut settings = BTreeMap::new();
settings.insert("port", 80);
settings.insert("mode", 1);
settings.insert("port", 443);
let mut colors = BTreeSet::new();
colors.insert("green"); colors.insert("green");
println!("{} {}", settings["port"], colors.len());
}Do not rely on hash-table iteration order when exact output matters. Choose a sorted collection or explicitly sort the results.
Challenge
EasyImplement pub fn frequencies(text: &str) -> BTreeMap<String, usize> and pub fn repeated(text: &str) -> BTreeSet<String> in vocabulary.rs, importing both types from std::collections. Split text on whitespace, compare words case-sensitively and retain punctuation. Frequencies counts every occurrence; repeated contains exactly words whose count is at least two. solve returns repeated words in sorted order as word=count, separated by commas; return none if the set is empty. Both APIs must handle empty input and independent calls with no retained global state.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, vocabulary.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod vocabulary;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
let counts = vocabulary::frequencies("fern oak fern elm oak fern");
assert_eq!(counts.len(), 3);
assert_eq!(counts.get("fern"), Some(&3));
assert_eq!(counts.get("elm"), Some(&1));
assert_eq!(counts.get("missing"), None);
let repeated = vocabulary::repeated("fern oak fern elm oak fern");
assert_eq!(repeated.into_iter().collect::<Vec<_>>(), vec![String::from("fern"), String::from("oak")]);
assert!(vocabulary::frequencies("").is_empty());
assert!(vocabulary::repeated("single").is_empty());
assert_eq!(vocabulary::frequencies("A a").len(), 2);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler