I have this enum:
enum Foo {
Bar,
Baz(String),
// And maybe some other variants
}
I find myself constantly pattern matching against predefined strings of Baz
.
match foo_instance {
Foo::Baz(ref x) => match x.as_str() {
"stuff" => ...,
"anotherstuff" => ...,
},
// Other match cases...
}
Sometimes I only match for one case, sometimes 4-5 cases of Foo::Baz
. In latter situation, a double match
doesn't bother me so much, in fact the grouping makes sense at that point. If I only match against one case of Foo::Baz
it doesn't feel right. What I really want to be able to do is this:
const STUFF: Foo = Foo::Baz("stuff".to_string());
const ANOTHER_STUFF: Foo = Foo::Baz("anotherstuff".to_string());
match foo_instance {
&STUFF => ...,
&ANOTHER_STUFF => ...,
// Other match cases...
}
But of course, because of to_string()
calls, this won't work (and I also need to derive Eq
trait to be able to match against const
s which is odd. That may also be a problem for me.). Is there any way to mimic this? For example, using a macro, can I do something like that:
const STUFF: Foo = magic!(Foo::Baz("stuff".to_string());
const ANOTHER_STUFF: Foo = magic!(Foo::Baz("anotherstuff".to_string()));
// Or any other thing that can mimic top level behavior,
// I may create these constants dynamically at program start, that would work too.
match foo_instance {
another_magic!(STUFF) => ...,
another_magic!(ANOTHER_STUFF) => ...,
// Other match cases...
}
Generally speaking, I want to be able to have some constant variants of an enum that contains an heap allocated data (String
in this case), so that I can reuse them whenever I need in a match
case. What's the best way to deal with this?