Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
X : T := T'Value (S);
using namespace std::literals;
enum T {
case_0,
case_1,
case_2,
case_4 = 4
};
std::optional<T> TryStrToEnum(std::string_view s) {
if (str == "case_0"sv) return case_0;
if (str == "case_1"sv) return case_1;
if (str == "case_2"sv) return case_2;
if (str == "case_4"sv) return case_4;
return std::nullopt;
}
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
t = T[s]
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())
}
}
}