Updating a Value
Part of the Logic & Flow section of Coddy's Rust journey — lesson 32 of 66.
Sometimes you need to update values in a hash map in different ways. You've already learned that .insert() will overwrite an existing value, but what if you only want to add a value when the key doesn't already exist?
Rust provides the .entry() API for more sophisticated value updates. The most useful method in this API is .or_insert(), which only inserts a value if the key is not already present:
let mut scores = HashMap::new();
scores.insert("Alice", 85);
// This will NOT overwrite Alice's score
scores.entry("Alice").or_insert(90);
// This WILL add Bob's score since he's not in the map
scores.entry("Bob").or_insert(90);The .entry() method returns an Entry enum that represents either an occupied or vacant spot in the hash map. When you call .or_insert() on it, it only inserts the new value if the entry is vacant (the key doesn't exist).
Challenge
EasyYou will receive an integer n indicating the number of player names to process. Then you will receive n player names as inputs. Create a hash map to track player scores (type HashMap<String, i32>). For each player name you receive, use .entry() with .or_insert() to add them to the map with an initial score of 100 only if they don't already exist. After processing all names, print each player and their score.
Requirements:
- Import
HashMapfromstd::collections - Create a mutable hash map with types
HashMap<String, i32> - Read the first input and convert it to
i32to get the number of player names - Use a loop to read
nplayer names - For each player name, use
.entry(name).or_insert(100)to add them with a score of100if they're not already in the map - After processing all names, iterate over the hash map and print each player's information in the format:
[name]: [score]
Input:
- First line: An integer
n(e.g.,5) - Next
nlines: Player names (e.g.,Alice,Bob,Alice,Charlie,Bob)
Output:
- One line for each unique player in the format:
[name]: [score] - The order of output lines may vary between test runs
Cheat sheet
The .entry() API provides sophisticated ways to update hash map values. The .or_insert() method only inserts a value if the key doesn't already exist:
let mut scores = HashMap::new();
scores.insert("Alice", 85);
// This will NOT overwrite Alice's score
scores.entry("Alice").or_insert(90);
// This WILL add Bob's score since he's not in the map
scores.entry("Bob").or_insert(90);The .entry() method returns an Entry enum representing either an occupied or vacant spot in the hash map. When you call .or_insert(), it only inserts the new value if the entry is vacant (the key doesn't exist).
Try it yourself
use std::collections::HashMap;
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
// Read the number of player names
let n: i32 = lines.next().unwrap().unwrap().trim().parse().unwrap();
// Create a mutable HashMap to store player scores
let mut player_scores: HashMap<String, i32> = HashMap::new();
// TODO: Write your code below
// Read n player names and use .entry().or_insert(100) to add them to the map
// Print each player and their score in the format: [name]: [score]
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together