Start learning free

LESSON 135 OF 293 · DICTIONARIES - CHALLENGES

Phone Book Lookup in Rust: Indexing a HashMap

Practice Read the full explanation

Given a phone book phoneBook, a HashMap from names to phone numbers, and a name, return the phone number of name.

Every name in the phone book is a key, and its value is that person's phone number, a string like "555-0142". The name you look up is always in the phone book.

 

Example 1:

Input: phoneBook = {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"}, name = "Ben"
Output: "555-0199"
Explanation: The key "Ben" maps to "555-0199".

Example 2:

Input: phoneBook = {"Max": "555-0100"}, name = "Max"
Output: "555-0100"
Explanation: The phone book has a single entry, and it is the one we look up.

Example 3:

Input: phoneBook = {"Tom": "555-0111", "Tim": "555-0111"}, name = "Tim"
Output: "555-0111"
Explanation: Tom and Tim share a phone number. We only need the value of the key "Tim".

 

Constraints:

  • phoneBook has at least one entry.
  • name is always a key of phoneBook.
  • Names are single words made of English letters, and they are all different. Two people can share a phone number.
  • Every phone number is a string of three digits, a dash and four digits, like "555-0142".
STEP 1 OF 1
    Ctrl + Enter to check

    RUST · DICTIONARIES - CHALLENGES

    Phone Book Lookup in Rust, explained

    Problem overview

    The function phone_book_lookup receives phone_book, a HashMap<String, String> from names to phone numbers, and a name. It returns that person's number as a String. The name is always a key of the map, and two people may share a number.

    For {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"} and name = "Ben", the answer is "555-0199". When "Tom" and "Tim" both map to "555-0111", looking up "Tim" still just returns the value stored under that key.

    Approach

    A HashMap finds the value for a key directly, without scanning the entries, so the lookup is one expression. Indexing with square brackets, map[&key], reads the value stored under key.

    Two Rust rules shape that expression. The key is passed by reference, because indexing only needs to look at it. And the result can't be moved out of the map, because the map still owns it, so the function returns a copy with clone().

    Step by step

    1. Index the map with &name. The & borrows name instead of moving it.
    2. Call .clone() on the result to get an owned String that the function can return.

    The solution in Rust

    impl Solution {
        fn phone_book_lookup(phone_book: HashMap<String, String>, name: String) -> String {
            return phone_book[&name].clone();
        }
    }
    
    • Why a reference. Indexing a HashMap<String, String> takes a reference to the key type, so the argument is &name, a &String. A bare name doesn't compile.
    • Why clone(). phone_book[&name] is a place inside the map, and moving a String out of it would leave the map with a hole. Without .clone() the compiler refuses with a "cannot move out of index" error. The clone copies the text into a new String.
    • return with a semicolon. This is valid Rust. The idiomatic form drops both and ends the function with the bare expression phone_book[&name].clone().

    Borrowing against moving

    The function owns phone_book and name because both arrive by value. Still, the lookup doesn't consume either of them: &name lends the key for the length of the expression, and the returned clone is a separate string. If you wrote phone_book[name] without the &, the code wouldn't compile, because the map is indexed by a reference to the key. Adding the & is the fix, and it also keeps name usable afterwards. The same holds if you need the number twice in a longer function.

    Edge cases and common mistakes

    • A missing key panics. Indexing a map with a key it doesn't hold stops the program with the message "no entry found for key". The lesson guarantees the name is present, so this can't happen here. When a key might be absent, use get, which returns an Option: phone_book.get("Zed") gives None for a map without that key.
    • Shared numbers. Values don't have to be unique. Only keys are, so two names with the same number don't interfere.
    • Looking up by number. The map goes from names to numbers. Finding a name from a number would need a loop over the entries.

    Testing

    • {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"} with "Ben" gives "555-0199".
    • {"Max": "555-0100"} with "Max" gives "555-0100".
    • {"Tom": "555-0111", "Tim": "555-0111"} with "Tim" gives "555-0111".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free