pouriya/keshvar

What's the best way to check if a string submitted matches any of the Alpha2 codes

emperorjm opened this issue · 2 comments

I want to store the Country's Alpha2 code to a record and therefore the function will accept a string which I want to validate that it exists within the Alpha2 enum. I assume the current search functions currently don't allow for this.

Since Alpha2 implements TryFrom<&str>, You can use the following snippet to check if an input matches an Alpha2 code or not:

let input = "fr".to_string();  // A correct alpha2 code
assert!(Alpha2::try_from(input.as_str()).is_ok());

let input = "rf".to_string();  // An invalid alpha2 code
assert!(Alpha2::try_from(input.as_str()).is_err());

Note that if you do not include some countries (by changing keshvar's default cargo features), You may get errors for correct Alpha2 codes too!
For example in the following Cargo.toml I only include countries of Asia region:

# ...
[dependencies]
# ...
keshvar = {version = "...", default-features = false, features = ["asia"]}
# ...

And I will get error if I try to convert fr (France) to Alpha2:

let input = "fr".to_string();
assert!(Alpha2::try_from(input.as_str()).is_err());

Thank you very much. Your suggestion worked perfectly.