Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate over string, and look up each value in a HashMap in Rust?

I would like to take an alphanumeric string, iterate character by character, and lookup each character in a HashMap.

Here is how I would do it in Python:

lookup: dict = {
    'J': 5,
    'H': 17,
    '4': 12
}

s: str = 'JH4'

looked_up: list[str] = [lookup[c] for c in s]
print(looked_up)
[5, 17, 12]

My attempt in Rust

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

use std::collections::HashMap;

fn main()
{

    let lookup: Hashmap<char, u32> = HashMap::from([
        ('J', 5),
        ('H', 17),
        ('4', 12)
    ]);

    let s = String::from("JH4");
    for c in s.chars()
    {
        // Stuck here
        // I would like to look up each character from s via the lookup key and return an array of
        // the values returned.
    }

}

>Solution :

chars() returns an iterator, so you can just map over each element, indexing the map:

use std::collections::HashMap;

fn main() {
    let lookup: HashMap<char, u32> = HashMap::from([
        ('J', 5),
        ('H', 17),
        ('4', 12)
    ]);

    let s = String::from("JH4");

    let looked_up: Vec<_> = s.chars().map(|c| lookup[&c]).collect();
    dbg!(looked_up);
}

This will panic if c is not a key of the map, so you may want to explicitly handle that case instead:

let looked_up: Vec<_> = s.chars().map(
    // return the value from the map, or if none exists,
    // return 0 by default
    |c| lookup.get(&c).unwrap_or(0)
).collect();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading