Collections Recap
Lesson 24 of 48 in Coddy's Rust for Go Developers course.
Challenge
EasyImplement pub fn add(stock: &mut BTreeMap<String, usize>, name: &str) and pub fn remove(stock: &mut BTreeMap<String, usize>, name: &str) -> bool in stock.rs. Add increases a name's count, inserting one when absent. Remove returns false without changing anything if absent; otherwise decrement and return true, removing the key when its count reaches zero. Valid stock maps contain only positive counts. Input has zero or more lines, each +name or -name; names are nonempty, contain no whitespace, and may contain Unicode. solve starts with empty stock, applies commands in order and returns removed|entries, where removed counts successful removals and entries are sorted name=count pairs joined with commas. Use empty for no entries.
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, stock.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 stock;
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 mut items = std::collections::BTreeMap::new();
stock::add(&mut items, "bolt"); stock::add(&mut items, "bolt");
stock::add(&mut items, "nut");
let unchanged = items.clone();
assert!(!stock::remove(&mut items, "absent"));
assert_eq!(items, unchanged);
assert!(stock::remove(&mut items, "bolt"));
assert_eq!(items.get("bolt"), Some(&1));
assert!(stock::remove(&mut items, "bolt"));
assert!(!items.contains_key("bolt"));
assert!(!stock::remove(&mut items, "bolt"));
assert_eq!(items.get("nut"), Some(&1));
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
All lessons in Rust for Go 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