Accessing Values
Part of the Logic & Flow section of Coddy's Rust journey — lesson 30 of 66.
Once you have data stored in your hash map, you'll need a way to retrieve it. The .get() method allows you to look up a value using its key:
let value = my_map.get("some_key");However, there's an important detail to understand: .get() doesn't directly return the value. Instead, it returns an Option type — a built-in Rust type that represents either a value being present (Some) or absent (None). This is because the key you're looking for might not exist in the hash map.
When the key exists, .get() returns Some(&value) - notice the & symbol, which means you get a reference to the value. When the key doesn't exist, it returns None:
match capitals.get("France") {
Some(capital) => println!("The capital is {}", capital),
None => println!("Country not found"),
}In the Some(capital) match arm, Rust automatically handles the reference for you — capital here is bound to the inner referenced value, so you don't need to write & explicitly in the pattern.
This design prevents your program from crashing when you try to access a key that doesn't exist. Instead of causing an error, Rust forces you to handle both possibilities - finding the value or not finding it - making your code more robust and predictable.
Challenge
EasyYou will receive two inputs: a country name and a capital city name. Create a hash map that stores country names as keys (type String) and their capital cities as values (type String). Insert the country and its capital into the hash map. Then, you will receive a third input with another country name to look up. Use the .get() method to retrieve the capital for this country and handle both cases: when the country exists in the map and when it doesn't.
Note: .get() returns an Option — either Some(&value) (a reference to the value) when the key exists, or None when it doesn't. In a match arm, you can write Some(capital) and Rust will automatically handle the reference for you, so you can use capital directly in your print statement.
Requirements:
- Import
HashMapfromstd::collections - Create a mutable hash map with types
HashMap<String, String> - Read the first input as the country name
- Read the second input as the capital city name
- Insert the country and capital into the hash map
- Read the third input as the country to look up
- Use
.get()to retrieve the capital for the lookup country - Use
matchto handle theOptionreturned by.get() - If the country is found, print:
The capital of [country] is [capital] - If the country is not found, print:
[country] not found in the map
Input:
- First line: Country name to insert (e.g.,
France) - Second line: Capital city name (e.g.,
Paris) - Third line: Country name to look up (e.g.,
FranceorGermany)
Output:
- If the lookup country exists:
The capital of [country] is [capital] - If the lookup country doesn't exist:
[country] not found in the map
Cheat sheet
The .get() method retrieves a value from a hash map using its key:
let value = my_map.get("some_key");The .get() method returns an Option type because the key might not exist in the hash map:
- When the key exists: returns
Some(&value)(a reference to the value) - When the key doesn't exist: returns
None
Use match to handle both cases:
match capitals.get("France") {
Some(capital) => println!("The capital is {}", capital),
None => println!("Country not found"),
}This design prevents crashes when accessing non-existent keys by forcing you to handle both possibilities.
Try it yourself
use std::collections::HashMap;
use std::io;
fn main() {
// Read the country name to insert
let mut country = String::new();
io::stdin().read_line(&mut country).expect("Failed to read line");
let country = country.trim().to_string();
// Read the capital city name
let mut capital = String::new();
io::stdin().read_line(&mut capital).expect("Failed to read line");
let capital = capital.trim().to_string();
// Read the country name to look up
let mut lookup_country = String::new();
io::stdin().read_line(&mut lookup_country).expect("Failed to read line");
let lookup_country = lookup_country.trim().to_string();
// TODO: Write your code below
// Create a HashMap, insert the country and capital, then look up the country
}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