Home > Software engineering >  Handling Missing Key via HashMap in Rust
Handling Missing Key via HashMap in Rust

Time:09-12

I am trying to decode an alphanumeric string using this HashMap table. I create an iterator using .chars() and then map each result to the HashMap. However, if a character in my string is numeric, I want to return it's value (since it wouldn't be found in the HashMap, which only decodes alphabetical characters). I am trying to handle it using .unwrap_or() but not sure the best way to make the character reference into a u32 within the same line.

Example string below: "4S3BJ" Desired Result: [4,2,3,2,1]

use std::collections::HashMap;


fn main() {

    let translit: HashMap<char, u32> = HashMap::from([
        ('A', 1),
        ('B', 2),
        ('C', 3),
        ('D', 4),
        ('E', 5),
        ('F', 6),
        ('G', 7),
        ('H', 8),
        ('J', 1),
        ('K', 2),
        ('L', 3),
        ('M', 4),
        ('N', 5),
        ('P', 7),
        ('R', 9),
        ('S', 2),
        ('T', 3),
        ('U', 4),
        ('V', 5),
        ('W', 6),
        ('X', 7),
        ('Y', 8),
        ('Z', 9)
    ]);
    let s = String::from("4S3BJ");

    // Goal is to take characters from s and transliterate the characters to u32
    let transliterated: Vec<u32> = s.chars()
                                    .map(|c| *translit.get(&c).unwrap_or(&0))
                                    .collect();

    dbg!(transliterated);

}

CodePudding user response:

let transliterated: Option<Vec<u32>> = s.chars()
                                .map(|c|  translit.get(&c).cloned().or_else(|| c.to_digit(10) ))
                                .collect();

It will return None if input string contains characters that are not in the map or are not digits. If you want to return default value you can use unwrap_or

  • Related