Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #295 String to Enum

Given the enumerated type T, create a function TryStrToEnum that takes a string s as input and converts it into an enum value of type T.

Explain whether the conversion is case sensitive or not.
Explain what happens if the conversion fails.

X : T := T'Value (S);
T.values.byName(s);
def try_str_to_enum(t, string), do: t[string]
T x = T.valueOf(s);
function TryEnumToStr(const s: string; out enum: T): Boolean;
var
  code: integer;
begin
  Val(s, enum, code);
  Result := (code = 0);
end;
my %T = ( RED => 1, GREEN => 2, BLUE => 3 );

sub TryStrToEnum { my $s = shift; $T{uc $s} }

print GREEN;  # prints 2
print TryStrToEnum('BLUE');  prints 3

use feature 'say';
use constant { RED => 1, GREEN => 2, BLUE => 3 };

sub TryStrToEnum { eval uc shift }

say GREEN; # prints 2
say TryStrToEnum('BLUE'); # prints 3
t = T[s]
use std::str::FromStr;
enum MyEnum {
    Foo,
    Bar,
    Baz,
}

impl FromStr for MyEnum{
    type Err =  String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "foo" => Ok(MyEnum::Foo),
            "bar" => Ok(MyEnum::Bar),
            "baz" => Ok(MyEnum::Baz),
            _ => Err("Could not convert str to enum".to_string())
        }
    }
}

New implementation...
< >
Bart