How to get the country name from the 2-letter country code (alpha-2) in Rust

1 Answer

0 votes
/*
    get_country_name
    Receives a 2‑letter ISO country code and returns the
    corresponding country name.

    Uses a HashMap for O(1) lookups.
    Input is normalized to uppercase to ensure consistent matching.
    Returns None if the code is not found.
*/
fn get_country_name(alpha2: &str) -> Option<&'static str> {
    // Static lookup table; extend as needed
    static COUNTRY_MAP: phf::Map<&'static str, &'static str> = phf::phf_map! {
        "CA" => "Canada",
        "CN" => "China",
        "DE" => "Germany",
        "FR" => "France",
        "GB" => "United Kingdom",
        "KR" => "South Korea",
        "IN" => "India",
        "JP" => "Japan",
        "US" => "United States",
    };

    // Normalize input
    let code = alpha2.trim().to_uppercase();

    // Lookup
    COUNTRY_MAP.get(code.as_str()).copied()
}

/*
    main
    Demonstrates the lookup function with several sample codes.
*/
fn main() {
    let codes = ["US", "GB", "FR", "JP", "ZZ"]; // ZZ is intentionally invalid

    for code in &codes {
        match get_country_name(code) {
            Some(name) => println!("{code} → {name}"),
            None => println!("{code} → (invalid code)"),
        }
    }
}


/*
run:

US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)

*/

 



answered Sep 19 by avibootz
...